Until now, the only way the Arduino could communicate with us was by blinking an LED. While charming, an LED is terrible at conveying exact numbers or complex error messages.
To see exactly what the Arduino is thinking, we use Serial Communication.
The Serial Monitor acts as a text console for your microcontroller.
Serial communication is a way for devices to talk to each other by sending data one bit at a time over a single wire. When your Arduino is plugged into your computer via USB, it establishes a virtual serial port connection.
The Arduino IDE has a built-in tool called the Serial Monitor that allows you to view the text being sent from the Arduino over this USB connection.
To use the serial port, you must first initialize it in the setup() function and tell it how fast to talk. This speed is called the Baud Rate.
void setup() {
// Start serial communication at 9600 bits per second
Serial.begin(9600);
}
Once initialized, you can use Serial.print() and Serial.println() inside your loop.
Serial.print("Hello"); prints the text and leaves the cursor right there.Serial.println(" World"); prints the text and moves the cursor to a new line (like pressing Enter).Let’s look at the potentiometer circuit from Lesson 116. We knew the analog value was changing the blink speed, but we didn’t know the exact number. Let’s print it!
int sensorPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(sensorPin);
// Print a label
Serial.print("Potentiometer Value: ");
// Print the actual variable data, followed by a new line
Serial.println(sensorValue);
delay(100); // Small delay to prevent flooding the screen
}
You should now see a continuous stream of text reading Potentiometer Value: 512 (or whatever the number is). As you twist the knob, watch the numbers change on your screen in real-time!
The Serial Monitor is your best friend when writing code. If an if statement isn’t triggering when it’s supposed to, you can use Serial.println() to check the values of the variables right before the if statement to see what’s going wrong. It gives you x-ray vision into the brain of your microcontroller.
[Take your data logging to the next level with a dedicated LCD Screen Display Module to show values without a computer attached!]