Skip to content

Commit 9250e67

Browse files
committed
Thread safe byte ring buffer, Release 1.0.4
1 parent 091977d commit 9250e67

File tree

2 files changed

+43
-20
lines changed

2 files changed

+43
-20
lines changed

library.properties

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
name=ESP32_BleSerial
2-
version=1.0.2
2+
version=1.0.4
33
author=Avinab Malla <[email protected]>
44
maintainer=Avinab Malla <[email protected]>
55
sentence= A BLE Serial library for Arduino ESP32

src/ByteRingBuffer.h

Lines changed: 42 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,69 @@
1+
// Thread safe ring buffer
12
#pragma once
23
#include <Arduino.h>
34

4-
55
template <size_t N>
66
class ByteRingBuffer
77
{
88
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;
1212

1313
public:
1414
void add(uint8_t value)
1515
{
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+
}
1922
}
2023
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)
2327
{
2428
return -1;
2529
}
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+
}
2936
}
37+
3038
void clear()
3139
{
32-
newestIndex = 0;
33-
length = 0;
40+
head = 0;
41+
tail = 0;
3442
}
43+
3544
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())
3848
{
3949
return -1;
4050
}
41-
return ringBuffer[(N + newestIndex - length + index) % N];
51+
else
52+
{
53+
return buffer[(tail + index) % N];
54+
}
4255
}
43-
size_t getLength() { return length; }
44-
};
4556

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+
}
4668

69+
};

0 commit comments

Comments
 (0)