Skip to content

Commit f33c332

Browse files
committed
Fixed ISR concurrency problems in example
1 parent 4f80e57 commit f33c332

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

libraries/ESP32/examples/Serial/Interrupt/Interrupt.ino

+15-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
#define BUFFER_SIZE 8
22

3+
// This semaphore is here to handle the interruption of the loop when the interrupt is running.
4+
SemaphoreHandle_t bufferSemaphore;
5+
36
static volatile char inputBuffer[BUFFER_SIZE];
47
static volatile size_t inputBufferLength = 0;
58

@@ -10,13 +13,20 @@ static void IRAM_ATTR onSerialRX(uint8_t character, void* user_arg){
1013
// Cast the user_arg back to a array
1114
char* buffer = (char*)user_arg;
1215

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);
1523
}
1624
}
1725

1826
void setup()
1927
{
28+
bufferSemaphore = xSemaphoreCreateBinary();
29+
2030
Serial.begin(115200);
2131
Serial2.begin(115200);
2232

@@ -27,7 +37,7 @@ void setup()
2737

2838
void loop()
2939
{
30-
if(inputBufferLength == (BUFFER_SIZE - 1)){
40+
if(xSemaphoreTake(bufferSemaphore, portMAX_DELAY) == pdTRUE && inputBufferLength == (BUFFER_SIZE - 1)){
3141
for(size_t i = 0; i < inputBufferLength; i++){
3242
Serial.write(inputBuffer[i]);
3343

@@ -36,6 +46,8 @@ void loop()
3646
}
3747
// Clear the bufferLength
3848
inputBufferLength = 0;
49+
50+
xSemaphoreGive(bufferSemaphore);
3951
}
4052

4153
delay(1000); // Wait for one second

0 commit comments

Comments
 (0)