Menu
CoddyTech

Read a Serial Character

Part of the Inputs section of Coddy's Arduino journey. Lesson 15 of 22.

The Serial connection works both ways. Text typed into the Serial monitor's box and sent with Send travels to the board one character at a time, and waits there in a buffer until the sketch reads it.

Serial.available() says how many characters are waiting. Serial.read() takes the next one out of the buffer. One character fits in a char variable, written in single quotes:

if (Serial.available() > 0) {
  char c = Serial.read();
  if (c == '1') {
    // 1 was typed
  }
}

'1' in single quotes is the character 1, the key you press. It is not the number 1: the board stores the character as the code 49.

The Serial monitor also sends an invisible newline character, written '\n', after whatever you type. A sketch acts on the characters it knows and skips any others.

challenge icon

Challenge

Easy

The LED is on pin 13. Switch it from the Serial monitor:

  • when a character is waiting, read it into a char
  • '1' turns the LED on, '0' turns it off
  • any other character, like the newline, changes nothing

Press Run, type 1 or 0 into the Serial monitor and press Send, then Check.

Try it yourself

const int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // when a character is waiting, read it
  // '1' turns the LED on, '0' turns it off
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Inputs

Practice on your own: Arduino playground