09. UART Serial & Debugging
Observe programs and receive commands from a computer.
Learning outcomes
- Explain baud rate and UART framing
- Use print and println
- Read characters and integers
- Add useful diagnostic messages
Parts and preparation
Uno, USB data cable and Arduino IDE Serial Monitor.
Before power: inspect wiring, confirm supply voltage and ensure all connected circuits share GND.
UART
UART sends bits asynchronously over TX and RX. Both ends agree on a baud rate. USB serial on the Uno shares hardware serial pins D0/RX and D1/TX.
Printing
print continues on the same line; println adds a line ending. Labels and units make raw numbers meaningful.
Receiving
available reports waiting bytes. read returns one byte. parseInt reads digit characters into an integer but can wait for its timeout.
Debugging strategy
Print key inputs, decisions and outputsnot every line. Use a moderate update rate so messages remain readable.
Wiring and safe build sequence
- USB connects the Uno to the Serial Monitor
- Avoid external devices on D0/D1 while uploading or debugging
Worked sketch
Download .ino sketchconst byte ledPin = LED_BUILTIN;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
Serial.println("Type 1 for ON, 0 for OFF");
}
void loop() {
if (Serial.available() > 0) {
char command = Serial.read();
if (command == '1') {
digitalWrite(ledPin, HIGH);
Serial.println("LED ON");
} else if (command == '0') {
digitalWrite(ledPin, LOW);
Serial.println("LED OFF");
}
}
}How the code works
- '1' is a character; 1 is a number.
- Line-ending characters are ignored by the else-if chain.
Test and record evidence
Practical evidence checklist
Common faults and checks
- Match 9600 baud.
- If commands repeat unexpectedly, inspect the selected line ending and received characters.
Check your understanding
Q1. Why must baud rates match?
Show answer
The receiver needs the same bit timing as the sender.
Q2. What does Serial.available report?
Show answer
The number of bytes waiting to be read.