Learning Goals 5 min
By the end of this lesson you will be able to:
- Wire a second push button on the breadboard, using
INPUT_PULLUPand two new wires per button — no external resistors. - Combine two conditions into one with
&&(AND — both true) and||(OR — at least one true), then put that combined condition inside anif. - Read a truth table for AND and OR, and predict the LED behaviour of an
if (a && b)sketch for any combination of button states before uploading.
Warm-Up 10 min
The 🔴 stretch task in L01-20 used && without explaining it. Today's lesson gives the two combining operators — && (AND) and || (OR) — their proper introduction, plus a second button so you have something to combine.
Quick-fire puzzle
Identify which English word — AND or OR — each rule uses. Then translate the rule into a condition.
- "You can enter the lift if you press the button and the door is open."
- "The doorbell rings if the front button is pressed or the back button is pressed."
- "Lockdown mode triggers if a window is open and motion is detected."
- "You can play the game if you're over 13 or a parent is with you."
Reveal the answer
- AND — both conditions must be true. Press alone, no lift. Door alone, no lift. Press + door = lift goes.
- OR — either condition is enough. Front rings → doorbell. Back rings → doorbell. Both ring → doorbell (still). Only "neither" results in no doorbell.
- AND — security demands both signals. A window open alone doesn't lock down; motion alone doesn't either. Both together is the alarm condition.
- OR — either qualifier admits you. The two paths are independent; one is enough.
Every rule of the form "if X and Y" or "if X or Y" maps directly to one operator. That's the whole lesson.
New Concept 20 min
The big idea — combine conditions, don't nest them
L01-19 showed you how to nest if blocks: if (X) { if (Y) { …; } } runs the body only when X is true and Y is true. That works, but it indents the code further every time you combine, and the meaning is buried.
With && you can write the same condition as a single if:
if (X && Y) {
// runs only when BOTH X and Y are true
}Flat, readable, no nesting. Same with || for "or":
if (X || Y) {
// runs when EITHER X or Y (or both) is true
}The two operators
| Operator | English name | True when… | Type to type |
|---|---|---|---|
&& | AND | BOTH sides are true | Two ampersands, no space |
|| | OR | AT LEAST ONE side is true (one or both) | Two vertical bars (pipes), no space |
! | NOT (from L01-17) | The side after it was false | One exclamation mark in front |
Truth tables — the full picture in eight rows
A truth table shows every possible combination of the inputs and what the output becomes. For two inputs each being true (T) or false (F), there are four combinations. Memorise these two tables; they cover every && and || you'll ever write.
| AND | — | OR | — | ||
|---|---|---|---|---|---|
A | B | A && B | A | B | A || B |
| F | F | F | F | F | F |
| F | T | F | F | T | T |
| T | F | F | T | F | T |
| T | T | T | T | T | T |
Notice the asymmetry: AND is true only once (when both are T); OR is false only once (when both are F). That asymmetry is the entire reason both operators exist.
Combining a comparison with a button read
The two sides of && and || can be any condition — anything that evaluates to true or false. So all of these are valid:
if (a == LOW && b == LOW) { … } // both buttons pressed
if (presses > 3 && presses < 10) { … } // in a range
if (mode == 0 || mode == 4) { … } // at either end
if (a == LOW && presses >= 5) { … } // button held AND we've had fiveThe condition can be as long as you need it. Just keep it readable — when it spans more than a line, refactor into named smaller pieces.
Short-circuit evaluation — a helpful side-effect
The Arduino is lazy in a good way. When it reaches A && B, it checks A first. If A is false, the whole && can't be true — so the Arduino skips evaluating B entirely. This is called short-circuit evaluation. With ||, it's symmetric: if A is true, the Arduino skips B because the whole expression is already true.
You don't have to think about this for Level 1, but knowing it means you can safely write conditions where the second half might fail if reached without the first half being true. The first half "guards" the second.
Wiring map — three LEDs and now two buttons
Today's hardware: the three-LED setup you have had since L01-10, plus the L01-17 button on D7, plus a new second button on D6. Five components, five signal wires, one shared GND bus. Both buttons use INPUT_PULLUP, so neither needs a resistor.
| Component | Signal pin | Position | Wires (new today) |
|---|---|---|---|
| Red LED | D9 | cols 2–7 (signal in at E2) | unchanged |
| Yellow LED | D10 | cols 10–15 (signal in at E10) | unchanged |
| Green LED | D11 | cols 18–23 (signal in at E18) | unchanged |
| Button A | D7 | col 9, straddling the channel | A9→− rail, D7→J9 |
| Button B (new) | D6 | col 17, straddling the channel | A17→− rail, D6→J17 |
| Shared: | − rail → Arduino GND | ||
Why it matters
Almost every real-world rule involves more than one condition. "Send the email if the user is logged in and the form is valid." "Sound the alarm if a door opens or a window opens." Without && and ||, every such rule would be a tower of nested ifs. With them, the code reads almost like English.
Worked Example 20 min
Goal: build two-button hardware and write a sketch where each LED reacts to a different logical rule — one OR, one AND.
The wiring, and the same board on paper
Five branches now. Hover any component to find it in both drawings — the two buttons are the easiest pair to mix up on the breadboard, and on the schematic they are unmistakably the only two branches with a switch in them.
On the breadboard what you build
On paper what engineers draw
The sketch — RED on OR, GREEN on AND
const int BUTTON_A_PIN = 7;
const int BUTTON_B_PIN = 6;
const int RED_PIN = 9;
const int GREEN_PIN = 11;
void setup() {
pinMode(BUTTON_A_PIN, INPUT_PULLUP);
pinMode(BUTTON_B_PIN, INPUT_PULLUP);
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
}
void loop() {
int a = digitalRead(BUTTON_A_PIN);
int b = digitalRead(BUTTON_B_PIN);
// RED: lights when EITHER button is pressed (OR)
if (a == LOW || b == LOW) {
digitalWrite(RED_PIN, HIGH);
}
else {
digitalWrite(RED_PIN, LOW);
}
// GREEN: lights when BOTH buttons are pressed (AND)
if (a == LOW && b == LOW) {
digitalWrite(GREEN_PIN, HIGH);
}
else {
digitalWrite(GREEN_PIN, LOW);
}
}Test by truth table
Press combinations and check that the LEDs match this table — the row your fingers are creating is the only row that should be lit.
| Button A | Button B | Red LED (A || B) | Green LED (A && B) |
|---|---|---|---|
| released | released | off | off |
| pressed | released | on | off |
| released | pressed | on | off |
| pressed | pressed | on | on |
Trace one condition slowly
Press only Button A. Step through what the Arduino does on a single loop() pass:
a = digitalRead(7)→abecomesLOW.b = digitalRead(6)→bbecomesHIGH(button B released).- First
if:a == LOWis true. Because OR short-circuits on the first true, the chip doesn't even check the second half. Whole expression is true. Red LED on. - Second
if:a == LOWis true. Now AND must check the second half:b == LOWis false. So the whole AND is false. Green LED off.
Basic 7 min
Goal: Verify the truth table by pressing every combination of Button A and Button B and watching the LEDs. No code changes — just the four combinations from the table above. Note any disagreement between your prediction and reality.
Questions:
- Of the four rows in the truth table, which is the only one where both LEDs are on at the same time? ____
- Of the four rows, which is the only one where neither LED is on? ____
- Look at the bold output column for OR and for AND. Which has more Ts — and what does that tell you about how "demanding" each operator is? ____
Challenge 1 7 min
Goal: Add the yellow LED back into the sketch with a third rule — light it when exactly one button is pressed (XOR). XOR isn't a built-in operator in C++, so we build it from &&, || and !.
1. Think first (on paper, no typing yet):
- Fill in the truth table below. Look at the two columns you already have (red's OR and green's AND) beside your yellow column.
- Describe yellow using those two columns in one sentence: "yellow is on when …". Which of
&&,||and!does your sentence need? - Which parts of your condition must be grouped with brackets?
2. Code it. Start from the Worked Example sketch. Add a YELLOW_PIN constant for D10 and set it up in setup(). Then add a third if/else block for yellow, shaped like the red and green ones, with your sentence as its condition.
3. Upload and observe. Press all four combinations and compare with your table.
It works if: yellow is on with only A pressed, on with only B pressed, and off with none or both.
Questions:
- Fill in the truth table for yellow:
| A | B | A || B (red) | A && B (green) | exactly one (yellow) |
|---|---|---|---|---|
| F | F | F | F | ____ |
| F | T | T | F | ____ |
| T | F | T | F | ____ |
| T | T | T | T | ____ |
- Which two rows light the yellow LED? Press those combinations and confirm. ____
- Write the sentence you turned into code: "yellow is on when ____".
- Take the brackets out of your condition, predict what changes, then upload and test. Were you right? ____
- Can you find a much shorter condition that does the same job? (Hint: when exactly one is pressed, are
aandbthe same or different?) ____
Challenge 2 6 min
Goal: The "key-pair lock". The green LED unlocks (lights up) only when you press a specific sequence: Button A first, then Button B (without releasing A), then let go of both. Releasing in the wrong order, or pressing them in the wrong order, doesn't unlock.
This needs state-change detection from L01-19 plus && from today. It is fiddly — the point isn't to produce a perfect lock, it's to use && in a non-trivial condition.
It works if:
- Press A, then (still holding A) press B → green lights.
- Press B first, then A → green stays dark.
- Let go of either button → green goes off, and the lock is ready for a fresh try.
1. Think first (on paper, no typing yet):
- Draw the timing: two rows, A and B, showing a correct sequence and a wrong one. Mark the exact moments where something must happen.
- When B goes down, the sketch has to know whether A went down first. A plain reading of A can't tell you that. What could the sketch remember, and when does it get set and cleared?
- For each marked moment, write the condition in words: "when … and … and …". How many things must be true at once when B goes down?
2. Code it. Start from the Worked Example sketch and add the state-change pattern from L01-19 for both buttons.
3. Upload and observe. Try the right order, the wrong order, and letting go in each order.
Questions:
- If you accidentally press both buttons at the exact same moment, what does your sketch decide? Which is the "first" press? ____
- How many conditions are joined with
&&in the check that lights green? Could you simplify by introducing a named helper? ____
Challenge 3 15 min
The microwave panel
Real microwaves have a safety rule: the heating element only fires if the door is closed and the user has pressed Start. Open the door mid-cook → the magnetron shuts off. Press Start with the door open → nothing happens.
Today we simulate that:
- Button A = the door. Pressed = door closed; released = door open. (We pretend, since real microwave doors are switches that close when shut.)
- Button B = the Start key. Pressed = "user wants to cook".
- Green LED = the magnetron. Lit means "heat is on".
- Red LED = the warning light. Lit means "door is open, can't cook".
Your task — implement these three rules:
- Green LED on if Button A is pressed AND Button B is pressed. (Door closed AND Start pressed.)
- Red LED on if Button A is released. (Door open — warning, regardless of Start.)
- Both LEDs off if Button A is pressed AND Button B is released. (Door closed but not cooking.)
1. Think first (on paper): Draw the truth table for A and B (four rows) and fill in red and green for each. Which rule do you test first? Could you give the two readings names that match the story, so the conditions read like the rules?
2. Code it. Start from the Worked Example sketch.
3. Upload and observe. Test all four rows of your table on the real buttons.
It works if:
- Door open (A released), any Start state → red LED on, green LED off.
- Door closed (A pressed), Start released → both LEDs off.
- Door closed (A pressed), Start pressed → green LED on, red LED off.
- You can't ever have both LEDs on at the same time.
Recap 5 min
Two logical operators turn two conditions into one. && (AND) is true only when both sides are true — the demanding one. || (OR) is true when at least one side is true — the easy-going one. Combined with comparison operators and if/else if/else, you can encode almost any rule you'd describe in English. Always use the doubled form (&&, ||) for logic — the single versions exist but mean something different and rarely what you want.
- && (logical AND)
- Combines two conditions into one that's true only when both are true. Type as two ampersands, no space.
- || (logical OR)
- Combines two conditions into one that's true when at least one is true. Type as two pipes, no space.
- ! (logical NOT, from L01-17)
- Flips a true/false value.
!(a && b)is true when "a AND b" is false. - Truth table
- A complete listing of every possible input combination and the matching output. For two inputs, it has 4 rows; for three inputs, 8 rows.
- Short-circuit evaluation
- The Arduino's habit of skipping the second half of
&&or||when the first half already settles the answer. Useful for "guard" patterns. - Named intermediate
- Storing the result of a comparison in a well-named
int(likedoorClosed) so that later conditions read like English. A readability trick used heavily in real codebases.
Extra Mission 5 min
Part 1 — Design a two-input safety rule
Many machines only run when two things are true at once. A blender spins only with the lid on and the button pressed. A safe opens only when two keys turn together. Invent a machine with a two-input safety rule. On paper, design it.
Your design must include:
- The machine, and what its two inputs stand for.
- What the red, yellow and green LEDs each mean.
- A full truth table: all four combinations of the two inputs, and which LED lights for each.
- Each rule written with AND, OR or NOT, such as "green if lid AND start".
- A check that exactly one LED is lit in every row.
Part 2 — Make it
Build your machine on today's circuit: two buttons on D7 and D6 with INPUT_PULLUP, and all three LEDs.
- Store each input in a named variable, such as
lidOn, using== LOW. - Turn your truth table into one
if/else if/elsechain using&&,||and!. - Reuse the
setLeds()helper from L01-20.
Test all four rows of your truth table on the real buttons.
Bring back next class: your design and truth table, the saved .ino file, and a short video pressing all four combinations.
Heads up for next class: L01-22 "Reaction Timer Game" puts buttons, timing and if/else together in a reflex game.