Pull-up and pull-down resistors help your Raspberry Pi read buttons or switches correctly by setting a clear default voltage.
0
0
Pull-up and pull-down resistors in Raspberry Pi
Introduction
When connecting a button to a Raspberry Pi GPIO pin to detect presses.
When you want to avoid random signals caused by floating inputs.
When you need to ensure a GPIO pin reads a known value when a switch is open.
When building simple circuits that interact with the Raspberry Pi's input pins.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(pin_number, GPIO.IN, pull_up_down=GPIO.PUD_UP) # For pull-up resistor GPIO.setup(pin_number, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # For pull-down resistor
Use GPIO.PUD_UP to activate the internal pull-up resistor.
Use GPIO.PUD_DOWN to activate the internal pull-down resistor.
Examples
This sets GPIO pin 17 as input with a pull-up resistor, so the pin reads HIGH when the button is not pressed.
Raspberry Pi
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)This sets GPIO pin 27 as input with a pull-down resistor, so the pin reads LOW when the button is not pressed.
Raspberry Pi
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)Sample Program
This program uses a pull-up resistor on pin 17. When the button is pressed, the pin reads LOW, and the program prints "Button pressed!". When not pressed, it prints "Button not pressed".
Raspberry Pi
import RPi.GPIO as GPIO import time BUTTON_PIN = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) print("Press the button...") try: while True: if GPIO.input(BUTTON_PIN) == GPIO.LOW: print("Button pressed!") else: print("Button not pressed") time.sleep(0.5) except KeyboardInterrupt: print("Exiting program") finally: GPIO.cleanup()
OutputSuccess
Important Notes
Pull-up means the pin is connected to HIGH voltage by default.
Pull-down means the pin is connected to LOW voltage by default.
Using these resistors prevents the pin from 'floating' and reading random values.
Summary
Pull-up and pull-down resistors set a default voltage level on input pins.
Use GPIO.PUD_UP or GPIO.PUD_DOWN in Raspberry Pi GPIO setup.
This helps your program read buttons and switches reliably.