Serial Communication & Debugging
Serial communication is the simplest way to get information from your Arduino to your computer — and back again. The USB connection provides a serial link over which you can exchange text.
The Serial Monitor
The Arduino IDE includes a Serial Monitor (magnifying glass icon in the top-right) that lets you:
- Send commands to the Arduino via text input
- Receive data from the Arduino (print statements)
void setup() {
Serial.begin(9600); // Initialize serial at 9600 baud
}
void loop() {
Serial.println("Hello from Arduino!");
delay(1000);
}Serial Communication with Arduino
Serial communication allows the Arduino to talk to the Serial Monitor and to other serial devices:
void setup() {
Serial.begin(9600);
}
void loop() {
// Read from serial (e.g., commands from computer)
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
Serial.print("Command received: ");
Serial.println(command);
}
// Send data to serial
Serial.print("Sensor value: ");
Serial.println(analogRead(A0));
delay(100);
}Sending Commands to Arduino
You can send commands from the Serial Monitor to control your Arduino:
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available()) {
String cmd = Serial.readStringUntil('\n');
if (cmd == "ON") {
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("LED turned ON");
} else if (cmd == "OFF") {
digitalWrite(LED_BUILTIN, LOW);
Serial.println("LED turned OFF");
} else if (cmd == "STATUS") {
Serial.println(digitalRead(LED_BUILTIN) ? "LED ON" : "LED OFF");
}
}
}Debugging Best Practices
- Use the Serial Monitor for quick debugging
- Use Serial Plotter for sensor data visualization
- Use descriptive Serial.print() statements to trace code flow
- Use different baud rates for different streams
Key Takeaways
Serial.begin(baud)initializes serial communicationSerial.available()checks if data is waiting to be readSerial.readStringUntil('\n')reads a line of textSerial.print()andSerial.println()send data to serial output- Baud rate must match between
Serial.begin()and Serial Monitor
Resources
- Arduino.cc - Serial: https://www.arduino.cc/reference/en/language/functions/communication/serial/
- Arduino Serial Communication Tutorial: https://www.arduino.cc/en/Tutorial/BuiltInExamples/SerialEvent
- Video: Arduino Serial Monitor - https://www.youtube.com/watch?v=Y5uiy13Rk5A