Sub topic 3
Reading and Parsing Incoming Data Without Blocking
This chapter assumes you can write an Arduino sketch with setup() and loop(), read binary and hexadecimal values, and open a serial connection at 9600 baud.
Reading without blocking
Serial.read() returns the next byte from the receive buffer, or -1 if the buffer is empty. A loop such as while (Serial.available() == 0) {} stops everything else in loop(). Instead, read whatever has arrived on each pass and keep the partial message in variables between passes.
const byte MAX_LEN = 32;
char line[MAX_LEN];
byte len = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\n') {
line[len] = '\0';
Serial.print(F("Got: "));
Serial.println(line);
len = 0;
} else if (c != '\r' && len < MAX_LEN - 1) {
line[len++] = c;
}
}
// Other work runs here on every pass.
}Extra serial ports
A hardware UART is a serial controller built into the microcontroller. It runs at full speed and has its own receive buffer. An Uno has one port, which is shared with USB. A Mega has four.
SoftwareSerial uses ordinary pins and software timing to send and receive bits. It works on any two pins, but it is reliable only at low speeds, and only one SoftwareSerial port can listen at a time.
| Option | Ports | Speed | Use when |
|---|---|---|---|
| Hardware UART | Serial, Serial1 to Serial3 on a Mega | Full speed | The device needs reliable throughput |
| SoftwareSerial | Any two pins | Low speed, one listener at a time | No hardware port is free |
Designing messages
A raw byte stream has no boundaries, so the receiver needs a way to find where each message starts and ends.
- Delimiter: end each text message with
\n. The payload must never contain the delimiter. - Length: send a length byte before the payload. One byte allows payloads up to 255 bytes.
- Checksum: XOR every payload byte and send the result last. The receiver recomputes it and rejects the frame on a mismatch. XOR catches many errors but not all of them.
Troubleshooting a UART link
| Symptom | Likely cause | Fix |
|---|---|---|
| Garbled characters | Baud rates differ between the two ends | Set the same baud rate on both devices |
| Missing bytes | Loop runs too slowly, so the buffer overflows | Remove blocking delays and reduce long prints |
| No data at all | TX and RX are not crossed, or grounds are not joined | Connect TX to RX, RX to TX, and GND to GND |
| Frames rejected | Length or checksum logic differs between sender and receiver | Print the raw bytes on both ends and compare |
Exercise
A frame uses a checksum computed as the XOR of its payload bytes. The payload is 0x0F, 0xF0 and 0x33. What checksum does the sender transmit?
Show answer
0x0F XOR 0xF0 is 0xFF. Then 0xFF XOR 0x33 is 0xCC. The sender transmits 0xCC.