Skip to content

Fix Hardwareserial sending a byte twice #3865

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions hardware/arduino/avr/cores/arduino/HardwareSerial.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <util/atomic.h>
#include "Arduino.h"

#include "HardwareSerial.h"
Expand Down Expand Up @@ -178,13 +179,12 @@ int HardwareSerial::read(void)
int HardwareSerial::availableForWrite(void)
{
#if (SERIAL_TX_BUFFER_SIZE>256)
uint8_t oldSREG = SREG;
cli();
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
#endif
tx_buffer_index_t head = _tx_buffer_head;
tx_buffer_index_t tail = _tx_buffer_tail;
#if (SERIAL_TX_BUFFER_SIZE>256)
SREG = oldSREG;
}
#endif
if (head >= tail) return SERIAL_TX_BUFFER_SIZE - 1 - head + tail;
return tail - head - 1;
Expand Down Expand Up @@ -217,9 +217,18 @@ size_t HardwareSerial::write(uint8_t c)
// to the data register and be done. This shortcut helps
// significantly improve the effective datarate at high (>
// 500kbit/s) bitrates, where interrupt overhead becomes a slowdown.
if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) {
*_udr = c;
sbi(*_ucsra, TXC0);
#if (SERIAL_TX_BUFFER_SIZE>256)
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
#endif
bool emptyBuffer = _tx_buffer_head == _tx_buffer_tail;
#if (SERIAL_TX_BUFFER_SIZE>256)
}
#endif
if (emptyBuffer && bit_is_set(*_ucsra, UDRE0)) {
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
*_udr = c;
sbi(*_ucsra, TXC0);
}
return 1;
}
tx_buffer_index_t i = (_tx_buffer_head + 1) % SERIAL_TX_BUFFER_SIZE;
Expand All @@ -240,9 +249,11 @@ size_t HardwareSerial::write(uint8_t c)
}

_tx_buffer[_tx_buffer_head] = c;
_tx_buffer_head = i;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
_tx_buffer_head = i;

sbi(*_ucsrb, UDRIE0);
sbi(*_ucsrb, UDRIE0);
}

return 1;
}
Expand Down