Consider this Python code running on a Raspberry Pi to control LED brightness using PWM. What will be printed?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 1000) # 1kHz frequency pwm.start(0) for duty_cycle in range(0, 101, 25): pwm.ChangeDutyCycle(duty_cycle) print(f"LED brightness set to {duty_cycle}%") time.sleep(0.1) pwm.stop() GPIO.cleanup()
Look at the range(0, 101, 25) which controls the duty cycle steps.
The range(0, 101, 25) generates values 0, 25, 50, 75, 100. Each value is printed as the LED brightness percentage.
In PWM (Pulse Width Modulation) for LED brightness control on Raspberry Pi, what does changing the duty cycle do?
Think about how PWM controls power by switching ON and OFF rapidly.
Duty cycle is the percentage of time the signal is ON during each PWM cycle, controlling perceived brightness.
Look at this code snippet for Raspberry Pi LED brightness control. It raises an error. What is the cause?
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 500) pwm.start(50) for i in range(0, 110, 10): pwm.ChangeDutyCycle(i) print(f"Brightness: {i}%") pwm.stop() GPIO.cleanup()
Check the range of duty cycle values in the loop.
The loop goes up to 110%, but duty cycle must be between 0 and 100. Values above 100 cause an error.
Which code snippet correctly changes the PWM duty cycle on Raspberry Pi?
Method names in RPi.GPIO are case sensitive.
The correct method name is ChangeDutyCycle with capital C, capital D, and capital C.
If you use an 8-bit PWM controller for LED brightness on Raspberry Pi, how many distinct brightness levels can you set?
8-bit means how many bits are used to represent the duty cycle value?
8 bits can represent 2^8 = 256 different values, so 256 brightness levels.