The course
Python on the Pi's pins is a beginner Coding course in seven lessons, for anyone who has finished Python from zero. Each lesson takes one part from "it works" to "I know what the pin is doing", on a gallery Pi circuit, with gpiozero as Raspberry Pi OS ships it. Steps are checked against what the Pi prints and what its pins and parts do: an LED's pin, a servo's angle, a sensor's reading.
- LEDs and PWM: a pin high and low, a launch countdown,
blink()in the background,PWMLEDbrightness, the duty cycle in milliseconds (2.5 ms of every 10 at 25 percent and 100 Hz), andpulse(). - Buttons and events: polling
is_pressed, counting presses by their edges,when_pressedhandlers, contact bounce andbounce_time, a long hold withwhen_held, and a reaction timer. - Buzzers and tunes:
Buzzeron and off,beep(), Morse code from a dict, notes worked out from A4 = 440 Hz, and a rising tune on aTonalBuzzer. - Servos:
Servoand why its default 1 to 2 ms pulses miss this servo's range,AngularServowith the right pulse widths, angles typed in the Serial Monitor, and a sweep that ends withdetach(). - Distance sensor: an HC-SR04 on a Raspberry Pi 5 with its echo divided down to 3.3 V, a moving target, a warning LED inside 20 cm, a parking-sensor bar graph, and echo times from the speed of sound, in air and in seawater.
- Motion sensor: a PIR's
wait_for_motion,when_motionevents, a timed log of visits, the module's own hold and blind time, and a cooldown that turns repeats into one alert. - Project: a desk alarm: the finale.
The project
The desk alarm guards a drawer. It is a state machine: DISARMED, ARMED,
TRIGGERED and ALARM. Typing arm lights amber; the drawer switch (the
button) starts a five second entry delay; when it runs out the red light
flashes as a siren; and a secret knock, three more presses of the same
switch, stands it down to green. A timed log records every step. The last
step adds features of your own, starting with the state diagram.
What the Pi engine does differently
- gpiozero's software PWM sets the duty in whole percent. A servo pulse
therefore lands on 200 microsecond steps, so 90 degrees comes out near 83,
and gpiozero prints its
PWMSoftwareFallbackwarning, as it does on a real Pi without pigpio. - The pushbutton bounces like a real one, so event handlers need
bounce_time. - The PIR holds its output for 2 seconds after motion stops and then ignores motion for about 2.5 seconds more, like an HC-SR501.
- While a program waits at
input(), nothing else runs, button and sensor events included. The desk alarm reads the keyboard only to arm, and watches in asleeploop after that.
The gallery has no Pi circuit with a buzzer yet, so the buzzer lesson drives
the blink circuit's LED with Buzzer and TonalBuzzer: a buzzer module on
the same pin runs the same code. The desk alarm uses the traffic light
module and button, and the distance sensor lesson runs on a Raspberry Pi 5,
the board its gallery circuit uses.