Bird
Raised Fist0
Raspberry Piprogramming~10 mins

LED toggle with button in Raspberry Pi - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - LED toggle with button
Start
↓
Wait for button press
↓
Button pressed?
No→Wait
Yes↓
Toggle LED state
↓
Update LED output
↓
Back to wait
The program waits for a button press, then toggles the LED state and updates the LED output, repeating this cycle.
Execution Sample
Raspberry Pi
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)

led_state = False
while True:
    button = GPIO.input(23)
    if button == GPIO.LOW:
        led_state = not led_state
        GPIO.output(18, led_state)
        time.sleep(0.3)
This code toggles an LED on pin 18 each time the button on pin 23 is pressed.
Execution Table
StepButton InputCondition (button pressed?)LED State BeforeLED State AfterActionDelay
1HIGHNoFalseFalseWaitNo
2HIGHNoFalseFalseWaitNo
3LOWYesFalseTrueToggle LED ONYes (0.3s)
4LOWYesTrueFalseToggle LED OFFYes (0.3s)
5HIGHNoFalseFalseWaitNo
6LOWYesFalseTrueToggle LED ONYes (0.3s)
ExitN/ALoop continuesN/AN/AProgram runs indefinitelyN/A
💡 The program runs forever, toggling LED each time button is pressed (button LOW).
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 4After Step 6Final
led_stateFalseFalseTrueFalseTrueTrue
buttonN/AHIGHLOWLOWLOWLOW
Key Moments - 3 Insights
Why does the LED toggle only when the button input is LOW?
Because the button is set up with a pull-up resistor, pressing it connects the pin to ground, making input LOW. The execution_table rows 3,4,6 show toggling happens only when button input is LOW.
Why is there a delay after toggling the LED?
The delay (0.3s) prevents the program from toggling the LED multiple times during one press due to button bouncing, as seen in execution_table rows 3 and 4.
What happens if the button is held down?
The LED toggles once per loop iteration with button LOW, but the delay slows toggling. The program does not detect button release explicitly, so holding the button toggles LED repeatedly but slowly.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the LED state after step 3?
ANo change
BFalse (LED OFF)
CTrue (LED ON)
DError
💡 Hint
Check the 'LED State After' column at step 3 in execution_table.
At which step does the program detect the button is pressed for the first time?
AStep 3
BStep 1
CStep 5
DStep 6
💡 Hint
Look at the 'Condition (button pressed?)' column for the first 'Yes' in execution_table.
If the delay after toggling was removed, what would happen?
ALED would stay ON permanently
BLED would toggle very fast and flicker
CButton presses would be ignored
DProgram would crash
💡 Hint
Consider the purpose of the delay in execution_table rows 3 and 4.
Concept Snapshot
LED toggle with button:
- Setup button input with pull-up resistor
- Read button state in loop
- If button pressed (input LOW), invert LED state
- Update LED output
- Add delay to avoid multiple toggles per press
Full Transcript
This program runs on a Raspberry Pi to toggle an LED on and off using a button. The button is connected with a pull-up resistor, so when pressed, the input reads LOW. The program continuously checks the button state. When it detects a press (LOW), it changes the LED state from ON to OFF or OFF to ON. It then updates the LED output pin accordingly. A short delay after toggling prevents the LED from flickering due to button bounce. The program loops forever, waiting for button presses to toggle the LED.

Practice

(1/5)
1.

What is the main purpose of using a button in an LED toggle program on Raspberry Pi?

easy
A. To provide power to the LED
B. To increase the brightness of the LED
C. To detect user input and change the LED state
D. To reset the Raspberry Pi

Solution

  1. Step 1: Understand the role of the button

    The button acts as an input device that the user can press to send a signal to the Raspberry Pi.
  2. Step 2: Connect button press to LED behavior

    Each time the button is pressed, the program toggles the LED state (turns it on if off, or off if on).
  3. Final Answer:

    To detect user input and change the LED state -> Option C
  4. Quick Check:

    Button press controls LED toggle = B [OK]
Hint: Button input changes LED state on press [OK]
Common Mistakes:
  • Thinking button powers the LED
  • Confusing button with LED brightness control
  • Assuming button resets the device
2.

Which of the following is the correct way to set up a GPIO pin 17 as an output for the LED in Python using RPi.GPIO?

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
# What goes here?
easy
A. GPIO.setup(17, GPIO.OUT)
B. GPIO.setup(17, GPIO.IN)
C. GPIO.output(17, GPIO.OUT)
D. GPIO.input(17, GPIO.OUT)

