File tree Expand file tree Collapse file tree 2 files changed +43
-20
lines changed Expand file tree Collapse file tree 2 files changed +43
-20
lines changed Original file line number Diff line number Diff line change 1
1
name =ESP32_BleSerial
2
- version =1.0.2
2
+ version =1.0.4
3
3
author =Avinab Malla <
[email protected] >
4
4
maintainer =Avinab Malla <
[email protected] >
5
5
sentence = A BLE Serial library for Arduino ESP32
Original file line number Diff line number Diff line change
1
+ // Thread safe ring buffer
1
2
#pragma once
2
3
#include < Arduino.h>
3
4
4
-
5
5
template <size_t N>
6
6
class ByteRingBuffer
7
7
{
8
8
private:
9
- uint8_t ringBuffer [N];
10
- size_t newestIndex = 0 ;
11
- size_t length = 0 ;
9
+ uint8_t buffer [N];
10
+ int head = 0 ;
11
+ int tail = 0 ;
12
12
13
13
public:
14
14
void add (uint8_t value)
15
15
{
16
- ringBuffer[newestIndex] = value;
17
- newestIndex = (newestIndex + 1 ) % N;
18
- length = min (length + 1 , N);
16
+ buffer[head] = value;
17
+ head = (head + 1 ) % N;
18
+ if (head == tail)
19
+ {
20
+ tail = (tail + 1 ) % N;
21
+ }
19
22
}
20
23
uint8_t pop ()
21
- { // pops the oldest value off the ring buffer
22
- if (length == 0 )
24
+ {
25
+ // pops the oldest value off the ring buffer
26
+ if (head == tail)
23
27
{
24
28
return -1 ;
25
29
}
26
- uint8_t result = ringBuffer[(N + newestIndex - length) % N];
27
- length -= 1 ;
28
- return result;
30
+ else
31
+ {
32
+ uint8_t value = buffer[tail];
33
+ tail = (tail + 1 ) % N;
34
+ return value;
35
+ }
29
36
}
37
+
30
38
void clear ()
31
39
{
32
- newestIndex = 0 ;
33
- length = 0 ;
40
+ head = 0 ;
41
+ tail = 0 ;
34
42
}
43
+
35
44
uint8_t get (size_t index)
36
- { // this.get(0) is the oldest value, this.get(this.getLength() - 1) is the newest value
37
- if (index < 0 || index >= length)
45
+ {
46
+ // this.get(0) is the oldest value, this.get(this.getLength() - 1) is the newest value
47
+ if (index >= this ->getLength ())
38
48
{
39
49
return -1 ;
40
50
}
41
- return ringBuffer[(N + newestIndex - length + index) % N];
51
+ else
52
+ {
53
+ return buffer[(tail + index) % N];
54
+ }
42
55
}
43
- size_t getLength () { return length; }
44
- };
45
56
57
+ size_t getLength ()
58
+ {
59
+ if (head >= tail)
60
+ {
61
+ return head - tail;
62
+ }
63
+ else
64
+ {
65
+ return N - tail + head;
66
+ }
67
+ }
46
68
69
+ };
You can’t perform that action at this time.
0 commit comments