Code Club - Quiz Controlled LEDs
Quiz Controlled LEDs with Raspberry Pi
Here's a challenge design for someone learning Python with a Raspberry Pi that incorporates asking questions and controlling LEDs.
Objective:
Create a Python-based LED game where players answer questions. Correct answers turn on a green LED, while wrong answers flash a red LED multiple times.

Requirements:
Hardware:
- Raspberry Pi (with GPIO capabilities)
- 1 green LED for correct answers
- 1 red LED for incorrect answers
- 2 330Ω resistors
- Breadboard and jumper wires
Python Concepts:
if
/else
statements- Loops
- Functions
- Basic GPIO control
Challenge Overview:
Game Rules:
- The game asks 5 multiple-choice questions.
- Players respond by entering the correct letter (e.g., A, B, C). If the answer is correct: The green LED lights up for 1 second. The player gets a congratulatory message. If the answer is incorrect: The red LED flashes 3 times. A message tells the player the correct answer. The game ends with a score summary.
Steps:
1. Setup the LEDs:
- Connect the LEDs to two GPIO pins (e.g., GPIO17 and GPIO18).
- Use resistors to protect the LEDs.
- Connect the cathode (short leg) of each LED to the ground (negative -).
Raspberry 3b Pinout
Raspberry Pi 4 Pinout
Raspberry Pi 5 Pinout
2. Write the Code:
Create a Python program that:
- Asks the user a question (e.g., "Is Python a programming language? (yes/no)").
- If the user answers correctly, turn on one LED for a short time.
- If the user answers incorrectly, turn on a different LED or flash it to indicate an error.
LED Wiring Test Application
This program will sequentially blink the red LED, green LED to visually confirm that the wiring and components are working correctly.
- Create a new file wiring_test.py
- Copy the code and paste into the new file
1from gpiozero import LED
2import time
3
4# Define LEDs
5LED_RED = LED(17) # Red LED pin
6LED_GREEN = LED(18) # Green LED pin
7
8# Functions
9def blink_led(led, interval, blink_times:1):
10 """
11 Blink a given LED
12 :param led: The LED object to blink
13 :param interval: sleep in seconds
14 :blink_times: how many times the led will blink
15 """
16 for _ in range(blink_times):
17 led.on()
18 time.sleep(interval)
19 led.off()
20 time.sleep(interval)
21
22# Test Wiring
23def test_wiring():
24 """
25 Sequentially test each LED and then both together.
26 """
27 print("Starting wiring test...")
28
29 # Test Red LED
30 print("Testing Red LED...")
31 blink_led(LED_RED,0.5,5)
32 print("Red LED test complete.")
33
34 # Test Green LED
35 print("Testing Green LED...")
36 blink_led(LED_GREEN,0.5,5)
37 print("Green LED test complete.")
38
39 print("Wiring test complete! If all LEDs blinked as expected, your wiring is correct.")
40
41# Main Program
42if __name__ == "__main__":
43 try:
44 test_wiring()
45 except KeyboardInterrupt:
46 print("\nTest interrupted.")
- Run wiring_test.py and you should see this output:
1$ python wiring_test.py
2
3Starting wiring test...
4Testing Red LED...
5Red LED test complete.
6Testing Green LED...
7Green LED test complete.
8Testing Both LEDs Together...
9Both LEDs test complete.
10Wiring test complete! If all LEDs blinked as expected, your wiring is correct.
11Cleaning up GPIO...
Example Code (Starter Template)
1from gpiozero import LED
2import time
3
4LED_GREEN = LED(18) # Green LED pin
5LED_RED = LED(17) # Red LED pin
6
7# Functions
8def indicate_correct():
9 """
10 Turn on the green LED for 1 second.
11 """
12 LED_GREEN.on()
13 time.sleep(1)
14 LED_GREEN.off()
15
16def indicate_wrong():
17 """
18 Flash the red LED 3 times with 0.5-second intervals.
19 """
20 # TODO: Write the code to flash the red LED 3 times
21 # Hint: Use a loop
22
23def get_valid_input():
24 """
25 Repeatedly ask the user for input until a valid answer (A, B, or C) is provided.
26 """
27 valid_answers = ['A', 'B', 'C']
28 while True:
29 user_input = input("Your answer (A/B/C): ").strip().upper()
30 if user_input in valid_answers:
31 return user_input
32 else:
33 print("Invalid input! Please choose A, B, or C.")
34
35# Questions and answers
36questions = [
37 # Format: [question, option1, option2, option3, correct_answer]
38 ["What is 5 + 3?", "6", "8", "10", "B"],
39 ["What is the capital of France?", "Rome", "Paris", "Berlin", "B"],
40 ["What is the color of the sky?", "Blue", "Green", "Yellow", "A"],
41 ["Which planet is known as the Red Planet?", "Earth", "Mars", "Venus", "B"],
42 ["What is the square root of 16?", "2", "4", "8", "B"]
43]
44
45# Main Quiz Logic
46score = 0
47for q in questions:
48
49 # Unpack question and options
50 question, option1, option2, option3, correct_answer = q
51 # Display the question and options
52 print(f"{question}")
53 print(f"A. {option1}")
54 print(f"B. {option2}")
55 print(f"C. {option3}")
56 answer = get_valid_input() # Get valid input
57
58 # TODO: Add the logic to check if the answer is correct
59 # Compare the user's input with the correct answer
60 if ...: # Complete this condition
61 print("Correct!")
62 indicate_correct()
63 score += 1
64 else:
65 print(f"Wrong! The correct answer was {correct_answer}.")
66 indicate_wrong()
67
68# Final score
69print(f"Game over! You scored {score} out of {len(questions)}.")
Tasks:
- Complete the
wrong_answer()
Function:- Write a loop to flash the red LED 3 times.
- Write the Quiz Logic:
- Fill in the condition to check if the player's answer matches the correct one.
- Expect lower or capital letter as input. Treat it accordingly.
- Lose Points: Take 1 point if the given answer is not correct.
- Enhance the Game (Optional):
- More questions: Add 3 additional questions
- Quit: Exit the quiz if the Q letter is entered.
- Timer: Add a countdown timer for each question to make it more challenging.
- More questions: Add more questions
Hints to Guide Learners
- Use
time.sleep(seconds)
to add delays. - Recall the syntax for loops (
for
orwhile
) and conditionals (if/else
). - upper() and lower() are basic functions to handle string conversion.