Skip to content

Commit 5cac99b

Browse files
authored
feat(uart): simplifies UART example based on MODBUS standard
1 parent 571c2f7 commit 5cac99b

File tree

1 file changed

+55
-65
lines changed

1 file changed

+55
-65
lines changed

libraries/ESP32/examples/Serial/onReceiveExample/onReceiveExample.ino

+55-65
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,20 @@
55
void HardwareSerial::onReceive(OnReceiveCb function, bool onlyOnTimeout = false)
66
77
It is possible to register an UART callback function that will be called
8-
every time that UART receives data and an associated interrupt is generated.
8+
every time that UART receives data and an associated UART interrupt is generated.
99
10-
In summary, HardwareSerial::onReceive() works like an RX Interrupt callback, that can be adjusted
11-
using HardwareSerial::setRxFIFOFull() and HardwareSerial::setRxTimeout().
10+
In summary, HardwareSerial::onReceive() works like an RX Interrupt callback, that
11+
can be adjusted using HardwareSerial::setRxFIFOFull() and HardwareSerial::setRxTimeout().
1212
13-
OnReceive will be called, while receiving a stream of data, when every 120 bytes are received (default FIFO Full),
14-
which may not help in case that the application needs to get all data at once before processing it.
15-
Therefore, a way to make it work is by detecting the end of a stream transmission. This can be based on a protocol
16-
or based on timeout with the UART line in idle (no data received - this is the case of this example).
13+
In case that <onlyOnTimeout> is not changed or it is set to <false>, the callback function is
14+
executed whenever any event happens first (FIFO Full or RX Timeout).
15+
OnReceive will be called when every 120 bytes are received(default FIFO Full),
16+
or when RX Timeout occurs after 1 UART symbol by default.
1717
18-
In some cases, it is necessary to wait for receiving all the data before processing it and parsing the
19-
UART input. This example demonstrates a way to create a String with all data received from UART0 and
20-
signaling it using a Mutex for another task to process it. This example uses a timeout of 500ms as a way to
21-
know when the reception of data has finished.
18+
This example demonstrates a way to create a String with all data received from UART0 only
19+
after RX Timeout. This example uses an RX timeout of about 3.5 Symbols as a way to know
20+
when the reception of data has finished.
21+
In order to achieve it, the sketch sets <onlyOnTimeout> to <true>.
2222
2323
The onReceive() callback is called whenever the RX ISR is triggered.
2424
It can occur because of two possible events:
@@ -34,18 +34,23 @@
3434
3535
2- UART RX Timeout: it happens, based on a timeout equivalent to a number of symbols at
3636
the current baud rate. If the UART line is idle for this timeout, it will raise an interrupt.
37-
This time can be changed by HardwareSerial::setRxTimeout(uint8_t rxTimeout)
37+
This time can be changed by HardwareSerial::setRxTimeout(uint8_t rxTimeout).
38+
<rxTimeout> is bound to the clock source.
39+
In order to use it properly, ESP32 and ESP32-S2 shall set the UART Clock Source to APB.
3840
3941
When any of those two interrupts occur, IDF UART driver will copy FIFO data to its internal
4042
RingBuffer and then Arduino can read such data. At the same time, Arduino Layer will execute
4143
the callback function defined with HardwareSerial::onReceive().
4244
43-
<bool onlyOnTimeout> parameter (default false) can be used by the application to tell Arduino to
44-
only execute the callback when the second event above happens (Rx Timeout). At this time all
45-
received data will be available to be read by the Arduino application. But if the number of
46-
received bytes is higher than the FIFO space, it will generate an error of FIFO overflow.
47-
In order to avoid such problem, the application shall set an appropriate RX buffer size using
45+
<bool onlyOnTimeout> parameter can be used by the application to tell Arduino to only execute
46+
the callback when Rx Timeout happens, by setting it to <true>.
47+
At this time all received data will be available to be read by the Arduino application.
48+
The application shall set an appropriate RX buffer size using
4849
HardwareSerial::setRxBufferSize(size_t new_size) before executing begin() for the Serial port.
50+
51+
MODBUS timeout of 3.5 symbol is based on these documents:
52+
https://www.automation.com/en-us/articles/2012-1/introduction-to-modbus
53+
https://minimalmodbus.readthedocs.io/en/stable/serialcommunication.html
4954
*/
5055

5156
// this will make UART0 work in any case (using or not USB)
@@ -57,67 +62,52 @@
5762

