Sub topic 2
Voltage levels and wiring: TX, RX and ground
This chapter assumes you can write a basic sketch with setup() and loop(), and that you know what HIGH and LOW mean on a digital pin. A UART link needs three wires: TX (transmit), RX (receive) and GND (ground). Each device's TX connects to the other device's RX, and the grounds must be joined.
Wiring two devices
Connect the wires in a crossed pattern:
- Device A TX goes to Device B RX.
- Device B TX goes to Device A RX.
- Device A GND goes to Device B GND.
Voltage levels
Logic levels are the voltages that represent 0 and 1. A 5 V Arduino Uno uses roughly 5 V for HIGH and 0 V for LOW. A 3.3 V board uses 3.3 V. Connecting a 5 V TX pin to a 3.3 V RX pin can damage the 3.3 V input, so use a level shifter. RS-232 uses about ±12 V and needs a converter chip before it reaches any Arduino pin.
Parity, framing errors and overrun
Parity is an optional extra bit that counts 1s in a byte. Both ends must agree on it. A framing error happens when the receiver expects a stop bit (HIGH) and reads LOW, usually from a baud rate mismatch or a noisy wire.
Overrun happens when new bytes arrive before your code reads the old ones. The receive buffer is then full, and the new bytes are lost.
Using the Arduino Serial API
Serial.begin() sets the baud rate and optionally the frame format. Serial.available() reports how many bytes are waiting, and Serial.read() removes one byte.
void setup() {
Serial.begin(115200, SERIAL_8E1); // 8 data bits, even parity, 1 stop bit
}
void loop() {
while (Serial.available() > 0) {
int b = Serial.read();
Serial.write(b); // echo the byte back
}
}Buffers and why bytes get lost
The hardware UART stores incoming bytes in a receive buffer, which is 64 bytes on the ATmega328P. Your loop() must empty this buffer before it fills. Code that blocks for a long time, such as a long delay(), is the most common cause of lost bytes.
> Serial.begin() with a mismatched baud rate or frame format produces garbled text, so check both ends first.
Exercise
A device sends at 9600 baud with even parity, and your Arduino uses Serial.begin(9600), which means 8N1 with no parity. What problem do you expect, and how do you fix it?
Show answer
The Arduino expects no parity bit, so the extra parity bit is misread, which causes framing or data errors. Change the Arduino to Serial.begin(9600, SERIAL_8E1) so both ends match.