Python Programming with Raspberry Pi: Interfacing External Gadgets
1. Setting Up GPIO in Python
Use the built-in [Link] library.
import [Link] as GPIO
import time
[Link]([Link])
[Link](False)
2. Output Devices (Control)
2.1 Blinking an LED
Wiring:
- Connect a resistor (220Ohm) and LED to GPIO 18. Cathode to GND.
Code:
[Link](18, [Link])
while True:
[Link](18, [Link])
[Link](1)
[Link](18, [Link])
[Link](1)
2.2 Buzzer
Wiring: Positive pin to GPIO 23, negative to GND.
Python Programming with Raspberry Pi: Interfacing External Gadgets
[Link](23, [Link])
[Link](23, [Link])
[Link](0.5)
[Link](23, [Link])
3. Input Devices (Read)
3.1 Push Button
Wiring: One end to GPIO 17, other to GND
[Link](17, [Link], pull_up_down=GPIO.PUD_UP)
while True:
if [Link](17) == [Link]:
print("Button Pressed")
[Link](0.2)
3.2 PIR Motion Sensor
Wiring: VCC to 5V, GND to GND, OUT to GPIO 24
[Link](24, [Link])
while True:
if [Link](24):
print("Motion Detected")
else:
print("No Motion")
[Link](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 = [Link]()
[Link](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)
[Link](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:
[Link](pin, [Link])
while True:
[Link](18, [Link])
[Link](2)
[Link](18, [Link])
[Link](23, [Link])
[Link](1)
[Link](23, [Link])
[Link](24, [Link])
[Link](2)
[Link](24, [Link])
6. Cleanup Code
Always end your script with:
[Link]()