1
1
#define BUFFER_SIZE 8
2
2
3
+ // This semaphore is here to handle the interruption of the loop when the interrupt is running.
4
+ SemaphoreHandle_t bufferSemaphore;
5
+
3
6
static volatile char inputBuffer[BUFFER_SIZE];
4
7
static volatile size_t inputBufferLength = 0 ;
5
8
@@ -10,13 +13,20 @@ static void IRAM_ATTR onSerialRX(uint8_t character, void* user_arg){
10
13
// Cast the user_arg back to a array
11
14
char * buffer = (char *)user_arg;
12
15
13
- if (inputBufferLength < BUFFER_SIZE){
14
- buffer[inputBufferLength++] = (char )character;
16
+ BaseType_t xHighPriorityTaskWoken;
17
+
18
+ if (xSemaphoreTakeFromISR (bufferSemaphore, &xHighPriorityTaskWoken) == pdTRUE){
19
+ if (inputBufferLength < BUFFER_SIZE){
20
+ buffer[inputBufferLength++] = (char )character;
21
+ }
22
+ xSemaphoreGiveFromISR (bufferSemaphore, &xHighPriorityTaskWoken);
15
23
}
16
24
}
17
25
18
26
void setup ()
19
27
{
28
+ bufferSemaphore = xSemaphoreCreateBinary ();
29
+
20
30
Serial.begin (115200 );
21
31
Serial2.begin (115200 );
22
32
@@ -27,7 +37,7 @@ void setup()
27
37
28
38
void loop ()
29
39
{
30
- if (inputBufferLength == (BUFFER_SIZE - 1 )){
40
+ if (xSemaphoreTake (bufferSemaphore, portMAX_DELAY) == pdTRUE && inputBufferLength == (BUFFER_SIZE - 1 )){
31
41
for (size_t i = 0 ; i < inputBufferLength; i++){
32
42
Serial.write (inputBuffer[i]);
33
43
@@ -36,6 +46,8 @@ void loop()
36
46
}
37
47
// Clear the bufferLength
38
48
inputBufferLength = 0 ;
49
+
50
+ xSemaphoreGive (bufferSemaphore);
39
51
}
40
52
41
53
delay (1000 ); // Wait for one second
0 commit comments