Consider this Python code to blink an LED connected to GPIO pin 17 on a Raspberry Pi. What will it print to the console?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) for i in range(3): GPIO.output(17, GPIO.HIGH) print("LED ON") time.sleep(0.5) GPIO.output(17, GPIO.LOW) print("LED OFF") time.sleep(0.5) GPIO.cleanup()
Each loop turns the LED ON then OFF once, printing messages accordingly.
The loop runs 3 times. Each time it prints "LED ON" then "LED OFF". So the output repeats these two lines 3 times.
In the code below, what does GPIO.setmode(GPIO.BCM) mean?
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM)
There are two common ways to number pins: BCM and BOARD.
GPIO.BCM means the program uses the Broadcom chip's GPIO numbering, not the physical pin numbers.
Look at this code snippet. What error will it raise when run on a Raspberry Pi?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.output(17, GPIO.HIGH) print("LED ON") time.sleep(1) GPIO.cleanup() GPIO.output(17, GPIO.LOW) print("LED OFF")
Consider what GPIO.cleanup() does before the last output call.
After calling GPIO.cleanup(), all GPIO channels are reset. Trying to use GPIO.output(17, GPIO.LOW) after cleanup causes a RuntimeError.
This code has a syntax error. Which option fixes it correctly?
for i in range(3)
GPIO.output(17, GPIO.HIGH)
time.sleep(0.5)for i in range(3) GPIO.output(17, GPIO.HIGH) time.sleep(0.5)
Python for loops require a colon at the end of the header line.
The syntax error is missing colon after for i in range(3). Adding the colon fixes it.
Given this Raspberry Pi GPIO code, how many times will the LED turn ON and OFF?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) count = 0 while count < 5: GPIO.output(17, GPIO.HIGH) time.sleep(0.2) GPIO.output(17, GPIO.LOW) time.sleep(0.2) count += 1 GPIO.cleanup()
Count how many times the loop runs and what happens each time.
The loop runs 5 times. Each time the LED turns ON once and OFF once, so 5 blinks total.