Learning Goals 5 min
By the end of this lesson you will be able to:
- Use
Serial.available()at the top ofloop()to check whether the user has typed anything into the Serial Monitor. - Use
Serial.read()to fetch one typed character at a time into acharvariable. - Compare the character with single-quote literals like
'r'or'g'and run different code for different commands — turning the laptop keyboard into a remote control for the Arduino.
Warm-Up 10 min
For two lessons now the conversation has been one-way: the Arduino talks, you read. Today the cable becomes a proper conversation — you type, the Arduino reacts. The same Serial Monitor window you've been reading from has had an input box at the top all along; today you finally use it.
Quick-fire puzzle
Imagine the Arduino as a tiny friend sitting on your desk, deaf and blind, listening only down the USB cable. You type a single letter into the Monitor and hit Send. Three things must happen before the Arduino can react:
- Your laptop has to send the keystroke down the cable.
- The Arduino has to notice something arrived.
- The Arduino has to look at what it was and decide what to do.
Which step do you think is the trickiest for a beginner — and why?
Reveal the answer
Step 2 — noticing — is the tricky one. The Arduino's loop() is running at thousands of cycles per second, mostly doing nothing. A character could arrive at any moment. So before reading anything, the sketch must check "is there anything waiting for me?" That check is what Serial.available() does. Skip the check and your sketch will try to read empty air — and what it reads back will be garbage.
Steps 1 and 3 are easy: the laptop already knows how to send (when you click Send), and matching a single character against 'r' is just an if statement (L01-20). The whole lesson is really about that one "is anything waiting?" check.
New Concept — the receive buffer and the three lines that read it 15 min
The big idea — a tiny mailbox
The Arduino doesn't sit and wait for you to type — it would never get anything else done. Instead, the hardware has a small receive buffer: a little mailbox that quietly fills with characters as they arrive down the cable, even while your loop() is busy with other work. Your job, every loop pass, is to peek in the mailbox and ask "is there any post?" If yes, fetch one item. If no, move on.
That mailbox holds up to 64 characters on a Uno before it starts dropping the oldest ones. Tiny — but for a person typing one letter at a time, more than enough.
The two lines you need to memorise
Add these to the two from L01-24 and you can have a full conversation.
Serial.available(); // returns how many bytes are waiting (0 = nothing typed)
Serial.read(); // returns the oldest byte and removes it from the mailboxThe standard input pattern
Almost every input sketch in this lesson — and the next two — has the same shape inside loop():
void loop() {
if (Serial.available() > 0) {
char c = Serial.read();
// decide what to do with c
}
}Three details to notice:
- The
ifguard.Serial.available() > 0means "there's at least one character waiting". Without this check,Serial.read()would return-1(the "nothing here" value) and your logic would behave randomly. - The
chartype.charis a one-character variable type — exactly the right shape for a single typed letter. (It's actually an 8-bit integer with a letter painted on it, but L01-27 is when we lift the hood.) - One character per
loop()pass. Each pass reads one character. If the user types"abc"and hits Send, the buffer gets three letters and they're read on three consecutive loop passes. The pattern handles this naturally — you don't need to do anything special.
Comparing with single-quote literals
Once you have a char in a variable, comparing it is exactly like comparing numbers — only the values use single quotes:
if (c == 'r') { // note: SINGLE quotes, one character only
digitalWrite(RED_PIN, HIGH);
}
else if (c == 'g') {
digitalWrite(GREEN_PIN, HIGH);
}Single quotes for one character, double quotes for strings (text of any length). 'r' and "r" look identical to a human but mean different things to the compiler — single is a number, double is a sequence of numbers ending in a hidden zero. Today, always use single.
The "Newline" setting matters
Look at the bottom-left of the Serial Monitor — there's a dropdown that says "No line ending", "Newline", "Carriage return", or "Both". This controls what the Monitor secretly tacks onto the end of every message you Send.
If it's set to "Newline", typing r and hitting Send actually delivers two characters to the Arduino: r followed by a hidden newline character. Your sketch then reads r, runs the red branch, and immediately reads the newline — which doesn't match any of your 'r'/'g'/'y' commands, so nothing happens. Confusing if you don't know it.
For today's single-letter commands, set the dropdown to "No line ending". We'll deal with newlines properly in L01-28.
Why it matters
Reading from Serial turns your sketch into a remote-controlled device. The patterns are tiny — five lines of code — but they unlock an entire family of projects: typing commands to drive LEDs, sliders to dial in motor speed, text triggers to play tunes, even simple chat bots. Every IoT device in your home accepts commands over a wire or radio; this is the simplest form of that pattern.
Worked Example — the typed traffic light 20 min
You're going to type r, y, or g into the Monitor and watch the corresponding LED light up on your breadboard — like operating a tiny traffic light by keyboard. Same wiring as L01-15 (three LEDs on D9, D10, D11, sharing GND through the − rail). No new components.
Step 1 — Refresh the wiring
If you've already broken down the L01-15 circuit, rebuild it. Three LEDs, each with a 220 Ω resistor, anodes to D9 (red), D10 (yellow), D11 (green), cathodes back to GND through the − rail. Same picture as L01-15.
On the breadboard what you build
On paper what engineers draw
Step 2 — The sketch
Open a new sketch and type this in:
// Typed traffic light — r/y/g key controls LEDs
const int RED_PIN = 9;
const int YELLOW_PIN = 10;
const int GREEN_PIN = 11;
void setLeds(int r, int y, int g) {
digitalWrite(RED_PIN, r);
digitalWrite(YELLOW_PIN, y);
digitalWrite(GREEN_PIN, g);
}
void setup() {
Serial.begin(9600);
pinMode(RED_PIN, OUTPUT);
pinMode(YELLOW_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
Serial.println("Type r, y, or g and press Send.");
}
void loop() {
if (Serial.available() > 0) {
char c = Serial.read();
if (c == 'r') {
setLeds(HIGH, LOW, LOW);
Serial.println("RED");
}
else if (c == 'y') {
setLeds(LOW, HIGH, LOW);
Serial.println("YELLOW");
}
else if (c == 'g') {
setLeds(LOW, LOW, HIGH);
Serial.println("GREEN");
}
}
}Step 3 — Upload, set the line-ending, type
- Upload the sketch.
- Open the Serial Monitor at 9600 baud.
- At the bottom-left of the Monitor, set the line-ending dropdown to "No line ending". This is the step everyone forgets.
- In the text box at the top, type
rand click Send. The red LED lights up; the Monitor echoesRED. - Type
ySend → yellow.gSend → green.ragain → red. - Now try typing
x. Nothing happens — none of theifbranches match, so the sketch just goes back to waiting. That's the right behaviour: unknown commands are silently ignored.
r typed in the top box, RED echoed in the output below. Both dropdowns set correctly — line-ending off, baud rate 9600. Get these two wrong and the sketch behaves strangely.Step 4 — Try a multi-character send
Now type rygr (no spaces) and hit Send. Four characters arrive at once. Watch the LEDs and Monitor:
RED
YELLOW
GREEN
REDEach loop pass reads one character, runs the matching branch, and moves on. With four characters in the buffer and a loop that runs thousands of times per second, all four are processed in well under a millisecond. The LEDs flash through red → yellow → green → red so fast you only see the final one (red). The Monitor, though, captures every step. This is the standard input pattern doing exactly what it should.
Trace it on paper
For the input "rg", fill in what happens on each loop pass.
| Pass | Buffer before | Serial.available() | c after read | Branch taken | Buffer after |
|---|---|---|---|---|---|
| 1 | r g | 2 | 'r' | ____ | ____ |
| 2 | ____ | ____ | ____ | ____ | (empty) |
| 3 | (empty) | 0 | — | none (the if is false) | (empty) |
If you can fill in pass 1 and pass 2 without uploading, you've understood the buffer.
Basic 7 min
Goal: An echo sketch. Whatever character you type, the Arduino prints You sent: X back at you, where X is the character. No wiring at all — just the USB cable.
Here is what the Serial Monitor should show after you send x, then 7:
You sent: x You sent: 7
1. Think first (on paper, no typing yet):
- The Worked Example already reads one character into a variable. What is that variable called, and where in
loop()does it hold the new character? - The reply has two parts: a label that never changes, and the character. Which part must stay on the same line, and which part should finish the line? (Think back to L01-24.)
2. Code it. Start a new sketch. Copy only the "is anything waiting? then read one character" part of the Worked Example into it — no LEDs. Then add your reply where the character has just been read.
3. Upload and observe. Open the Monitor at 9600 baud, set "No line ending", and send a few single characters. Compare with the box above.
It works if: typing x and pressing Send shows You sent: x on its own line.
Questions:
- Which two calls did you add, and which one ends the line? ____
- Type
helloand hit Send. How many lines appear in the Monitor and why? ____ - Change the line-ending dropdown from "No line ending" to "Newline". Re-send
hello. How many lines now, and what's the extra one? ____ - Type a space, then Send. Does anything appear? What's on the line after
You sent:? ____
Challenge 1 7 min
Goal: A toggle sketch. Wire one LED on D9 (L01-07 circuit). Type t to toggle the LED — each t Send flips its state from off → on or on → off. No delay; the LED stays in whatever state you last set it to.
Sending t three times, then x, should give something like this (and the LED goes on, off, on):
toggled, now 1 toggled, now 0 toggled, now 1
1. Think first (on paper, no typing yet):
- To flip the LED, the sketch has to remember whether it is on or off right now. Where must that memory live so it survives from one pass of
loop()to the next? - When a
tarrives, what three jobs have to happen, and in what order? Write them as plain-English steps. - How can you turn 0 into 1 and 1 into 0 in one go? (L01-17 showed you an operator for "not".)
2. Code it. Start from your Basic echo sketch. Add the LED pin and whatever you need to remember the state, then make t do your three steps.
3. Upload and observe. Send t a few times, then a different letter. Watch the LED and the Monitor together.
It works if: each t flips the LED, any other key does nothing, and the Monitor tells you the new state.
Questions:
- How did you flip
ledState? If you used!: whenledStateis 0, what does!ledStatebecome? When it's 1? ____ - Type
tttt(four t's) and hit Send once. The Monitor prints four lines instantly. What state does the LED end up in — on or off — and why? ____ - Add a
qcommand that quits by forcing the LED off regardless of state. Where in yourloop()does the newelse ifgo? ____
Challenge 2 6 min
Goal: A tone keyboard. Wire a piezo buzzer on D8 (L01-14 circuit). Each of the keys a, s, d, f, g, h, j plays a different note of the C-major scale (C, D, E, F, G, A, B). One key per Send.
The frequencies (in Hz): C 262 · D 294 · E 330 · F 349 · G 392 · A 440 · B 494.
1. Think first (on paper, no typing yet):
- The Worked Example decides between
r,yandg. How many choices does your keyboard need? How will you write "if it's this key… otherwise if it's that key…"? - Which instruction from L01-14 makes the buzzer play a note? What three things does it need to be told?
- Make a small table: key → note → frequency. That table is your plan.
2. Code it. Start from the Worked Example sketch. Swap the LED pins for a buzzer pin and replace the r/y/g branches with your own. Get two keys working first, upload, then add the rest.
3. Upload and observe. Play the keys one at a time, a to j. Does each step sound higher than the last?
It works if: each of the seven keys plays its own note, and the notes rise from a to j.
Questions:
- Type
adgjand Send. Do you hear all four notes, or just one? Why? ____ (Hint: eachtone(…, 300)overrides the previous one almost immediately.) - If you wanted to actually hear all four notes as a quick arpeggio, what one call from L01-14 would you add inside each branch after the
tone? ____ - Add an eighth key —
k— that plays high C (523 Hz). One newelse if. ____
Challenge 3 — the four-key remote 10 min
"One Arduino, four commands"
Combine all of Cluster B and C in one tiny command shell. Wire three LEDs on D9/D10/D11 and a piezo buzzer on D8 (the L01-15 circuit). Now build a sketch that responds to four typed commands:
| Key | Effect |
|---|---|
r | Red LED on, others off, buzzer silent. |
g | Green LED on, others off, buzzer silent. |
b | Beep the buzzer at 440 Hz for 200 ms. LEDs unchanged. |
q | Quit: all LEDs off, buzzer silent. |
Your task:
- Reuse the
setLeds(r, y, g)helper from L01-23. - Use the standard input pattern with a four-way
if/else ifchain. - After every command, print a short confirmation to the Monitor (e.g.
RED,GREEN,BEEP,QUIT). - Print a helpful
"Commands: r g b q"banner insetup()so a fresh user knows what to type.
Sending rbgbq in one go should leave this in the Monitor:
Commands: r g b q RED BEEP GREEN BEEP QUIT
1. Think first (on paper, no typing yet):
- For each of the four keys, write what happens to the red, yellow and green LEDs and to the buzzer. Which commands touch the LEDs and which leave them alone?
qhas to silence the buzzer even if a beep is still going. Which instruction from L01-14 stops a tone?- What should happen if someone sends a letter that isn't one of the four?
2. Code it. Start from the Worked Example sketch (it already has setLeds and the read-one-character pattern). Add the buzzer, then one command at a time — upload after each.
3. Upload and observe. Try each key on its own, then send rbgbq in one go and compare the Monitor with the box above.
It works if:
- Typing
rSend turns only the red LED on. Typinggswaps it for green. Typingbbeeps without changing the LED. Typingqturns everything off. - Typing
rbgbqas one Send runs all five commands in sequence: red, beep, green, beep, off.
Recap 5 min
The Arduino has a tiny receive mailbox that fills with characters as they arrive down the USB cable. Every loop pass, the standard input pattern asks "is anything in there?" with Serial.available(); if yes, it grabs one with Serial.read() into a char and runs whichever if/else if branch matches. Compare with single-quote literals. Set the Monitor's line-ending to "No line ending" while you're working with one-letter commands. Five lines of code turn the laptop keyboard into a remote control for your sketch.
- Receive buffer
- A small piece of memory (about 64 bytes on a Uno) that automatically stores incoming characters from the USB cable until your sketch is ready to read them.
Serial.available()- Returns the number of bytes waiting in the receive buffer right now. Returns 0 when nothing is waiting. Use as the
ifguard before every read. Serial.read()- Returns the oldest byte from the buffer and removes it. Returns
-1if the buffer is empty — which is why you always guard it withSerial.available()first. char- The data type for exactly one character. Stores it as a small integer (its character code), but you can compare and assign it like a letter.
- Single-quote literal
- A character written between single quotes —
'r','?','1'. One character, never more. Different from a double-quoted string like"r", which is a sequence of characters. - Line-ending dropdown
- The Monitor setting that adds an invisible newline (and/or carriage return) to the end of every Send. Set to "No line ending" for single-character commands; we'll need other settings in L01-28.
Extra Mission 5 min
Part 1 — Design a keyboard-controlled gadget
Pick a gadget that could take orders from a keyboard — a desk lamp, a doorbell, a toy robot's eyes. On paper, design its one-letter command set.
Your design must include:
- A name and a one-sentence job for the gadget.
- At least five commands. Each one is a single letter with the job it does.
- The short reply the gadget prints after each command.
- What happens when someone types a letter that is not a command.
- Which pins its LEDs and buzzer use.
Part 2 — Make it
Build your gadget with up to three LEDs and the buzzer. Use the standard input pattern and an if/else if chain. Print a Commands: … banner in setup() listing every letter.
Bring back next class:
- The saved
.inofile. - A Serial Monitor screenshot showing every command and its reply.
- A photo of your working circuit.
Heads up for next class: L01-27 "ASCII Basics" answers the question we kept ducking today — what is a character actually, under the hood? You'll discover that the letter A is the number 65, and that you can do arithmetic on letters as easily as on numbers. That unlocks several powerful tricks in L01-28's switch/case lesson.