|
| 1 | +// this will make UART0 work in any case (using or not USB) |
| 2 | +#if ARDUINO_USB_CDC_ON_BOOT |
| 3 | +#define UART0 Serial0 |
| 4 | +#else |
| 5 | +#define UART0 Serial |
| 6 | +#endif |
| 7 | + |
| 8 | +// global variable to keep the results from onReceive() |
| 9 | +String uart_buffer = ""; |
| 10 | +// a pause of a half second in the UART transmission is considered the end of transmission. |
| 11 | +const uint32_t communicationTimeout_ms = 500; |
| 12 | + |
| 13 | +// Create a mutex for the access to uart_buffer |
| 14 | +// only one task can read/write it at a certain time |
| 15 | +SemaphoreHandle_t uart_buffer_Mutex = NULL; |
| 16 | + |
| 17 | +// UART_RX_IRQ will be executed as soon as data is received by the UART |
| 18 | +// This is a callback function executed from a high priority |
| 19 | +// task created when onReceive() is used |
| 20 | +void UART0_RX_CB() { |
| 21 | + // take the mutex, waits forever until loop() finishes its processing |
| 22 | + if (xSemaphoreTake(uart_buffer_Mutex, portMAX_DELAY)) { |
| 23 | + uint32_t now = millis(); // tracks timeout |
| 24 | + while ((millis() - now) < communicationTimeout_ms) { |
| 25 | + if (UART0.available()) { |
| 26 | + uart_buffer += (char) UART0.read(); |
| 27 | + now = millis(); // reset the timer |
| 28 | + } |
| 29 | + } |
| 30 | + // releases the mutex for data processing |
| 31 | + xSemaphoreGive(uart_buffer_Mutex); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +// setup() and loop()are callback functions executed by a low priority task |
| 36 | +// Therefore, there are 2 tasks running when using onReceive() |
| 37 | +void setup() { |
| 38 | + // creates a mutex object to control access to uart_buffer |
| 39 | + uart_buffer_Mutex = xSemaphoreCreateMutex(); |
| 40 | + |
| 41 | + UART0.begin(115200); |
| 42 | + UART0.onReceive(UART0_RX_CB); // sets the callback function |
| 43 | + UART0.println("Send data to UART0 in order to activate the RX callback"); |
| 44 | +} |
| 45 | + |
| 46 | +uint32_t counter = 0; |
| 47 | +void loop() { |
| 48 | + if (uart_buffer.length() > 0) { |
| 49 | + // signals that the onReceive function shall not change uart_buffer while processing |
| 50 | + if (xSemaphoreTake(uart_buffer_Mutex, portMAX_DELAY)) { |
| 51 | + // process the received data from UART0 - example, just print it beside a counter |
| 52 | + UART0.print("["); |
| 53 | + UART0.print(counter++); |
| 54 | + UART0.print("] ["); |
| 55 | + UART0.print(uart_buffer.length()); |
| 56 | + UART0.print(" bytes] "); |
| 57 | + UART0.println(uart_buffer); |
| 58 | + uart_buffer = ""; // reset uart_buffer for the next UART reading |
| 59 | + } |
| 60 | + // releases the mutex for more data to be received |
| 61 | + xSemaphoreGive(uart_buffer_Mutex); |
| 62 | + } |
| 63 | + UART0.println("Sleeping for 1 second..."); |
| 64 | + delay(1000); |
| 65 | +} |
0 commit comments