|
| 1 | +/** Tim Koers - 2021 |
| 2 | + * |
| 3 | + * This sketch shows the usage of an queue, to store and read the characters that are sent to the interrupt. |
| 4 | + * You can safely use this in a FreeRTOS environment and use the queue from different tasks on different CPU cores. |
| 5 | + * This sketch assumes that when Hi is sent, the device returns an 8 byte message. |
| 6 | + * |
| 7 | + */ |
| 8 | + |
| 9 | +#define BUFFER_SIZE 8 |
| 10 | + |
| 11 | +// This queue is here to handle the interruption of the loop when the interrupt is running. |
| 12 | +Queue_t bufferQueue; |
| 13 | + |
| 14 | +bool messageSent = false; |
| 15 | + |
| 16 | +// Please keep in mind, since the ESP32 is dual core, |
| 17 | +// the interrupt will be running on the same core as the setRxInterrupt function was called on. |
| 18 | +static void IRAM_ATTR onSerialRX(uint8_t character, void* user_arg){ |
| 19 | + |
| 20 | + BaseType_t xHighPriorityTaskWoken; |
| 21 | + |
| 22 | + if(!xQueueSendFromISR(bufferQueue, &character, &xHighPriorityTaskWoken) == pdTRUE){ |
| 23 | + log_e("IRQ", "Failed to put character onto the queue\n"); |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +void setup() |
| 28 | +{ |
| 29 | + bufferQueue = xQueueCreate(BUFFER_SIZE * 4, sizeof(char)); // Create a queue that can hold 4 messages of 8-bytes each. |
| 30 | + |
| 31 | + assert(bufferQueue != NULL); |
| 32 | + |
| 33 | + Serial.begin(115200); |
| 34 | + Serial2.begin(115200); |
| 35 | + |
| 36 | + Serial2.setRxInterrupt(onSerialRX, NULL); |
| 37 | +} |
| 38 | + |
| 39 | +void loop() |
| 40 | +{ |
| 41 | + if(!messageSent){ |
| 42 | + Serial.println("Hi"); |
| 43 | + messageSent = true; |
| 44 | + } |
| 45 | + |
| 46 | + // Check if data in the queue and check if there is a complete message (8-bytes) in the queue |
| 47 | + if(!(uxQueueMessagesWaiting(bufferQueue) % RESPONSE_SIZE)){ |
| 48 | + char c; |
| 49 | + // Check if the queue is not empty, 0 % 8 returns 0 instead, so does 24 % 8 |
| 50 | + while(uxQueueMessagesWaiting(bufferQueue) > 0){ |
| 51 | + // Get the character from the queue, but don't block if someone else is busy with the queue |
| 52 | + if(xQueueReceive(bufferQueue, &c, 0) == pdTRUE) |
| 53 | + Serial.write(c); |
| 54 | + } |
| 55 | + |
| 56 | + // Allow the system to request another data set |
| 57 | + messageSent = false; |
| 58 | + } |
| 59 | +} |
0 commit comments