5863
// global variable to keep the results from onReceive()
5964
String uart_buffer = "";
60-
// a pause of a half second in the UART transmission is considered the end of transmission.
61-
const uint32_t communicationTimeout_ms = 500;
62-
63-
// Create a mutex for the access to uart_buffer
64-
// only one task can read/write it at a certain time
65-
SemaphoreHandle_t uart_buffer_Mutex = NULL;
66-
67-
// UART_RX_IRQ will be executed as soon as data is received by the UART
68-
// This is a callback function executed from a high priority
69-
// task created when onReceive() is used
65+
// The Modbus RTU standard prescribes a silent period corresponding to 3.5 characters between each
66+
// message, to be able fo figure out where one message ends and the next one starts.
67+
const uint32_t modbusRxTimeoutLimit = 4;
68+
const uint32_t baudrate = 19200;
69+
70+
// UART_RX_IRQ will be executed as soon as data is received by the UART and an RX Timeout occurs
71+
// This is a callback function executed from a high priority monitor task
72+
// All data will be buffered into RX Buffer, which may have its size set to whatever necessary
7073
void UART0_RX_CB() {
71-
// take the mutex, waits forever until loop() finishes its processing
72-
if (xSemaphoreTake(uart_buffer_Mutex, portMAX_DELAY)) {
73-
uint32_t now = millis(); // tracks timeout
74-
while ((millis() - now) < communicationTimeout_ms) {
75-
if (UART0.available()) {
76-
uart_buffer += (char)UART0.read();
77-
now = millis(); // reset the timer
78-
}
79-
}
80-
// releases the mutex for data processing
81-
xSemaphoreGive(uart_buffer_Mutex);
74+
while (UART0.available()) {
75+
uart_buffer += (char)UART0.read();
8276
}
8377
}
8478

8579
// setup() and loop() are functions executed by a low priority task
8680
// Therefore, there are 2 tasks running when using onReceive()
8781
void setup() {
88-
UART0.begin(115200);
89-
90-
// creates a mutex object to control access to uart_buffer
91-
uart_buffer_Mutex = xSemaphoreCreateMutex();
92-
if (uart_buffer_Mutex == NULL) {
93-
log_e("Error creating Mutex. Sketch will fail.");
94-
while (true) {
95-
UART0.println("Mutex error (NULL). Program halted.");
96-
delay(2000);
97-
}
98-
}
82+
#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2
83+
// UART_CLK_SRC_APB will allow higher values of RX Timeout
84+
// default for ESP32 and ESP32-S2 is REF_TICK which limits the RX Timeout to 1
85+
// setClockSource() must be called before begin()
86+
UART0.setClockSource(UART_CLK_SRC_APB);
87+
#endif
88+
// the amount of data received or waiting to be proessed shall not exceed this limit of 1024 bytes
89+
UART0.setRxBufferSize(1024); // default is 256 bytes
90+
UART0.begin(baudrate); // default pins and default mode 8N1 (8 bits data, no parity bit, 1 stopbit)
91+
// set RX Timeout based on UART symbols ~ 3.5 symbols of 11 bits (MODBUS standard) ~= 2 ms at 19200
92+
UART0.setRxTimeout(modbusRxTimeoutLimit); // 4 symbols at 19200 8N1 is about 2.08 ms (40 bits)
93+
// sets the callback function that will be executed only after RX Timeout
94+
UART0.onReceive(UART0_RX_CB, true);
9995

100-
UART0.onReceive(UART0_RX_CB); // sets the callback function
10196
UART0.println("Send data to UART0 in order to activate the RX callback");
10297
}
10398

10499
uint32_t counter = 0;
105100
void loop() {
101+
// String <uart_buffer> is filled by the UART Callback whenever data is received and RX Timeout occurs
106102
if (uart_buffer.length() > 0) {
107-
// signals that the onReceive function shall not change uart_buffer while processing
108-
if (xSemaphoreTake(uart_buffer_Mutex, portMAX_DELAY)) {
109-
// process the received data from UART0 - example, just print it beside a counter
110-
UART0.print("[");
111-
UART0.print(counter++);
112-
UART0.print("] [");
113-
UART0.print(uart_buffer.length());
114-
UART0.print(" bytes] ");
115-
UART0.println(uart_buffer);
116-
uart_buffer = ""; // reset uart_buffer for the next UART reading
117-
// releases the mutex for more data to be received
118-
xSemaphoreGive(uart_buffer_Mutex);
119-
}
103+
// process the received data from UART0 - example, just print it beside a counter
104+
UART0.print("[");
105+
UART0.print(counter++);
106+
UART0.print("] [");
107+
UART0.print(uart_buffer.length());
108+
UART0.print(" bytes] ");
109+
UART0.println(uart_buffer);
110+
uart_buffer = ""; // reset uart_buffer for the next UART reading
120111
}
121-
UART0.println("Sleeping for 1 second...");
122-
delay(1000);
112+
delay(1);
123113
}

0 commit comments

Comments
 (0)