How to Print to Serial Monitor in Arduino: Simple Guide
To print to the serial monitor in Arduino, first start communication with
Serial.begin(baud_rate) in setup(). Then use Serial.print() or Serial.println() in loop() or other functions to send text or numbers to the monitor.Syntax
To print to the serial monitor, you use these main commands:
Serial.begin(baud_rate);- starts serial communication at the speed you choose (baud rate).Serial.print(data);- prints data without moving to a new line.Serial.println(data);- prints data and moves to a new line.
The baud rate is usually set to 9600, which is a common speed for serial communication.
arduino
void setup() { Serial.begin(9600); // Start serial communication at 9600 baud } void loop() { Serial.print("Hello"); // Print without newline Serial.println(" World!"); // Print with newline delay(1000); // Wait 1 second }
Example
This example shows how to print a message and a number to the serial monitor every second.
arduino
void setup() { Serial.begin(9600); // Initialize serial communication } void loop() { int sensorValue = analogRead(A0); // Read analog pin A0 Serial.print("Sensor value: "); Serial.println(sensorValue); // Print value with newline delay(1000); // Wait 1 second }
Output
Sensor value: 523
Sensor value: 520
Sensor value: 518
...
Common Pitfalls
Some common mistakes when printing to the serial monitor are:
- Not calling
Serial.begin()insetup(), so no data is sent. - Using a baud rate in the code that does not match the serial monitor's baud rate.
- Forgetting to open the serial monitor in the Arduino IDE.
- Using
Serial.print()when you want a new line, missingSerial.println().
arduino
/* Wrong: Missing Serial.begin() */ void setup() { // Serial.begin(9600); // This line is missing } void loop() { Serial.println("Hello"); // This will not print anything delay(1000); } /* Right: */ void setup() { Serial.begin(9600); // Correctly start serial communication } void loop() { Serial.println("Hello"); delay(1000); }
Quick Reference
Here is a quick cheat sheet for printing to the serial monitor:
| Command | Description | Example |
|---|---|---|
| Serial.begin(baud_rate) | Start serial communication at given speed | Serial.begin(9600); |
| Serial.print(data) | Print data without newline | Serial.print("Value: "); |
| Serial.println(data) | Print data with newline | Serial.println(123); |
| delay(ms) | Pause program for ms milliseconds | delay(1000); |
Key Takeaways
Always start serial communication with Serial.begin() in setup().
Use Serial.print() to print without a new line and Serial.println() to print with a new line.
Make sure the baud rate in your code matches the serial monitor's baud rate.
Open the serial monitor in the Arduino IDE to see the printed output.
Use delay() to space out prints so you can read the output clearly.