Skip to content

Commit 6f60715

Browse files
committed
arduino: make uart1_write() a critical section
A race condition (likely exacerbated by FreeRTOS which allows task switching inside the uart1_write() routine) causes the arduino to retransmit old data. One reason could be the "TX empty" ISR is called even though the transmit buffer is empty (i.e. _tx_buffer_head == _tx_buffer_tail). This causes the _tx_buffer_tail to be incremented past _tx_buffer_head, resulting in the arduino transmitting old data. Alternatively, what might be happening is that the "TX empty" ISR might be enabled BEFORE _tx_buffer_head is incremented, which results in _tx_buffer_head being incremented past _tx_buffer_tail. (Ref: The HardwareSerial::write() code, a memory barrier might need to be added in between the `_tx_buffer_head = i` and `sbi(*_ucsrb, UDRIE0)`) The raspi code (particularly ucomm_SampleAssembler) is written with the assumption that old packets won't be received again. However, the above problem results in behavior which breaks this assumption, and bad things happen as a result. Fix this by wrapping uart1_write() with a critical section, so that no task switching or ISRs will be called when it is in progress. This should hopefully fix the race condition occurring with _tx_buffer_head/_tx_buffer_tail. Ref: https://github.com/arduino/Arduino/issues/3745
1 parent 466155c commit 6f60715

1 file changed

Lines changed: 3 additions & 0 deletions

File tree

‎arduino/uart1.cpp‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#include <Arduino.h>
33
#include <Arduino_FreeRTOS.h>
44
#include <semphr.h>
5+
#include <task.h>
56
#include <avr/io.h>
67
#include <avr/interrupt.h>
78
#include <HardwareSerial.h>
@@ -49,7 +50,9 @@ uart1_init(void)
4950
void
5051
uart1_write(uint8_t byte)
5152
{
53+
taskENTER_CRITICAL();
5254
UART1.write(byte);
55+
taskEXIT_CRITICAL();
5356
}
5457

5558
uint8_t

0 commit comments

Comments
 (0)