Source: L4 — External GPIO Devices Using the Grove Base Hat
Overview
Lab 4 uses the Grove Base Hat to read a joystick (analog X/Y + digital button) and control the mouse via ydotool.
Prerequisites
- ydotool installed and
ydotoolddaemon running — see ydotool source - I2C interface enabled — see enable-i2c source
- Grove Base Hat ribbon cable connected correctly (red line aligned with green button / PWM port)
Verify I2C after enabling
i2cdetect -y 1
# Should show UU at addresses 0x1a, 0x2a, 0x39, 0x46 (or similar)Hardware: Joystick Wiring
Joystick has 5 pins:
| Pin | Meaning | Connect to |
|---|---|---|
| GND | Ground (0V) | GND on Grove Hat |
| Vcc / +5V | Power (3.3V from Grove Hat) | Vcc on Grove Hat |
| VRx / Xout | Analog X-position voltage | Analog port A0 |
| VRy / Yout | Analog Y-position voltage | Analog port A1 |
| SW / Sel | Digital button press (on/off) | Digital port D22 (or any digital port) |
The Grove Base Hat analog ports use channels:
- A0 → channel 0
- A1 → channel 1
- A2 → channel 2, A3 → channel 3 (up to A7 → channel 7)
Code Pattern
from grove.adc import ADC
from gpiozero import Button
import subprocess
adc = ADC()
joystick_btn = Button(22) # BCM pin for digital port D22
joystick_btn.when_pressed = lambda: subprocess.run(['ydotool', 'click', '0xC0'])
if __name__ == "__main__":
from signal import pause
while True:
x_mv = adc.read_voltage(0) # A0 → VRx
y_mv = adc.read_voltage(1) # A1 → VRy
# Center is ~1650mV (half of 3300mV supply)
# Map to mouse delta: positive = right/down, negative = left/up
dx = (x_mv - 1650) // 100
dy = (y_mv - 1650) // 100
if abs(dx) > 2 or abs(dy) > 2: # deadzone
subprocess.run(['ydotool', 'mousemove', '-x', str(dx), '-y', str(dy)])Signal Types
- Joystick X/Y axes = analog signal (infinitely many positions) → read with
grove.adc - Joystick button press = digital signal (on/off) → read with
gpiozero.Button - Grove Base Hat converts analog → 12-bit digital → Pi reads over I2C
install requirements
# In lab-4 venv
pip install -r requirements.txt # includes grove.py, gpiozero, lgpioTroubleshooting: EDGE DETECTION error
sudo apt install swig liblgpio-dev build-essential
sudo apt install python3-lgpioAdd lgpio to requirements.txt and re-run pip install -r requirements.txt.
See Also
- GPIO and reTerminal topic
- grove-adc source
- ydotool source
- enable-i2c source
- gpiozero-recipes source
- ADC concept, I2C concept