Bird
Raised Fist0
Raspberry Piprogramming~20 mins

Button with interrupt (GPIO.add_event_detect) in Raspberry Pi - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
GPIO Interrupt Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output when the button is pressed?

Consider this Raspberry Pi Python code using GPIO interrupts. What will be printed when the button connected to GPIO pin 17 is pressed?

Raspberry Pi
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)


def button_pressed(channel):
    print("Button pressed!")

GPIO.add_event_detect(17, GPIO.FALLING, callback=button_pressed, bouncetime=200)

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    GPIO.cleanup()
AButton pressed! (printed once per press)
BNo output, program runs silently
CButton pressed! printed repeatedly without pressing
DSyntaxError due to missing colon
Attempts:
2 left
💡 Hint

Think about what GPIO.add_event_detect does when the button is pressed.

❓ Predict Output
intermediate
2:00remaining
What error occurs if callback function has wrong parameters?

What error will this code produce when the button is pressed?

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def button_pressed():
    print("Pressed")

GPIO.add_event_detect(17, GPIO.FALLING, callback=button_pressed)
ANo error, prints 'Pressed' on button press
BTypeError: button_pressed() takes 0 positional arguments but 1 was given
CSyntaxError: missing colon in function definition
DRuntimeError: GPIO pin not set up
Attempts:
2 left
💡 Hint

Callback functions for GPIO interrupts receive the channel number as an argument.

🔧 Debug
advanced
2:00remaining
Why does the callback run multiple times on one press?

This code prints "Pressed" multiple times for a single button press. What is the likely cause?

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def button_pressed(channel):
    print("Pressed")

GPIO.add_event_detect(17, GPIO.FALLING, callback=button_pressed)

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    GPIO.cleanup()
ASyntax error in add_event_detect call
BCallback function missing required argument
CNo debounce time set, causing multiple triggers due to button bounce
DGPIO pin not set as input
Attempts:
2 left
💡 Hint

Mechanical buttons can cause multiple signals quickly when pressed.

📝 Syntax
advanced
2:00remaining
Which option correctly adds a button interrupt with debounce?

Choose the correct code snippet that sets up a button interrupt on GPIO 17 with a 300ms debounce time.

AGPIO.add_event_detect(17, GPIO.FALLING, callback=button_pressed, bouncetime='300')
BGPIO.add_event_detect(17, GPIO.FALLING, callback=button_pressed bouncetime=300)
CGPIO.add_event_detect(17, GPIO.FALLING, callback=button_pressed, debounce=300)
DGPIO.add_event_detect(17, GPIO.FALLING, callback=button_pressed, bouncetime=300)
Attempts:
2 left
💡 Hint

Check the parameter name and syntax for debounce in add_event_detect.

🚀 Application
expert
2:00remaining
How to safely clean up GPIO after using interrupts?

You wrote a program using GPIO.add_event_detect for a button. What is the best way to ensure GPIO pins are cleaned up properly when the program ends?

AUse a try-except block catching KeyboardInterrupt and call <code>GPIO.cleanup()</code> in finally
BCall <code>GPIO.cleanup()</code> immediately after <code>add_event_detect</code>
CDo nothing; GPIO pins reset automatically on program exit
DCall <code>GPIO.cleanup()</code> inside the callback function
Attempts:
2 left
💡 Hint

Think about program termination and resource cleanup.

Practice

(1/5)
1.

What is the main purpose of using GPIO.add_event_detect with a button on a Raspberry Pi?

easy
A. To increase the voltage on the button pin
B. To set the button pin as an output
C. To disable the button input temporarily
D. To detect button presses instantly without constantly checking in a loop

Solution

  1. Step 1: Understand what GPIO.add_event_detect does

    This function listens for changes on a GPIO pin and triggers a callback or event without needing to check the pin repeatedly.
  2. Step 2: Compare options to the function's purpose

    Only To detect button presses instantly without constantly checking in a loop correctly describes the purpose: detecting button presses instantly without polling.
  3. Final Answer:

    To detect button presses instantly without constantly checking in a loop -> Option D
  4. Quick Check:

    Event detection = instant button press response [OK]
Hint: Think: event means reacting immediately, no waiting loop needed [OK]
Common Mistakes:
  • Confusing input and output pin setup
  • Thinking it disables the button
  • Assuming it changes voltage levels
2.

Which of the following is the correct syntax to add an event detect for a button press on GPIO pin 17 for a falling edge?

GPIO.add_event_detect(____, GPIO.FALLING, callback=my_callback)
easy
A. 17
B. '17'
C. GPIO.FALLING
D. my_callback

