0
0
Raspberry Piprogramming~5 mins

Digital input (GPIO.input) in Raspberry Pi

Choose your learning style9 modes available
Introduction

We use digital input to read if a switch or sensor is ON or OFF. It helps the Raspberry Pi know what is happening in the real world.

To check if a button is pressed or not.
To detect if a door is open or closed using a sensor.
To read signals from simple sensors like motion detectors.
To monitor if a device is powered ON or OFF.
To control a program based on physical switches.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(pin_number, GPIO.IN)

input_state = GPIO.input(pin_number)

Use GPIO.setmode(GPIO.BCM) to select pin numbering by Broadcom chip.

GPIO.setup(pin_number, GPIO.IN) sets the pin as input to read signals.

Examples
Set pin 17 as input and read its state.
Raspberry Pi
GPIO.setup(17, GPIO.IN)
state = GPIO.input(17)
Check if pin 4 is HIGH (ON) or LOW (OFF) and print a message.
Raspberry Pi
if GPIO.input(4):
    print("Pin 4 is HIGH")
else:
    print("Pin 4 is LOW")
Read a button connected to pin 22 and print if pressed.
Raspberry Pi
button_pin = 22
GPIO.setup(button_pin, GPIO.IN)
if GPIO.input(button_pin) == GPIO.HIGH:
    print("Button pressed")
Sample Program

This program reads a button on pin 18 every second. It prints if the button is pressed or not. Press Ctrl+C to stop.

Raspberry Pi
import RPi.GPIO as GPIO
import time

button_pin = 18

GPIO.setmode(GPIO.BCM)
GPIO.setup(button_pin, GPIO.IN)

print("Press the button connected to pin 18")

try:
    while True:
        if GPIO.input(button_pin):
            print("Button is pressed")
        else:
            print("Button is not pressed")
        time.sleep(1)
except KeyboardInterrupt:
    print("Program stopped")
    GPIO.cleanup()
OutputSuccess
Important Notes

Always call GPIO.cleanup() at the end to reset pins safely.

Use pull-up or pull-down resistors to avoid false readings on input pins.

Pin numbering can be BCM or BOARD; be consistent in your code.

Summary

Digital input reads ON/OFF signals from pins.

Use GPIO.setup(pin, GPIO.IN) to prepare a pin for input.

Use GPIO.input(pin) to get the current state (True/False).