How to Read from Serial Monitor in Arduino: Simple Guide
To read data from the serial monitor in Arduino, use
Serial.available() to check if data is available and Serial.read() to read incoming bytes. Initialize serial communication with Serial.begin(baud_rate) in the setup() function.Syntax
The basic syntax to read from the serial monitor involves three main parts:
Serial.begin(baud_rate);- Starts serial communication at the specified speed.Serial.available()- Returns the number of bytes available to read.Serial.read()- Reads one byte of incoming serial data.
Use these inside your setup() and loop() functions to handle serial input.
arduino
void setup() { Serial.begin(9600); // Start serial communication at 9600 baud } void loop() { if (Serial.available() > 0) { // Check if data is available char incomingByte = Serial.read(); // Read one byte // Use incomingByte as needed } }
Example
This example reads characters sent from the serial monitor and prints them back with a message. It shows how to wait for input and respond.
arduino
void setup() { Serial.begin(9600); // Initialize serial communication Serial.println("Send a character:"); } void loop() { if (Serial.available() > 0) { char received = Serial.read(); Serial.print("You sent: "); Serial.println(received); } }
Output
Send a character:
You sent: A
You sent: B
You sent: C
Common Pitfalls
- Not calling
Serial.begin()insetup()causes no communication. - Reading from serial without checking
Serial.available()can cause errors or block code. - Reading only one byte when multiple bytes are sent may miss data.
- For strings, reading byte-by-byte without buffering can be tricky.
Always check Serial.available() before reading and consider reading all available bytes in a loop.
arduino
void loop() { // Wrong: reading without checking availability // char c = Serial.read(); // May read -1 if no data // Right: check before reading while (Serial.available() > 0) { char c = Serial.read(); Serial.print(c); } }
Quick Reference
| Function | Description |
|---|---|
| Serial.begin(baud_rate) | Starts serial communication at the given speed |
| Serial.available() | Returns number of bytes available to read |
| Serial.read() | Reads one byte from serial input |
| Serial.println(data) | Prints data with a new line to serial monitor |
| Serial.print(data) | Prints data without a new line |
Key Takeaways
Always start serial communication with Serial.begin() in setup().
Use Serial.available() to check if data is ready before reading.
Read serial data byte-by-byte using Serial.read().
For multiple bytes, read in a loop until no data remains.
Print responses with Serial.print() or Serial.println() to see output.