Solution

  1. Step 1: Identify the pin number argument

    The first argument to GPIO.add_event_detect is the pin number as an integer, here 17.
  2. Step 2: Check the options for correct type

    17 uses integer 17, which is correct. '17' uses a string which is invalid. Options C and D are incorrect because they are not pin numbers.
  3. Final Answer:

    17 -> Option A
  4. Quick Check:

    Pin number must be integer 17 [OK]
Hint: Pin numbers are integers, not strings or functions [OK]
Common Mistakes:
  • Using pin number as a string
  • Passing edge type or callback as pin number
  • Missing required arguments
3.

Consider this code snippet:

import RPi.GPIO as GPIO
import time

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

button_pressed = False

def button_callback(channel):
    global button_pressed
    button_pressed = True

GPIO.add_event_detect(18, GPIO.FALLING, callback=button_callback, bouncetime=200)

print("Waiting for button press...")

while not button_pressed:
    time.sleep(0.1)

print("Button was pressed!")
GPIO.cleanup()

What will be printed when the button connected to pin 18 is pressed?

medium
A. Waiting for button press...
B. Button was pressed!\nWaiting for button press...
C. Waiting for button press...\nButton was pressed!
D. No output

Solution

  1. Step 1: Understand program flow before button press

    The program prints "Waiting for button press..." and then waits in a loop until button_pressed becomes True.
  2. Step 2: Effect of button press and callback

    When the button is pressed, the callback sets button_pressed = True, breaking the loop and printing "Button was pressed!" before cleanup.
  3. Final Answer:

    Waiting for button press... Button was pressed! -> Option C
  4. Quick Check:

    Prints before and after button press [OK]
Hint: Callback sets flag; loop waits; prints before and after press [OK]
Common Mistakes:
  • Thinking callback prints directly
  • Ignoring the loop waiting for flag
  • Assuming no output before press
4.

What is wrong with this code snippet that tries to detect a button press on GPIO pin 22?

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(22, GPIO.IN)

def on_press(channel):
    print("Button pressed")

GPIO.add_event_detect(22, GPIO.RISING, callback=on_press)

while True:
    pass

GPIO.cleanup()
medium
A. Missing pull-up or pull-down resistor setup on pin 22
B. Callback function should return a value
C. GPIO.cleanup() is called before the loop ends
D. Using GPIO.RISING instead of GPIO.FALLING is invalid

Solution

  1. Step 1: Check pin setup for input

    The code sets pin 22 as input but does not specify pull-up or pull-down resistors, which can cause floating input and unreliable detection.
  2. Step 2: Review other options

    Callback functions do not need to return values. The cleanup call is unreachable but not an error. Both RISING and FALLING edges are valid depending on wiring.
  3. Final Answer:

    Missing pull-up or pull-down resistor setup on pin 22 -> Option A
  4. Quick Check:

    Input pins need pull resistors to avoid floating [OK]
Hint: Always set pull-up/down resistors for input pins [OK]
Common Mistakes:
  • Ignoring pull-up/down resistor setup
  • Expecting callback to return a value
  • Misunderstanding edge types
5.

You want to detect both button press and release events on GPIO pin 5 using interrupts. Which code snippet correctly sets up event detection for both edges and avoids multiple triggers due to button bounce?

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def button_event(channel):
    if GPIO.input(channel) == GPIO.LOW:
        print("Button pressed")
    else:
        print("Button released")

# Which line correctly adds event detection?
hard
A. GPIO.add_event_detect(5, GPIO.RISING, callback=button_event)
B. GPIO.add_event_detect(5, GPIO.BOTH, callback=button_event, bouncetime=300)
C. GPIO.add_event_detect(5, GPIO.FALLING, callback=button_event, bouncetime=50)
D. GPIO.add_event_detect(5, GPIO.BOTH, callback=button_event)

Solution

  1. Step 1: Identify edge detection for press and release

    To detect both press and release, use GPIO.BOTH to catch rising and falling edges.
  2. Step 2: Add debounce to avoid multiple triggers

    Button bounce causes multiple events; setting bouncetime=300 ms helps debounce effectively.
  3. Final Answer:

    GPIO.add_event_detect(5, GPIO.BOTH, callback=button_event, bouncetime=300) -> Option B
  4. Quick Check:

    Both edges + debounce = correct setup [OK]
Hint: Use BOTH edges with bouncetime to catch press and release cleanly [OK]
Common Mistakes:
  • Using only RISING or FALLING edge misses events
  • Forgetting debounce causes multiple prints
  • Not setting pull-up resistor on input pin
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