Arduino Basics: Serial Communication
Table of Contents
Serial communication allows your Arduino to send and receive data from your computer or other devices. It is one of the most important tools for debugging, logging data, and interacting with your projects in real time.
Serial Basics
To use serial communication, you first need to initialize it in the setup()
function:
void setup() {
Serial.begin(9600); // Start serial communication at 9600 baud
}
The number 9600
is the baud rate, which is the speed of communication (bits per second). Both Arduino and the connected device must use the same baud rate.
Serial.print() vs Serial.println()
- Serial.print(value): Sends the value to the Serial Monitor without a newline. The next print statement will continue on the same line.
- Serial.println(value): Sends the value followed by a newline character. The next print statement will start on a new line.
Example:
int sensorValue = analogRead(A0);
Serial.print("Sensor: "); // Prints "Sensor: " on the same line
Serial.println(sensorValue); // Prints the value and moves to next line
Sending Data from Arduino to Computer
You can send text, numbers, or formatted messages to the Serial Monitor for monitoring or debugging:
int tempSensor = A1;
float voltage;
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(tempSensor);
voltage = sensorValue * (5.0 / 1023.0); // Convert to volts
Serial.print("Voltage: ");
Serial.println(voltage); // Print each reading on a new line
delay(500);
}
Serial Plotter
The Arduino IDE includes a Serial Plotter, which graphs numerical data sent via serial in real time. This is particularly useful for visualizing sensor readings or monitoring changes over time.
- Open the Serial Plotter via Tools → Serial Plotter.
- Send numerical values using
Serial.println(value)
. - You can plot multiple variables by printing them separated with commas:
Serial.println(value1, value2, value3);
(Arduino automatically plots them in different colors).
Example: Graphing a Potentiometer
int potPin = A0;
int potValue = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
potValue = analogRead(potPin);
Serial.println(potValue); // Each reading appears on Serial Plotter
delay(100);
}
Tips for Serial Communication
- Always call
Serial.begin()
once insetup()
before using serial functions. - Use
Serial.print()
for inline messages andSerial.println()
for separate lines or plotting. - Keep your baud rate consistent between Arduino and Serial Monitor/Plotter.
- Use Serial communication for debugging complex logic or tracking sensor behavior.
- Be mindful of delay and print frequency to avoid flooding the serial buffer.
Mastering Serial Communication allows you to monitor, debug, and visualize your Arduino projects efficiently, making it easier to build interactive and responsive systems.