Unit B - Inputs & Outputs

09. UART Serial & Debugging

Observe programs and receive commands from a computer.

Estimated time 3 hours

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 Serial & Debugging instructional connection diagram
Open the diagram for a larger view. Trace every connection before building.

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

  1. USB connects the Uno to the Serial Monitor
  2. Avoid external devices on D0/D1 while uploading or debugging
Power rule: switch off before moving wires. Arduino I/O pins are control signals; high-current loads require a driver and suitable external supply.
const 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. '1' is a character; 1 is a number.
  2. Line-ending characters are ignored by the else-if chain.

Test and record evidence

Expected result: Typing 1 or 0 controls the onboard LED and prints confirmation.

Practical evidence checklist

Common faults and checks
  • Match 9600 baud.
  • If commands repeat unexpectedly, inspect the selected line ending and received characters.
Extension challenge: Accept a brightness from 0 to 255 with parseInt and apply it to a PWM LED.

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.