Consider this Python code using the RPi.GPIO library to set a pin mode and read its state:
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN) state = GPIO.input(18) print(state)
What will this code print if the pin 18 is connected to ground?
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN) state = GPIO.input(18) print(state)
Remember, when a pin is set as input and connected to ground, its state reads as low.
The pin 18 is set as input. When connected to ground, the input reads low, which is 0.
Given this code snippet:
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.OUT) GPIO.output(23, GPIO.HIGH) print(GPIO.input(23))
What will be printed?
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.OUT) GPIO.output(23, GPIO.HIGH) print(GPIO.input(23))
Output pins reflect the value you set on them.
Pin 23 is set as output and set to HIGH, so reading it returns 1.
Look at this code snippet:
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.output(17, 1) GPIO.setup(17, GPIO.IN) print(GPIO.input(17))
What error will this code cause when run?
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.output(17, 1) GPIO.setup(17, GPIO.IN) print(GPIO.input(17))
Think about setting up the same pin twice without cleanup.
Setting up the same pin twice without cleanup causes a RuntimeWarning about channel already in use.
Choose the correct statement about setting GPIO pin modes on Raspberry Pi:
Think about the difference between input and output pins.
Input pins read voltage levels but do not drive voltage. Output pins drive voltage but reading them depends on the hardware.
Consider this code that toggles a pin state:
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(27, GPIO.OUT) GPIO.output(27, GPIO.LOW) time.sleep(0.1) GPIO.output(27, not GPIO.input(27)) print(GPIO.input(27))
What will be printed?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(27, GPIO.OUT) GPIO.output(27, GPIO.LOW) time.sleep(0.1) GPIO.output(27, not GPIO.input(27)) print(GPIO.input(27))
Think about toggling the pin state from LOW to HIGH.
The pin starts LOW (0). The code sets it to the opposite of current state, which is HIGH (1). Then it prints 1.