Serial Communication
UART debugging, structured data formats, and bidirectional PC-Arduino communication
Skills taught: embedded.serial
UART Serial Basics
Serial is the simplest and most useful debugging tool in embedded programming. Serial.begin(baud) initialises the UART at a given speed; Serial.print() and Serial.println() send data to the PC. The Arduino IDE Serial Monitor (Ctrl+Shift+M) shows incoming data in real time.
void setup() {
Serial.begin(115200); // baud rate must match Serial Monitor
Serial.println(F("=== Boot complete ==="));
Serial.print(F("Free SRAM: "));
// Print multiple types on one line
Serial.print(2048 - 500); // approximate
Serial.println(F(" bytes"));
}
void loop() {
// Print structured CSV data: timestamp, A0, A1
Serial.print(millis());
Serial.print(',');
Serial.print(analogRead(A0));
Serial.print(',');
Serial.println(analogRead(A1));
delay(500);
}
Sending Structured Data as JSON
Plain CSV is easy to parse but fragile. For more robust communication, send data as JSON. A Python script on the PC can receive it via pyserial and log to a database or display a live chart.
// Send sensor readings as JSON — easy to parse on PC
// Format: {"t":1234,"temp":23.4,"hum":55.1,"light":789}
#include <DHT.h>
DHT dht(4, DHT22);
void setup() {
Serial.begin(115200);
dht.begin();
}
void loop() {
float temp = dht.readTemperature();
float hum = dht.readHumidity();
int light = analogRead(A0);
if (!isnan(temp) && !isnan(hum)) {
Serial.print(F("{\"t\":"));
Serial.print(millis() / 1000);
Serial.print(F(",\"temp\":"));
Serial.print(temp, 1);
Serial.print(F(",\"hum\":"));
Serial.print(hum, 1);
Serial.print(F(",\"light\":"));
Serial.print(light);
Serial.println(F("}"));
}
delay(2000);
}
Receiving Commands from the PC
Arduino can read commands from the Serial Monitor using Serial.available() (number of bytes waiting) and Serial.read() (read one byte). For multi-character commands, read a complete line into a buffer and parse it.
const int LED_PIN = 13;
String inputBuffer = "";
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(115200);
Serial.println(F("Commands: LED_ON, LED_OFF, STATUS"));
}
void handleCommand(const String& cmd) {
if (cmd == "LED_ON") {
digitalWrite(LED_PIN, HIGH);
Serial.println(F("OK: LED on"));
} else if (cmd == "LED_OFF") {
digitalWrite(LED_PIN, LOW);
Serial.println(F("OK: LED off"));
} else if (cmd == "STATUS") {
Serial.print(F("Uptime: "));
Serial.print(millis() / 1000);
Serial.print(F("s A0: "));
Serial.println(analogRead(A0));
} else {
Serial.print(F("ERR: Unknown command: "));
Serial.println(cmd);
}
}
void loop() {
// Read incoming serial data character by character
while (Serial.available()) {
char c = Serial.read();
if (c == '\n' || c == '\r') {
inputBuffer.trim();
if (inputBuffer.length() > 0) {
handleCommand(inputBuffer);
inputBuffer = "";
}
} else {
inputBuffer += c;
if (inputBuffer.length() > 32) inputBuffer = ""; // overflow guard
}
}
}
SoftwareSerial: Multiple Serial Ports
Arduino Uno has one hardware UART (pins 0/1 — shared with USB). To connect multiple serial devices (GPS module, Bluetooth HC-05, 4G modem), use SoftwareSerial to emulate serial on any two pins.
#include <SoftwareSerial.h>
// SoftwareSerial(RX_pin, TX_pin)
// Connect HC-05 Bluetooth TX → Arduino pin 10
// Connect HC-05 Bluetooth RX → Arduino pin 11
SoftwareSerial bluetooth(10, 11);
void setup() {
Serial.begin(115200); // USB debug
bluetooth.begin(9600); // HC-05 default baud
Serial.println(F("Bluetooth ready"));
bluetooth.println(F("AT")); // test HC-05 with AT command
}
void loop() {
// Bridge: forward bluetooth → USB serial
if (bluetooth.available()) {
Serial.write(bluetooth.read());
}
// Bridge: forward USB serial → bluetooth
if (Serial.available()) {
bluetooth.write(Serial.read());
}
}
Warning: SoftwareSerial disables interrupts while receiving data to maintain bit timing. This interferes with libraries that rely on interrupts (servo, DHT, encoder). For multi-serial Arduino projects, choose an Arduino Mega (4 hardware UARTs) or ESP32 (3 hardware UARTs) instead.
Tip: Use 115200 baud instead of 9600. At 9600 baud, sending a 50-byte JSON packet takes 52 ms — meaning you can only send ~19 packets/second. At 115200 baud, the same packet takes 4.3 ms, allowing 230+ packets/second.
Frequently Asked Questions
Can I use Serial while also using other libraries?
Most libraries are compatible with HardwareSerial. Watch out for SoftwareSerial conflicts and libraries that disable interrupts for long periods, which can corrupt incoming serial data in the buffer.
How do I log Arduino serial data to a file on my PC?
Use Python with pyserial: `import serial; s = serial.Serial('COM3', 115200)` then `s.readline()`. Or use the Arduino IDE's Serial Plotter for live graphs, or CoolTerm/PuTTY for file logging.
My serial data has garbage characters at the start. Why?
This happens when the Serial Monitor is opened before the Arduino finishes booting. The 16 MHz Arduino sends a character at the wrong baud during USB enumeration. It's cosmetic — just clear the monitor or add a 500 ms delay at the start of setup().