ElectronParade

← Back to Academy

Lesson 118: The Serial Monitor (Talking to your computer)

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 Arduino IDE Serial Monitor The Serial Monitor acts as a text console for your microcontroller.

What is Serial Communication?

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.

Setting up Serial

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); 
}

Printing Data

Once initialized, you can use Serial.print() and Serial.println() inside your loop.

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
}

Using the Serial Monitor

  1. Upload the code above to your Arduino.
  2. In the Arduino IDE, click the magnifying glass icon in the top right corner (or go to Tools -> Serial Monitor).
  3. A new window will pop up.
  4. Important: Check the dropdown menu in the bottom right of the Serial Monitor window. Make sure it is set to 9600 baud. If it’s set to the wrong speed, you will just see random garbage characters.

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 Ultimate Debugging Tool

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!]