Sub topic 5
Parity, Framing Errors and Overrun
This chapter assumes you know how a UART frame is built (start bit, data bits, optional parity bit, stop bit), what a baud rate is, and how to write basic Arduino sketches. Here you will see how a UART receiver notices that a frame went wrong, which three errors it can report, what causes each one, and what the Arduino core does when one occurs.
What a UART receiver can and cannot check
A UART has no clock line and no acknowledgement. The receiver samples the line on its own timing and decides what the bits were. The hardware has only a few cheap checks available:
- Was the line at the expected idle level (HIGH) when the stop bit should have been?
- Does the parity bit match the data bits, if parity is enabled?
- Did the previous byte get read before the next one arrived?
These checks map to three error flags: framing error, parity error and overrun error. They catch only some faults. A UART cannot tell you that a byte arrived with the wrong value if the corruption left the frame looking valid. For that you need a checksum, covered in the message framing chapter.
Parity
How the parity bit works
Parity adds one bit after the data bits. The sender sets it so that the total number of 1 bits, data plus parity, has a known property:
- Even parity: the total count of 1s is even.
- Odd parity: the total count of 1s is odd.
The receiver counts the 1s in what it received and compares. If the count has the wrong property, it sets the parity error flag.
Take the byte 0x41 (ASCII A), which is 01000001. It has two 1 bits.
| Mode | Parity bit sent | Total 1s |
|---|---|---|
| Even | 0 | 2 |
| Odd | 1 | 3 |
Now take 0x43 (01000011), which has three 1 bits. Even parity sends 1 (total 4). Odd parity sends 0 (total 3).
What parity catches
Parity detects any odd number of flipped bits in a frame. A single flipped bit changes the count of 1s by one, so the check fails. Two flipped bits cancel out, and the frame passes as if nothing happened. Parity also cannot say which bit flipped, so it cannot correct anything.
For example, if 0x41 is sent with even parity and noise flips bit 0, the receiver sees 01000000 with a parity bit of 0. That has one 1 bit, which is odd, so the error is flagged. If noise flips bits 0 and 1 instead, the receiver sees 01000010 with parity 0. That still has an even count, and the error goes unnoticed.
Parity costs one bit per frame. With 8E1 each byte takes 11 bits instead of 10, so throughput drops by about 9 percent.
Mark and space parity
Some devices use mark parity (the parity bit is always 1) or space parity (always 0). These detect nothing about the data. The receiver can only check that the bit has the fixed value. Some protocols use them to flag the first byte of a message as an address. The standard Arduino Serial modes cover none, even and odd only.
Setting parity on Arduino
The second argument to Serial.begin() selects the frame format. The default is SERIAL_8N1.
void setup() {
Serial.begin(115200, SERIAL_8E1);
}
void loop() {
}The constant name reads as data bits, parity letter (N, E, O), stop bits. So SERIAL_7O2 is 7 data bits, odd parity, 2 stop bits. Both devices must use the same format. If one side uses 8N1 and the other 8E1, the 8N1 receiver sees an extra bit it treats as part of the next frame or as the stop bit, and the 8E1 receiver sees mostly valid-looking data with occasional parity errors.
Framing errors
What the receiver checks
After the data bits (and the parity bit, if any), the line must go HIGH for the stop bit. If the receiver samples LOW at that moment, it sets a framing error. The receiver found a start bit and read a full frame, but the frame did not end the way a frame should.
Common causes
- Baud rate mismatch. If the receiver's bit timing differs from the sender's, its samples drift across the frame. By the stop bit it may sample a data bit instead. The typical symptom is garbled characters, not just an occasional bad one.
- Frame format mismatch. For example, the sender uses 7 data bits and the receiver expects 8.
- Joining a stream mid-frame. If you connect or power up while the sender is transmitting, the receiver may treat a data bit that happens to be LOW as a start bit. The following bits are misaligned, and the stop check fails. This usually clears after the line returns to idle.
- A break condition. If the sender holds the line LOW for longer than a full frame, the receiver reads all zeros, including a LOW stop bit. This produces a framing error with a data value of
0x00. Some protocols use a break on purpose to signal the start of a message. A disconnected or unpowered transmitter on a line with a pull-down can look the same. - Electrical noise or a floating RX pin. An input with nothing driving it picks up noise that looks like start bits followed by random data.
Why the stop bit helps
The stop bit exists so the receiver can resynchronise. Because the line idles HIGH and every frame begins with a LOW start bit, the receiver can always find the next falling edge once the line goes idle. A framing error tells it that its current alignment was wrong. The receiver then waits for the next HIGH-to-LOW edge and tries again.
This resynchronisation works best when there are gaps between bytes. In a continuous stream with no idle time, a receiver that lost alignment can stay misaligned for a long time, because every LOW data bit looks like a possible start bit. Longer idle gaps between messages make recovery faster. This is one reason protocols often add a pause or a distinct start marker between messages.
Overrun errors
What overrun means
The UART hardware receives a byte into a small hardware register. Software must read it before the next byte finishes arriving. If the next byte arrives while the previous one is still unread, the old byte is lost or overwritten and the overrun flag is set.
On an ATmega328P, the hardware has room for about one byte of receive data plus the shift register. The Arduino core avoids most overruns by attaching an interrupt service routine (ISR) that moves each byte into a 64-byte software ring buffer as soon as it arrives. So an overrun in the hardware means the ISR did not run in time. A different, more common loss happens in the software buffer, covered next.
Two kinds of lost bytes
| Kind | Where | Typical cause | What happens |
|---|---|---|---|
| Hardware overrun | UART data register | Interrupts disabled for longer than one byte time | The byte is overwritten or dropped, and the overrun flag is set |
| Software buffer overflow | Core's receive ring buffer | Sketch does not call `read()` fast enough | New bytes are discarded, with no error reported to the sketch |
The second kind produces no flag you can check. It shows up only as missing data.
How long you have
The time budget is one byte time at your baud rate. At 9600 baud with 8N1, a byte takes 10 bit times of about 104 µs each, so about 1.04 ms. At 115200 baud it takes about 86.8 µs. Anything that blocks interrupts for longer than that, with data arriving at full speed, risks a hardware overrun.
Common culprits:
- Long interrupt service routines of your own, or libraries that disable interrupts for a long time (some LED driver libraries do this while shifting out data).
delay()is not a culprit for the hardware, since interrupts stay enabled. It is a culprit for the software buffer, because your sketch is not reading.- Slow
Serial.print()calls. When the transmit buffer is full,print()blocks until space frees up, and during that time yourloop()is not reading input.
Software buffer overflow in practice
The receive ring buffer holds 64 bytes on small AVR boards (the AVR core uses 64 for both buffers; some other boards use larger values). If a sender emits 100 bytes at once and your sketch reads nothing for the time it takes to receive them, the bytes beyond the 64th are lost.
This sketch shows the problem. It blocks for a while and then reads whatever is waiting:
void setup() {
Serial.begin(115200);
}
void loop() {
delay(50); // about 575 bytes could arrive at 115200 baud in this time
Serial.print(F("Waiting: "));
Serial.println(Serial.available());
}If the sender streams continuously, Serial.available() never reports more than 63 or 64, because the buffer is full and the extra bytes were dropped. Seeing available() pinned at that value is a strong sign of overflow.
Detecting errors from a sketch
Since the AVR core hides the hardware flags, you detect problems indirectly.
Check the buffer level
Print or log Serial.available() at a point where it should be small. If it often sits near the buffer size, you are about to lose data.
Use a checksum or CRC
An application-level check catches corruption that parity and framing checks miss, including software buffer loss that makes a message shorter than expected. The framed message in this tutorial uses a start marker, a length byte, a payload and an XOR checksum:
uint8_t xorChecksum(const uint8_t *data, uint8_t len) {
uint8_t sum = 0;
for (uint8_t i = 0; i < len; i++) {
sum ^= data[i];
}
return sum;
}
void sendFrame(const uint8_t *payload, uint8_t len) {
Serial.write((uint8_t)0x7E);
Serial.write(len);
Serial.write(payload, len);
Serial.write(xorChecksum(payload, len));
}If a byte is lost, the length no longer matches what arrives, and the checksum will almost always fail. A later chapter builds the receiver side.
Use the board's own flags where available
Some cores expose errors. On many ARM-based boards the underlying library or register interface lets you read framing, parity and overrun flags directly. If you need this on AVR, you can read the UCSR0A register bits FE0, DOR0 and UPE0, but only before the core's ISR has read the data register, which makes it impractical with the standard Serial class. If error counting matters, use a board whose core reports errors, or write a custom receive routine.
Quick reference
| Symptom | Likely error | First thing to check |
|---|---|---|
| Every character is garbled | Framing error from baud or format mismatch | Baud rate and frame format on both ends |
| Mostly correct text with occasional wrong characters | Parity error or noise | Wiring, grounding, cable length, parity setting |
| `0x00` bytes appear when the sender is unplugged | Break condition or floating pin | Pull-up on RX, sender power |
| Long messages arrive cut short | Software buffer overflow | Read faster, shorten `delay()`, raise buffer size |
| Data lost only when a certain library is active | Hardware overrun | Interrupt-disabling code in that library |
| Data looks fine but one value is wrong | Undetected corruption | Add a checksum |
Reducing errors
- Match baud rate and frame format exactly on both devices.
- Use a baud rate that your board's clock divides accurately. At 16 MHz on AVR, 115200 has about 2.1 percent error, which usually works but leaves less margin than 9600 (about 0.2 percent). Both ends adding error in opposite directions can exceed the roughly 3 to 4 percent tolerance a frame can take.
- Share a common ground and keep wires short.
- Read the serial port often. Avoid long
delay()calls in programs that receive data. - Keep interrupt-disabled sections short.
- Add a checksum to anything important.
- If you need more headroom, lower the baud rate, add flow control, or define a protocol where the receiver requests data.
Exercise
A sender transmits a continuous stream at 115200 baud, 8N1. Your Arduino sketch calls delay(100) in loop() and then reads all available bytes. About how many bytes arrive during one delay, and how many can the 64-byte software receive buffer keep? Which error category does the loss belong to?
Show answer
At 115200 baud with 8N1 each byte takes 10 bit times, so the byte rate is about 11520 bytes per second. In 100 ms about 1152 bytes arrive. The buffer holds 64, so roughly 1088 bytes are lost. This is a software buffer overflow, not a hardware overrun, and it reports no error flag to the sketch.
Exercise
A frame is sent as 8E1 with data byte 0x5A (01011010). What parity bit does the sender transmit? If noise flips exactly two bits of the frame, will the receiver report a parity error?
Show answer
0x5A has four 1 bits, which is already even, so the even parity bit is 0. If exactly two bits flip, the count of 1s changes by an even amount (or stays equal in parity), so the parity still matches and no parity error is reported.
Exercise
You unplug the sender from an Arduino whose RX line has a pull-down resistor to ground, and you see a stream of 0x00 bytes. Which error does the hardware report, and why does it produce 0x00?
Show answer
A framing error. The line stays LOW, so the receiver sees a start bit, eight data bits of 0 and a stop bit that should be HIGH but is LOW. The data bits are all 0, so the byte value is 0x00. Adding a pull-up resistor makes the idle level HIGH when nothing is connected.