Mastering Raspberry Pi Sensor & Actuator Control: Accelerometer, Servo, and Data Streaming
While most developers work with static files or simple graphics, physical computing opens the door to real‑world interaction. By reading data from sensors and driving actuators, you can create systems that sense, decide, and act in the physical world.
Goal
Use a Raspberry Pi to read accelerometer values and to command a servo motor, demonstrating key concepts of physical computing.
Key Concepts
- Raspberry Pi – A $35 Linux computer with HDMI, Ethernet, two USB ports, and most importantly, GPIO pins that let you send and receive signals.
- GPIO Pins – General Purpose Input/Output pins that act as binary switches. You can set a pin HIGH (3.3 V) or LOW (0 V) to drive an actuator, or read its state to gather sensor data.
This article walks through four practical Python projects that illustrate the Pi’s hardware capabilities:
- Blink an LED.
- Read a potentiometer.
- Stream data over a network.
- Control a servo motor.
Blink an LED
An LED (Light‑Emitting Diode) emits light when current flows in one direction. To protect the Pi and the LED, use a resistor between 500 Ω and 1.5 kΩ. The resistor value can be calculated with R = (V_s - V_d) / I but the range above works for most hobby kits.
import time
from itertools import cycle
import RPi.GPIO as io
io.setmode(io.BCM)
io.setup(12, io.OUT)
for state in cycle([1, 0]):
io.output(12, state)
time.sleep(0.5)
The code sets pin 12 as an output and toggles it every half second, making the LED blink.
Read a Potentiometer
A potentiometer (pot) is a variable resistor that converts a knob position into a voltage. Since GPIO pins are digital, we need an Analog‑to‑Digital Converter (ADC). The MCP3008 offers eight 10‑bit channels, mapping 0–3.3 V to integer values 0–1023.
Install spidev to communicate with the MCP3008 via SPI:
pip install spidev
Run the following script to read values from channel 0:
import spidev
import time
spi = spidev.SpiDev()
spi.open(0, 0)
def readadc(adcnum):
if not 0 <= adcnum <= 7:
return -1
r = spi.xfer2([1, (8 + adcnum) << 4, 0])
adcout = ((r[1] & 3) << 8) + r[2]
return adcout
while True:
val = readadc(0)
print(val)
time.sleep(0.5)
Stream Data with ØMQ
ØMQ simplifies networking by providing a high‑performance messaging library. Using the REQUEST/REPLY pattern, you can build a lightweight server and client in Python.
Server
import zmq
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind('tcp://*:1980')
while True:
message = socket.recv()
print(message)
socket.send(b"I'm here")
Client
import zmq
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect('tcp://192.168.1.6:1980')
for _ in range(10):
socket.send(b'You home?')
message = socket.recv()
print(message)
With traits and enaml, you can create a responsive UI that visualizes the streamed data. See the acc_plot demo for a full example.
Control a Servo Motor
Servos move to precise positions using Pulse Width Modulation (PWM). A typical hobby servo interprets a 0.5 ms pulse as its minimum angle and a 2.5 ms pulse as its maximum, repeating every 20 ms.
Precise timing is hard to achieve in a general‑purpose OS. ServoBlaster is a kernel module that offloads PWM generation to the DMA controller, exposing a simple /dev/servoblaster interface.
I’ve wrapped this functionality in a small, object‑oriented library: RobotBrain. The example below demonstrates moving a servo from 0 % to 100 % duty cycle.
import time
import numpy as np
from robot_brain.servo import Servo
# Initialize servo on pin 4 with custom min/max pulse widths (in µs)
servo = Servo(0, min=60, max=200)
for val in np.arange(0, 1, 0.05):
servo.set(val)
time.sleep(0.1)
Use the servo_slider demo on GitHub to see how the servo can be controlled over the network.
For a deeper dive into sensor and actuator control with the Raspberry Pi, refer to the original documentation or community tutorials.
Manufacturing process
- Build a Remote Temperature Sensor with Raspberry Pi and Python – Step‑by‑Step Guide
- Control an LED with a PIR Motion Sensor on Raspberry Pi
- Build a Low‑Cost Raspberry Pi Soil Moisture Sensor for Smart Irrigation
- Build a Multi‑Sensor Temperature & Light Monitoring System with Raspberry Pi & DS18B20
- Raspberry Pi–Based Bathroom Occupancy Sensor with Voice & SMS Alerts via Twilio
- Build an Automated Aeroponics System with Raspberry Pi and Humidity Sensor
- Build a Raspberry Pi Home Temperature Monitor with MCP9808, InfluxDB & Grafana
- Control Your Raspberry Pi with a Repurposed IR Remote: Shutdown & Reboot via LIRC
- Smart Indoor Air Quality & Waste Monitoring System
- Build a Raspberry Pi 3 & Arduino Laptop: Step‑by‑Step Guide