Source: L3 — Programming the ReTerminal
Overview
Lab 3 covers three progressively layered tasks:
- Bash script to control the reTerminal backlight
- Python script using
subprocessto call the bash script - Python with
seeed-python-rpito sequence the built-in LEDs
Part 1: Bash Backlight Script
Script: lab-3/bash/backlight (no extension, executable)
#!/bin/bash
# Validate: exactly 1 argument
if [[ $#--ne-1-| -ne 1 ]]; then
echo "Usage: $0 <0-255>" >&2
exit 1
fi
val=$1
# Validate: is it an integer
if ! [[ "$val" =~ ^[0-9]+$ ]]; then
echo "Error: must be integer" >&2
exit 1
fi
# Validate: in range
if [[ $val -lt 0 || $val -gt 255 ]]; then
echo "Error: must be 0-255" >&2
exit 1
fi
# Write to device file using sudo+tee (required for root-owned /sys/ files)
echo "$val" | sudo tee /sys/class/leds/<backlight-device>/brightness > /dev/nullMake executable: chmod +x lab-3/bash/backlight
Run: ./lab-3/bash/backlight 255
Part 2: Python Wrapping Bash (subprocess)
Script: lab-3/python/backlight.py
#!/usr/bin/env python3
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument("mode", type=str, choices=["ON", "OFF", "DIM"])
args = parser.parse_args()
mapping = {"ON": "255", "OFF": "0", "DIM": "1"}
value = mapping[args.mode]
# Call bash script using relative path from this file's directory
subprocess.run(["../bash/backlight", value])Make executable: chmod +x backlight.py
Key points:
- Use relative path (
../bash/backlight) to the bash script - Re-use the working bash script; do NOT rewrite its logic
- argparse converts string
ON/OFF/DIMto numeric255/0/1
Part 3: seeed-python-rpi LED Sequence
Script: lab-3/python/leds.py
Setup:
# Create and activate venv
python -m venv .venv
source .venv/bin/activate
pip install git+https://github.com/Seeed-Studio/Seeed_Python_RPi/
pip install RPi-GPIOimport seeed_python_rpi.core as rt
import time
while True:
rt.sta_led = True # STA: Red on (default color is red)
time.sleep(1)
rt.sta_led = False
rt.sta_led_green = True # STA: Green
time.sleep(1)
rt.sta_led_green = False
rt.usr_led = True # USR: Green
time.sleep(1)
rt.usr_led = Falsesudo + venv problem
The seeed library needs root to access LED files. But sudo python uses root’s Python, not the venv.
# CORRECT: use venv's Python with sudo
sudo $(which python) leds.py # command substitution
sudo ./.venv/bin/python leds.py # direct path to venv pythonDo NOT commit .venv folder (add to .gitignore).
subprocess Module Reference
import subprocess
# Basic usage
subprocess.run(['command', 'arg1', 'arg2'])
# Capture output
result = subprocess.run(['ls', '-la'], capture_output=True, text=True)
print(result.stdout)
print(result.returncode)
# Raise on error
subprocess.check_call(['./script.sh'])
# Shell string (less safe, avoid if possible)
subprocess.run('echo hello', shell=True)See Also
- Python Essentials topic (argparse, subprocess, venv)
- GPIO and reTerminal topic (seeed-python-rpi)
- Bash Scripting topic (shebang, positional args, conditionals)