Bird
0
0

Identify the error in this code that controls LED brightness and fix it:

medium📝 Debug Q14 of 15
Raspberry Pi - PWM Output
Identify the error in this code that controls LED brightness and fix it:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
pwm = GPIO.PWM(18, 1000)
pwm.ChangeDutyCycle(50)
pwm.start(50)
GPIO.cleanup()
AFrequency 1000 is too high, use 100
BChangeDutyCycle called before start; swap their order
CGPIO.cleanup() should be before pwm.start()
DMissing GPIO.setwarnings(False)
Step-by-Step Solution
Solution:
  1. Step 1: Check PWM start and ChangeDutyCycle order

    ChangeDutyCycle must be called after pwm.start(), not before.
  2. Step 2: Correct the order

    Swap lines so pwm.start(50) comes before pwm.ChangeDutyCycle(50).
  3. Final Answer:

    ChangeDutyCycle called before start; swap their order -> Option B
  4. Quick Check:

    start() must come before ChangeDutyCycle() [OK]
Quick Trick: Always start PWM before changing duty cycle [OK]
Common Mistakes:
  • Calling ChangeDutyCycle before start
  • Cleaning up GPIO too early
  • Incorrect frequency assumptions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes