Python and Hardware Control
Why Python Is the Default Superpower
Python is not the only good language on Raspberry Pi, but it is usually the fastest route from idea to working prototype.
It is strong for:
- automation scripts
- GPIO control
- small web apps and APIs
- camera and sensor integrations
- data logging and dashboards
Set Up a Clean Python Workflow
sudo apt install -y python3-pip python3-venv python3-dev
mkdir -p ~/projects/blink-demo
cd ~/projects/blink-demo
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
Recommended Library Categories
| Need | Good starting point |
|---|---|
| beginner-friendly GPIO | gpiozero |
| lower-level GPIO control | lgpio or gpiod-based tooling depending on stack |
| HTTP APIs | FastAPI or Flask |
| scheduling simple jobs | APScheduler or cron |
| camera and imaging | picamera2, OpenCV |
| MQTT and IoT messaging | paho-mqtt |
First Example: Blink an LED
Wire an LED to a GPIO pin with a resistor and use gpiozero.
pip install gpiozero
from gpiozero import LED
from time import sleep
led = LED(17)
while True:
led.on()
sleep(1)
led.off()
sleep(1)
Second Example: React to a Button
from gpiozero import Button, LED
from signal import pause
button = Button(27, pull_up=True)
led = LED(17)
button.when_pressed = led.on
button.when_released = led.off
pause()
Structure Your Project Early
garden-monitor/
├── app/
│ ├── main.py
│ ├── sensors.py
│ ├── storage.py
│ └── web.py
├── requirements.txt
├── .env
└── systemd/
└── garden-monitor.service
This is better than one giant script once the project becomes real.
Turning a Script Into a Service
Example systemd unit:
[Unit]
Description=Garden Monitor
After=network-online.target
[Service]
User=your-user
WorkingDirectory=/home/your-user/projects/garden-monitor
ExecStart=/home/your-user/projects/garden-monitor/.venv/bin/python -m app.main
Restart=always
[Install]
WantedBy=multi-user.target
Then enable it:
sudo cp systemd/garden-monitor.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now garden-monitor
Patterns That Work Well on Pi
| Pattern | Why it works |
|---|---|
| Poll sensor, write to local file or DB, expose small API | Simple and robust |
| Separate collection loop from web UI | Easier debugging |
| Use env vars or config file for pin numbers and thresholds | Hardware changes without code edits |
| Keep long-running loops restartable | Pi projects do eventually crash |
Example Automation Script
Turn on a fan relay when CPU temperature is high.
from gpiozero import OutputDevice
from time import sleep
from subprocess import check_output
fan = OutputDevice(18, active_high=True, initial_value=False)
def cpu_temp_c() -> float:
raw = check_output(['vcgencmd', 'measure_temp'], text=True)
return float(raw.split('=')[1].split("'")[0])
while True:
temp = cpu_temp_c()
fan.value = temp >= 60
sleep(10)
When to Use Another Language
| Language | Good reason to choose it |
|---|---|
| Go | Single binary services, low memory web backends, easy deployment |
| Rust | Performance-critical or reliability-critical services |
| Node.js | If your team already lives in JavaScript |
| C/C++ | Tight hardware integration or performance-sensitive code |
Python remains the best default until you have a strong reason otherwise.
Next Step
Move to 05-electronics-gpio-and-sensors.md to learn safe hardware patterns that keep your software projects from frying components.