Solution

  1. Step 1: Identify the function to configure pin mode

    GPIO.setup(pin_number, mode) is used to set a pin as input or output.
  2. Step 2: Set pin 17 as output

    Use GPIO.setup(17, GPIO.OUT) to configure pin 17 as an output for the LED.
  3. Final Answer:

    GPIO.setup(17, GPIO.OUT) -> Option A
  4. Quick Check:

    GPIO.setup with GPIO.OUT sets output pin = A [OK]
Hint: Use GPIO.setup(pin, GPIO.OUT) for output pins [OK]
Common Mistakes:
  • Using GPIO.setup with GPIO.IN for output pin
  • Confusing GPIO.output with GPIO.setup
  • Using GPIO.input for output pin setup
3.

What will be the output behavior of this code snippet controlling an LED and button on Raspberry Pi?

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
LED_PIN = 18
BUTTON_PIN = 23
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

led_state = False

while True:
    button_state = GPIO.input(BUTTON_PIN)
    if button_state == False:
        led_state = not led_state
        GPIO.output(LED_PIN, led_state)
        time.sleep(0.3)

Choose the correct description of the LED behavior.

medium
A. LED blinks continuously without button press
B. LED toggles on and off each time the button is pressed
C. LED stays always off
D. LED stays always on

Solution

  1. Step 1: Understand button input reading

    The button is set with a pull-up resistor, so pressing it makes input False (pressed).
  2. Step 2: Toggle LED state on button press

    When button_state is False, led_state flips True/False and sets LED output accordingly, then waits 0.3 seconds to avoid bouncing.
  3. Final Answer:

    LED toggles on and off each time the button is pressed -> Option B
  4. Quick Check:

    Button press flips LED state = D [OK]
Hint: Button press flips LED state with delay to avoid bounce [OK]
Common Mistakes:
  • Ignoring pull-up resistor effect on button input
  • Missing delay causing multiple toggles
  • Assuming LED always on or off
4.

Identify the error in this Raspberry Pi LED toggle code snippet:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
LED_PIN = 21
BUTTON_PIN = 20
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN)

led_on = False

while True:
    if GPIO.input(BUTTON_PIN) == False:
        led_on = not led_on
        GPIO.output(LED_PIN, led_on)
    time.sleep(0.1)

What is the main problem?

medium
A. Missing pull-up or pull-down resistor setup for the button input
B. LED pin is not set as output
C. time.sleep() is too long
D. led_on variable is not initialized

Solution

  1. Step 1: Check button input setup

    The button pin is set as input but lacks pull-up or pull-down resistor configuration, which can cause unstable readings.
  2. Step 2: Understand effect of missing resistor

    Without pull-up/down, the input pin may float, causing random toggles of the LED.
  3. Final Answer:

    Missing pull-up or pull-down resistor setup for the button input -> Option A
  4. Quick Check:

    Button input needs pull-up/down resistor = A [OK]
Hint: Always set pull-up/down for button input pins [OK]
Common Mistakes:
  • Forgetting pull-up/down resistor causes unstable input
  • Assuming LED pin setup is wrong
  • Thinking sleep time is the issue
5.

You want to modify your Raspberry Pi LED toggle program so the LED only toggles when the button is pressed and released (not multiple toggles if held down). Which approach is best?

hard
A. Remove the pull-up resistor from the button pin
B. Increase the delay after toggling LED to 5 seconds
C. Use a while loop inside the main loop to wait until button is released
D. Add a variable to track previous button state and toggle LED only on state change from released to pressed

Solution

  1. Step 1: Understand button press and hold behavior

    Holding the button causes the input to stay low, triggering multiple toggles if not tracked.
  2. Step 2: Use previous state tracking

    By saving the last button state, the program can detect the transition from released to pressed and toggle LED only once per press.
  3. Final Answer:

    Add a variable to track previous button state and toggle LED only on state change from released to pressed -> Option D
  4. Quick Check:

    Track button state changes to toggle once = C [OK]
Hint: Track previous button state to toggle once per press [OK]
Common Mistakes:
  • Using long delays instead of state tracking
  • Removing pull-up resistor causing unstable input
  • Busy waiting inside loops causing CPU load
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard