๐ ๏ธ Section project: a button that turns on and off
Section 3: Inputs: the buttonLesson 3.3 ยท โฑ 12 min
๐ฏ Project goal
Every press of the button changes the LED: one press turns it on, and the next press turns it off, like a light switch.
We need a variable that remembers the LED's state. On every press we flip the state, then wait until the button is released so one press isn't counted many times.
- Make a variable called on.
- If the button is pressed: set on = its opposite (not on).
- Wait until the button is released (wait until not pressed).
- Turn the LED on if on is true, otherwise turn it off.
๐ Another example: the button turns on but not off
With no โelseโ: one press turns the LED on, and it stays on.



โ๏ธ Practise
Build the project.
โ๏ธ Practise here in the lessonโ Close the labor open the lab in a new page โ
๐ฏ Challenge yourself
Easy
A press blinks the LED 5 times, then it stops.
๐ Show the solution๐ Hide the solution


Result: five blinks.
Medium
A press lights the LED for two seconds (a timer).
๐ Show the solution๐ Hide the solution


Result: it lights up, then goes off by itself.
Hard
Not pressed, the LED blinks slowly (waiting), and pressed, it stays steadily on.
๐ Show the solution๐ Hide the solution


Result: a waiting blink, then a steady light.

