Python Programming with Raspberry Pi: Interfacing External Gadgets
1. Setting Up GPIO in Python
Use the built-in RPi.GPIO library.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
2. Output Devices (Control)
2.1 Blinking an LED
Wiring:
- Connect a resistor (220Ohm) and LED to GPIO 18. Cathode to GND.
Code:
GPIO.setup(18, GPIO.OUT)
while True:
GPIO.output(18, GPIO.HIGH)
time.sleep(1)
GPIO.output(18, GPIO.LOW)
time.sleep(1)
2.2 Buzzer
Wiring: Positive pin to GPIO 23, negative to GND.
Python Programming with Raspberry Pi: Interfacing External Gadgets
GPIO.setup(23, GPIO.OUT)
GPIO.output(23, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(23, GPIO.LOW)
3. Input Devices (Read)
3.1 Push Button
Wiring: One end to GPIO 17, other to GND
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
if GPIO.input(17) == GPIO.LOW:
print("Button Pressed")
time.sleep(0.2)
3.2 PIR Motion Sensor
Wiring: VCC to 5V, GND to GND, OUT to GPIO 24
GPIO.setup(24, GPIO.IN)
while True:
if GPIO.input(24):
print("Motion Detected")
else:
print("No Motion")
time.sleep(1)
Python Programming with Raspberry Pi: Interfacing External Gadgets
4. Reading Analog Sensors (MCP3008)
Use MCP3008 to read analog sensors.
Libraries:
sudo pip3 install spidev
Code:
import spidev
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 1350000
def read_adc(channel):
adc = spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1]&3) << 8) + adc[2]
return data
while True:
value = read_adc(0)
print("Analog Value:", value)
time.sleep(1)
5. Controlling Multiple Outputs
Example: Traffic Lights
Python Programming with Raspberry Pi: Interfacing External Gadgets
led_pins = [18, 23, 24]
for pin in led_pins:
GPIO.setup(pin, GPIO.OUT)
while True:
GPIO.output(18, GPIO.HIGH)
time.sleep(2)
GPIO.output(18, GPIO.LOW)
GPIO.output(23, GPIO.HIGH)
time.sleep(1)
GPIO.output(23, GPIO.LOW)
GPIO.output(24, GPIO.HIGH)
time.sleep(2)
GPIO.output(24, GPIO.LOW)
6. Cleanup Code
Always end your script with:
GPIO.cleanup()