Challenge - 5 Problems
PWM Mastery with RPi.GPIO
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PWM duty cycle print?
Consider this Python code using RPi.GPIO to create a software PWM on pin 18. What will be printed?
Raspberry Pi
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 100) # 100 Hz frequency pwm.start(0) # Start with 0% duty cycle for dc in range(0, 101, 50): pwm.ChangeDutyCycle(dc) print(f"Duty Cycle set to: {dc}%") time.sleep(0.1) pwm.stop() GPIO.cleanup()
Attempts:
2 left
💡 Hint
Look at the range function parameters and step size.
✗ Incorrect
The range(0, 101, 50) generates values 0, 50, and 100. So the loop prints three lines with those duty cycles.
❓ Predict Output
intermediate2:00remaining
What error does this PWM code raise?
What error will this code raise when run on a Raspberry Pi?
Raspberry Pi
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 0) # Frequency set to 0 pwm.start(50)
Attempts:
2 left
💡 Hint
Think about what frequency zero means for PWM.
✗ Incorrect
RPi.GPIO requires a positive frequency for PWM. Setting frequency to zero raises a ValueError.
🔧 Debug
advanced3:00remaining
Why does this PWM code not change brightness smoothly?
This code is intended to smoothly increase LED brightness using PWM. Why does the LED jump abruptly instead of smoothly changing brightness?
Raspberry Pi
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 1000) pwm.start(0) for dc in range(0, 101, 20): pwm.ChangeDutyCycle(dc) time.sleep(0.5) pwm.stop() GPIO.cleanup()
Attempts:
2 left
💡 Hint
Think about how many steps the brightness changes in.
✗ Incorrect
The duty cycle changes in big jumps (0, 20, 40, 60, 80, 100), causing abrupt brightness changes instead of smooth.
📝 Syntax
advanced2:00remaining
Which option fixes the syntax error in this PWM code?
This code snippet has a syntax error. Which option fixes it correctly?
Raspberry Pi
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 100) pwm.start(50 pwm.ChangeDutyCycle(75) pwm.stop() GPIO.cleanup()
Attempts:
2 left
💡 Hint
Look carefully at the parentheses in the pwm.start line.
✗ Incorrect
The line pwm.start(50 is missing a closing parenthesis. Adding it fixes the syntax error.
🚀 Application
expert2:00remaining
How many PWM cycles occur in 2 seconds at 500 Hz?
You set up software PWM on a Raspberry Pi with frequency 500 Hz. How many complete PWM cycles will occur in 2 seconds?
Attempts:
2 left
💡 Hint
Multiply frequency by time in seconds.
✗ Incorrect
At 500 Hz, 500 cycles happen each second. In 2 seconds, 500 * 2 = 1000 cycles occur.