Lesson 10 / 25

Serial (UART) for Debugging and Data

Serial.begin, print, read.

Asynchronous serial

A UART sends bytes over two wires, TX and RX, with no shared clock, so both sides must agree on the baud rate (for example 9600 or 115200) and frame format (usually 8N1). On the Uno R3 the hardware UART is on pins 0 (RX) and 1 (TX) and is also connected to the USB-to-serial chip, which is why you should avoid using those pins for other things while using USB. Serial.print() is the main debugging tool in Arduino work; Serial.available() and Serial.read() receive data. Connect TX to the other device's RX, share a ground, and match voltage levels (5 V versus 3.3 V).

Talking to PCs, sensors and displays

UART, I2C and SPI are the three serial buses you will meet in almost every project.

Three ideas: Serial/UART, I2C, SPI and libraries.
Figure 4.1 — UART, I2C and SPI links from one microcontroller.

A tiny command interface

Type a line such as "led on" in the serial monitor (newline line ending).

String line;

void setup() {
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.println(F("Ready. Commands: led on | led off"));
}

void loop() {
  while (Serial.available() > 0) {
    char c = Serial.read();
    if (c == '\n') {
      line.trim();
      if (line == "led on")       digitalWrite(LED_BUILTIN, HIGH);
      else if (line == "led off") digitalWrite(LED_BUILTIN, LOW);
      else Serial.println(F("Unknown command"));
      line = "";
    } else if (line.length() < 32) {
      line += c;                       // cap length to protect tiny RAM
    }
  }
}

Garbage in the monitor?

Random characters usually mean a baud-rate mismatch between Serial.begin() and the serial monitor setting.

Quick check: What must both ends of a UART link agree on?

  • The baud rate and frame format
  • The I2C address
  • A shared clock line
  • The SPI mode
Answer

The baud rate and frame format — UART is asynchronous: timing comes from the agreed baud rate.