How to Set GPIO Pin as Input on Raspberry Pi
To set a GPIO pin as input on Raspberry Pi, use the
RPi.GPIO library in Python and call GPIO.setup(pin_number, GPIO.IN). This configures the specified pin to read signals instead of sending them.Syntax
Use the GPIO.setup() function to configure a GPIO pin. It takes two main arguments:
pin_number: The number of the GPIO pin you want to use.GPIO.IN: This sets the pin as an input.
You can also add an optional pull_up_down parameter to set internal resistors.
python
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) # Use BCM pin numbering GPIO.setup(17, GPIO.IN) # Set GPIO pin 17 as input
Example
This example shows how to set GPIO pin 17 as input and read its value. It prints HIGH if the pin is receiving voltage, or LOW if not.
python
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) # Use BCM pin numbering GPIO.setup(17, GPIO.IN) # Set GPIO pin 17 as input try: while True: if GPIO.input(17): print("Pin 17 is HIGH") else: print("Pin 17 is LOW") time.sleep(1) except KeyboardInterrupt: GPIO.cleanup() # Clean up GPIO on CTRL+C exit
Output
Pin 17 is LOW
Pin 17 is LOW
Pin 17 is HIGH
Pin 17 is LOW
...
Common Pitfalls
- Forgetting to set the pin numbering mode with
GPIO.setmode()causes errors. - Not calling
GPIO.cleanup()can leave pins in an undefined state. - Ignoring pull-up or pull-down resistors can cause unstable input readings.
Always specify pull resistors if your circuit needs them.
python
import RPi.GPIO as GPIO # Wrong: Missing setmode # GPIO.setup(17, GPIO.IN) # This will raise an error # Right: GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Use pull-up resistor
Quick Reference
| Function | Description |
|---|---|
| GPIO.setmode(GPIO.BCM) | Set pin numbering to BCM mode |
| GPIO.setup(pin, GPIO.IN) | Set a pin as input |
| GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) | Set input pin with pull-up resistor |
| GPIO.input(pin) | Read the current value of the input pin |
| GPIO.cleanup() | Reset all GPIO pins to default state |
Key Takeaways
Always call GPIO.setmode() before setting up pins to avoid errors.
Use GPIO.setup(pin, GPIO.IN) to configure a pin as input.
Consider using pull-up or pull-down resistors to stabilize input readings.
Call GPIO.cleanup() to reset pins when your program ends.
Use GPIO.input(pin) to read the current state of an input pin.