Skip to content

Commit d50e597

Browse files
johnholmanfacchinm
authored andcommitted
Create macro to guard critical sections for large transmit buffers
New macro TX_BUFFER_ATOMIC makes the following code block atomic only if the transmit buffer is larger than 256 bytes. SREG is restored on completion. The macro is then used to simplify code for availableForWrite()
1 parent f1c4cc6 commit d50e597

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

Diff for: cores/arduino/HardwareSerial.cpp

+15-9
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#include <stdio.h>
2727
#include <string.h>
2828
#include <inttypes.h>
29+
#include <util/atomic.h>
2930
#include "Arduino.h"
3031

3132
#include "HardwareSerial.h"
@@ -76,6 +77,13 @@ void serialEventRun(void)
7677
#endif
7778
}
7879

80+
// macro to guard critical sections when needed for large TX buffer sizes
81+
#if (SERIAL_TX_BUFFER_SIZE>256)
82+
#define TX_BUFFER_ATOMIC ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
83+
#else
84+
#define TX_BUFFER_ATOMIC
85+
#endif
86+
7987
// Actual interrupt handlers //////////////////////////////////////////////////////////////
8088

8189
void HardwareSerial::_tx_udr_empty_irq(void)
@@ -177,15 +185,13 @@ int HardwareSerial::read(void)
177185

178186
int HardwareSerial::availableForWrite(void)
179187
{
180-
#if (SERIAL_TX_BUFFER_SIZE>256)
181-
uint8_t oldSREG = SREG;
182-
cli();
183-
#endif
184-
tx_buffer_index_t head = _tx_buffer_head;
185-
tx_buffer_index_t tail = _tx_buffer_tail;
186-
#if (SERIAL_TX_BUFFER_SIZE>256)
187-
SREG = oldSREG;
188-
#endif
188+
tx_buffer_index_t head;
189+
tx_buffer_index_t tail;
190+
191+
TX_BUFFER_ATOMIC {
192+
head = _tx_buffer_head;
193+
tail = _tx_buffer_tail;
194+
}
189195
if (head >= tail) return SERIAL_TX_BUFFER_SIZE - 1 - head + tail;
190196
return tail - head - 1;
191197
}

0 commit comments

Comments
 (0)