Operation Sentry
Build an alarm that watches a doorway, learns what "normal" looks like, sounds a siren when someone sneaks in, and then fires a foam rocket at them. You will write every line in plain Python, one mission at a time.
What you will build
- A board that listens to your Python program (Mission 1).
- A sensor "tripwire" across a doorway (Mission 2).
- A siren and a screen that tells you what's going on (Mission 3).
- The full alarm: arm it, learn the room, catch the intruder, disarm with a PIN (Mission 4).
- A USB cannon that fires when the alarm goes off (Mission 5).
The rules of the game
- Plain Python only: variables,
if,while, functions. No classes, no lists, no f-strings. - Every program on this page runs on its own. Copy it, save it, run it.
- Green bars in the code gutter show the lines that are new in that mission. Read those first.
- Foam rockets only. Never aim the cannon at anyone's face.
Set up the kit
Plug every part into the right port, then prove the Pi can see the board before you write any code.
The parts
Where everything plugs in
Hover or tap a part to see its cable and port. The port name is printed on the GrovePi+ next to each white socket. Match the names, not the positions in this drawing.
| Part | Port | What it does in the alarm |
|---|---|---|
| Green LED | D2 | "Armed" light |
| Red LED | D3 | "Alarm!" light |
| Ultrasonic ranger | D5 | The invisible tripwire: measures distance in cm |
| Speaker | D6 | Beeps and the low note of the siren (only D3, D5 and D6 can play a tone) |
| Buzzer | D7 | The high note of the siren |
| Temperature & humidity (blue DHT11) | D8 | Fire alarm, and room conditions on the screen |
| Light sensor | A0 | Catches a torch, or a light switched on or off |
| LCD RGB Backlight | any I2C | Shows the stage, readings and messages. Its colour tells you the stage at a glance. |
| USB office cannon | USB port on the Pi | Mission 5: fires a foam rocket when the alarm goes off |
Check the Pi can see the board
Open a terminal and run this. It scans the I2C wires and lists every device that answers.
Pasting into the Kali terminal: use Ctrl+Shift+V (plain Ctrl+V does not paste in a terminal).
$ i2cdetect -y -a 1 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- 04 -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- 3e -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- 62 -- -- -- -- -- -- -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- --
You should see three numbers: 04 is the GrovePi+ board, 3e is the LCD's text and 62 is the LCD's coloured backlight. Those are their addresses, and your programs use them to pick which device to talk to.
Nothing shows up? Try this.
- Check the GrovePi+ is pushed all the way down onto the Pi's pins and the Pi's green light is on.
- Ask your teacher whether I2C has been switched on for this Pi (it is a one-time setting in
/boot/firmware/config.txt:dtparam=i2c_arm=on, then reboot). - Only
04missing? Unplug and replug the LCD. Only3eand62missing? The LCD cable is loose or in a D port by mistake.
Where to save your programs
Make a folder called sentry in your home folder. Every program on this page gets copied, pasted into your editor and saved there with the file name shown on its tab. You run it from the terminal like this (replace the file name each time):
$ mkdir -p ~/sentry && cd ~/sentry$ sudo python3 mission1_lights.pysudo is needed because talking straight to the I2C wires and USB is a job only the administrator is allowed to do. Ctrl+C stops any of these programs.
Checkpoint
Lights
Make the green and red LEDs take turns blinking, and understand the 5-byte message that makes it happen.
How the Pi talks to the board
Your Python program does not switch the LED on by itself. It sends a short message over two wires (called I2C) to a small chip on the GrovePi+, and that chip does the work. Every message is exactly five bytes (a byte is a number from 0 to 255). Press a button to watch a message travel.
| Command number | Means | Port | Value |
|---|---|---|---|
5 | Set up a port | D2, D3, ... | 1 = output (we will drive it), 0 = input |
2 | Switch a port on or off | D2, D3, ... | 1 = on, 0 = off |
7 | Measure distance (Mission 2) | D5 | ignored |
3 | Read a light level (Mission 2) | A0 | ignored |
4 | Play a tone (Mission 3) | D6 | 128 = tone on, 0 = off |
40 | Read temperature and humidity (Mission 4) | D8 | 0 = blue DHT11 sensor |
The program
Read the comments (the green text). Each function wraps one message so the main program at the bottom reads like English: turn_on(green_led_port).
# Mission 1 - LIGHTS
# GrovePi+ on a Raspberry Pi 5 (Kali Linux)
#
# Plug in: Green LED -> D2 Red LED -> D3
# Run with: sudo python3 mission1_lights.py (Ctrl+C to stop)
#
# What you learn: how the Pi talks to the GrovePi+ board.
# Every message to the board is 5 bytes: 1, command, port, value, 0
import os
import fcntl
import struct
import time
import signal
# ---------- Settings you can change ----------
green_led_port = 2
red_led_port = 3
blink_speed = 0.5 # seconds each LED stays on
# ---------- Connecting to the GrovePi+ ----------
# The GrovePi+ listens on the I2C wires at address 4.
def open_device(address):
device = os.open("/dev/i2c-1", os.O_RDWR)
fcntl.ioctl(device, 0x0703, address) # 0x0703 means "talk to this address"
return device
# ---------- GrovePi+ helpers ----------
# Every GrovePi+ message is 5 bytes: 1, the command number, the port, a value, 0
def grovepi_send(command, port, value):
message = struct.pack("BBBBB", 1, command, port, value, 0)
os.write(grovepi, message)
time.sleep(0.02) # give the board a moment to read it
def make_output(port):
grovepi_send(5, port, 1) # command 5 = set a port to be an output
def turn_on(port):
grovepi_send(2, port, 1) # command 2 = digital write, 1 = on
def turn_off(port):
grovepi_send(2, port, 0) # 0 = off
# ---------- Set up ----------
signal.signal(signal.SIGINT, signal.SIG_DFL) # make Ctrl+C stop the program quietly
grovepi = open_device(0x04)
make_output(green_led_port)
make_output(red_led_port)
print("Blinking! Press Ctrl+C to stop.")
# ---------- Main program ----------
while True:
turn_on(green_led_port) # green on, red off...
turn_off(red_led_port)
time.sleep(blink_speed)
turn_off(green_led_port) # ...then swap
turn_on(red_led_port)
time.sleep(blink_speed)Press Copy, paste into your editor, save as
mission1_lights.pyin yoursentryfolder.Run
sudo python3 mission1_lights.py.The LEDs should swap every half a second. Ctrl+C stops it (one LED may stay on, that's fine).
Find the line
blink_speed = 0.5and change it. Run again.
Tinker
- Make the green LED blink three times for every one blink of the red LED.
- Add a third pattern: both on, both off, both on. Which function do you need to call, and how many times?
- Swap the two port numbers at the top. What happens, and why does nothing else need to change?
Checkpoint
Eyes
Read the ultrasonic ranger and the light sensor, print the numbers, and turn the red LED on when something comes closer than 50 cm.
How the ranger measures distance
The ranger shouts a click too high for you to hear, then listens for the echo. Sound travels at about 343 metres per second, so the longer the echo takes, the further away the object is. The GrovePi+ does the maths and hands back the distance in centimetres. Drag the slider to move the object.
0 means nothing bounced back within range, and anything above about 400 cm is too far to trust.Reading the answer
Sending a message is Mission 1. The new part is reading the reply. The board answers with three bytes. A byte only goes up to 255, so a distance like 300 cm would not fit in one byte. The board splits the number into a "high" byte and a "low" byte, and your program joins them back together:
Try the slider above 255 cm and watch the high byte change from 0 to 1.
The program
Everything with a green bar is new. grovepi_answer() reads the three bytes; read_distance() and read_light() each send a question and then wait for the answer.
# Mission 2 - EYES
# GrovePi+ on a Raspberry Pi 5 (Kali Linux)
#
# Plug in: Green LED -> D2 Red LED -> D3
# Ultrasonic ranger -> D5 Light sensor -> A0
# Run with: sudo python3 mission2_eyes.py (Ctrl+C to stop)
#
# What you learn: asking the board a question and reading its answer.
# The ranger measures distance in cm. The light sensor gives 0 (dark) to 1023 (bright).
# If something comes closer than the tripwire distance, the red LED comes on.
import os
import fcntl
import struct
import time
import signal
# ---------- Settings you can change ----------
green_led_port = 2
red_led_port = 3
ranger_port = 5
light_port = 0 # A0
tripwire = 50 # cm - closer than this = red LED
# ---------- Connecting to the GrovePi+ ----------
def open_device(address):
device = os.open("/dev/i2c-1", os.O_RDWR)
fcntl.ioctl(device, 0x0703, address) # 0x0703 means "talk to this address"
return device
# ---------- GrovePi+ helpers ----------
# Every GrovePi+ message is 5 bytes: 1, the command number, the port, a value, 0
def grovepi_send(command, port, value):
message = struct.pack("BBBBB", 1, command, port, value, 0)
os.write(grovepi, message)
time.sleep(0.02)
# The GrovePi+ answers with 3 bytes: a label, then a number split into two bytes
def grovepi_answer():
reply = os.read(grovepi, 3)
label, high, low = struct.unpack("BBB", reply)
return high * 256 + low # join the two bytes back into one number
def make_output(port):
grovepi_send(5, port, 1) # command 5 = set a port to be an output
def turn_on(port):
grovepi_send(2, port, 1) # command 2 = digital write, 1 = on
def turn_off(port):
grovepi_send(2, port, 0) # 0 = off
def read_distance():
grovepi_send(7, ranger_port, 0) # command 7 = ultrasonic read
time.sleep(0.1) # wait for the echo to come back
return grovepi_answer()
def read_light():
grovepi_send(3, light_port, 0) # command 3 = analog read (0 = dark, 1023 = bright)
time.sleep(0.05)
return grovepi_answer()
# ---------- Set up ----------
signal.signal(signal.SIGINT, signal.SIG_DFL) # make Ctrl+C stop the program quietly
grovepi = open_device(0x04)
make_output(green_led_port)
make_output(red_led_port)
print("Watching... Press Ctrl+C to stop.")
# ---------- Main program ----------
while True:
distance = read_distance()
light = read_light()
print("Distance:", distance, "cm Light:", light)
if distance > 0 and distance < tripwire: # 0 means nothing in range
turn_on(red_led_port) # something is close!
turn_off(green_led_port)
else:
turn_off(red_led_port)
turn_on(green_led_port)
time.sleep(0.3)Copy, paste, save as
mission2_eyes.py, then run it.Point the ranger at a wall. The terminal prints a new line every 0.3 seconds. Wave your hand in front of the ranger.
Cover the light sensor with your thumb, then shine your phone torch on it. Watch the light number.
Walk towards the ranger. The red LED should come on when you are closer than
tripwire(50 cm). Changetripwireto 100 and try again.
Tinker
- Print only when something is closer than the tripwire, instead of every 0.3 seconds.
- Turn the red LED on when the room goes dark instead (hint: compare
lightwith a number, like 200). - Make it a parking sensor: the closer the object, the shorter the
time.sleepbetween red blinks.
Checkpoint
Voice
Count down on the LCD with a beep each second, play a "nee-naw" siren, then show a green "All clear".
Two noises, one siren
The speaker on the GrovePi+ can only play one pitch, and the buzzer only has one pitch too. On their own each is just a flat tone. But if they take turns every 0.3 seconds, you get a siren. That is what the siren() function does, using a for loop to repeat the pair.
Talking to the screen
The LCD is two devices in one: address 0x3E is the text, and 0x62 is the coloured backlight. Each line holds exactly 16 characters, so messages must be short. lcd_show(line1, line2) writes both lines, and lcd_colour(red, green, blue) mixes a colour from three numbers between 0 and 255. Press Run demo to see what the program below does on the screen.
The program
New this mission: the speaker helpers, siren(), and all the LCD helpers. Look at lcd_write_line(): the LCD wants letters as numbers, and ord("A") gives you the number for A (it's 65).
# Mission 3 - VOICE
# GrovePi+ on a Raspberry Pi 5 (Kali Linux)
#
# Plug in: Speaker -> D6 Buzzer -> D7 LCD RGB Backlight -> any I2C port
# Run with: sudo python3 mission3_voice.py
#
# What you learn: making sounds and writing on the screen.
# The program counts down on the screen with a beep each second,
# then plays a "nee-naw" siren, then shows a green "All clear".
import os
import fcntl
import struct
import time
import signal
# ---------- Settings you can change ----------
speaker_port = 6 # must be D3, D5 or D6 - only these ports can play a tone
buzzer_port = 7
countdown_from = 5 # seconds
sound_on = True # set to False to test quietly in class
# ---------- Connecting to the devices ----------
# Every device on the I2C wires has its own address (a number).
def open_device(address):
device = os.open("/dev/i2c-1", os.O_RDWR)
fcntl.ioctl(device, 0x0703, address) # 0x0703 means "talk to this address"
return device
# ---------- GrovePi+ helpers ----------
def grovepi_send(command, port, value):
message = struct.pack("BBBBB", 1, command, port, value, 0)
os.write(grovepi, message)
time.sleep(0.02)
def make_output(port):
grovepi_send(5, port, 1) # command 5 = set a port to be an output
def turn_on(port):
grovepi_send(2, port, 1) # command 2 = digital write, 1 = on
def turn_off(port):
grovepi_send(2, port, 0) # 0 = off
# ---------- Speaker helpers ----------
def speaker_on():
grovepi_send(4, speaker_port, 128) # command 4 = analog write: makes a tone
def speaker_off():
grovepi_send(4, speaker_port, 0)
def beep(seconds):
if sound_on:
speaker_on()
time.sleep(seconds)
speaker_off()
def siren(times):
# "nee-naw": the speaker (low note) and the buzzer (high note) take turns
# "for count in range(times)" repeats the block exactly 'times' times
if sound_on:
for count in range(times):
turn_off(buzzer_port)
speaker_on()
time.sleep(0.3)
speaker_off()
turn_on(buzzer_port)
time.sleep(0.3)
turn_off(buzzer_port)
# ---------- LCD helpers ----------
# The LCD has two addresses: one for the text, one for the coloured backlight.
def lcd_command(code):
os.write(lcd_text, struct.pack("BB", 0x80, code))
time.sleep(0.005)
def lcd_setup():
lcd_command(0x01) # clear the screen
time.sleep(0.05)
lcd_command(0x0C) # screen on, no cursor
lcd_command(0x28) # use both lines
os.write(lcd_backlight, struct.pack("BB", 0, 0)) # wake up the backlight chip
os.write(lcd_backlight, struct.pack("BB", 1, 0))
os.write(lcd_backlight, struct.pack("BB", 8, 0xAA))
def lcd_colour(red, green, blue):
# each colour is a number from 0 (off) to 255 (full)
os.write(lcd_backlight, struct.pack("BB", 4, red))
os.write(lcd_backlight, struct.pack("BB", 3, green))
os.write(lcd_backlight, struct.pack("BB", 2, blue))
def lcd_write_line(code, text):
lcd_command(code) # 0x80 = start of line 1, 0xC0 = start of line 2
text = text.ljust(16) # pad with spaces to clear old letters
for letter in text:
# ord() turns a letter into its number code, which is what the LCD needs
os.write(lcd_text, struct.pack("BB", 0x40, ord(letter)))
def lcd_show(line1, line2):
# Each line holds 16 characters - keep messages short!
lcd_write_line(0x80, line1)
lcd_write_line(0xC0, line2)
# ---------- Set up ----------
signal.signal(signal.SIGINT, signal.SIG_DFL) # make Ctrl+C stop the program quietly
grovepi = open_device(0x04)
lcd_text = open_device(0x3E)
lcd_backlight = open_device(0x62)
make_output(buzzer_port)
make_output(speaker_port)
turn_off(buzzer_port)
speaker_off()
lcd_setup()
# ---------- Main program ----------
lcd_colour(255, 120, 0) # orange
seconds_left = countdown_from
while seconds_left > 0:
lcd_show("Get ready...", "Siren in " + str(seconds_left) + " sec")
print("Siren in", seconds_left)
beep(0.1)
time.sleep(0.9)
seconds_left = seconds_left - 1
lcd_colour(255, 0, 0) # red
lcd_show("!!! NEE-NAW !!!", "Siren test")
print("Siren!")
siren(5)
lcd_colour(0, 255, 0) # green
lcd_show("All clear", "Mission 3 done")
print("Done.")Copy, paste, save as
mission3_voice.py, run it. Turn the blue knob on the speaker if it is too quiet or too loud.Change
countdown_fromto 3 and the message to your name. Run again.Set
sound_on = False. Which lines stop doing anything? Find them.
Tinker
- Make the siren faster by changing one number. Make it play 10 times by changing another.
- Change the countdown colour from orange to purple. (Hint: red and blue, no green.)
- Write a function
flash(colour_name)that flashes the backlight twice. You decide what it takes as an input.
Checkpoint
The brain
Put the pieces together into a real alarm: arm it, learn the room, watch, raise the alarm, and disarm with a secret PIN. Every alarm is written to a log file.
The five stages
The main program is one big while True: loop that goes around the five stages forever. The LCD colour tells you which stage you are in. Step through them.
Why two strikes?
Sensors are a little jumpy. One odd reading could be a fly, a draught or a glitch. The alarm only fires after two unusual readings in a row. Any normal reading in between resets the count to zero. That is the whole job of the strikes variable.
The program
This is the complete alarm. The helpers at the top are the ones you already know, plus one new sensor. The new ideas are marked. Three things you may not have seen before, each explained in a comment: for count in range(times), the % remainder operator ("every 25th loop"), and a function that returns two values.
# Mission 4 - THE BRAIN: Intruder Alarm
# GrovePi+ on a Raspberry Pi 5 (Kali Linux)
#
# Plug the parts into the GrovePi+ like this:
# Green LED -> D2
# Red LED -> D3
# Ultrasonic ranger -> D5
# Speaker -> D6
# Buzzer -> D7
# Temp & humidity -> D8 (the blue DHT11 sensor)
# Light sensor -> A0
# LCD RGB Backlight -> any I2C port
#
# Run with: sudo python3 intruder_alarm.py
# Press Ctrl+C to stop.
#
# How it works:
# 1. ARMING A countdown that beeps every second while you leave the room.
# 2. LEARNING The alarm measures what "normal" looks like: the distance to the
# wall or door, and how bright the room is.
# 3. ARMED It keeps checking. Someone walking through the ultrasonic beam makes
# the distance shorter. A torch, or a light being switched on or off,
# changes the light level. It also watches the temperature, in case
# of a fire. The screen shows the room's temperature and humidity.
# 4. ALARM Red LED, a "nee-naw" siren (speaker and buzzer take turns), a red
# screen - and the time, reason and room conditions go in a log file.
# 5. DISARM Type the secret PIN to stop it. Every wrong PIN is logged and sets
# the siren off again.
import os
import fcntl
import struct
import time
import signal
import getpass
# ---------- Settings you can change ----------
green_led_port = 2
red_led_port = 3
ranger_port = 5
speaker_port = 6 # must be D3, D5 or D6 - only these ports can play a tone
buzzer_port = 7
dht_port = 8
light_port = 0 # A0
secret_pin = "1234" # the PIN that stops the alarm
arming_delay = 10 # seconds you get to leave the room
distance_change = 20 # someone this many cm closer than normal = intruder
light_change = 150 # light level changing by this much = intruder
heat_limit = 40 # temperature (C) that counts as a possible fire
sound_on = True # set to False to test quietly in class
log_file_name = "intrusion_log.txt"
# ---------- Connecting to the devices ----------
# Every device on the I2C connection has its own address (a number).
def open_device(address):
device = os.open("/dev/i2c-1", os.O_RDWR)
fcntl.ioctl(device, 0x0703, address) # 0x0703 means "talk to this address"
return device
# ---------- GrovePi+ helpers ----------
# Every GrovePi+ message is 5 bytes: 1, the command number, the port, a value, 0
def grovepi_send(command, port, value):
message = struct.pack("BBBBB", 1, command, port, value, 0)
os.write(grovepi, message)
time.sleep(0.02)
# The GrovePi+ answers with 3 bytes: a label, then a number split into two bytes
def grovepi_answer():
reply = os.read(grovepi, 3)
label, high, low = struct.unpack("BBB", reply)
return high * 256 + low
def make_output(port):
grovepi_send(5, port, 1) # command 5 = set a port to be an output
def turn_on(port):
grovepi_send(2, port, 1) # command 2 = digital write, 1 = on
def turn_off(port):
grovepi_send(2, port, 0) # 0 = off
def read_distance():
grovepi_send(7, ranger_port, 0) # command 7 = ultrasonic read
time.sleep(0.1) # wait for the echo
return grovepi_answer()
def read_light():
grovepi_send(3, light_port, 0) # command 3 = analog read (0 = dark, 1023 = bright)
time.sleep(0.05)
return grovepi_answer()
def read_temperature_and_humidity():
grovepi_send(40, dht_port, 0) # command 40 = temp & humidity, 0 = blue DHT11
time.sleep(0.6) # this sensor is slow
reply = os.read(grovepi, 9)
# The reply is 9 bytes: a label, then two decimal numbers of 4 bytes each.
# "<Bff" means: B = one byte, f = a 4-byte decimal number, < = byte order
label, temperature, humidity = struct.unpack("<Bff", reply)
return temperature, humidity
# ---------- Speaker helpers ----------
def speaker_on():
grovepi_send(4, speaker_port, 128) # command 4 = analog write: makes a beep tone
def speaker_off():
grovepi_send(4, speaker_port, 0)
def beep(seconds):
if sound_on:
speaker_on()
time.sleep(seconds)
speaker_off()
def siren(times):
# "nee-naw": the speaker (low note) and the buzzer (high note) take turns
if sound_on:
for count in range(times):
turn_off(buzzer_port)
speaker_on()
time.sleep(0.3)
speaker_off()
turn_on(buzzer_port)
time.sleep(0.3)
# ---------- LCD helpers ----------
# The LCD has two addresses: one for the text, one for the coloured backlight.
def lcd_command(code):
os.write(lcd_text, struct.pack("BB", 0x80, code))
time.sleep(0.005)
def lcd_setup():
lcd_command(0x01) # clear the screen
time.sleep(0.05)
lcd_command(0x0C) # screen on, no cursor
lcd_command(0x28) # use both lines
os.write(lcd_backlight, struct.pack("BB", 0, 0)) # wake up the backlight chip
os.write(lcd_backlight, struct.pack("BB", 1, 0))
os.write(lcd_backlight, struct.pack("BB", 8, 0xAA))
def lcd_colour(red, green, blue):
# each colour is a number from 0 (off) to 255 (full)
os.write(lcd_backlight, struct.pack("BB", 4, red))
os.write(lcd_backlight, struct.pack("BB", 3, green))
os.write(lcd_backlight, struct.pack("BB", 2, blue))
def lcd_write_line(code, text):
lcd_command(code) # 0x80 = start of line 1, 0xC0 = start of line 2
text = text.ljust(16) # pad with spaces to clear old letters
for letter in text:
# ord() turns a letter into its number code, which is what the LCD needs
os.write(lcd_text, struct.pack("BB", 0x40, ord(letter)))
def lcd_show(line1, line2):
# Each line holds 16 characters - keep messages short!
lcd_write_line(0x80, line1)
lcd_write_line(0xC0, line2)
# ---------- Log file ----------
def write_log(message):
log_file = open(log_file_name, "a") # "a" = add to the end of the file
log_file.write(time.strftime("%Y-%m-%d %H:%M:%S") + " " + message + "\n")
log_file.close()
# ---------- Set up ----------
signal.signal(signal.SIGINT, signal.SIG_DFL) # make Ctrl+C stop the program quietly
grovepi = open_device(0x04)
lcd_text = open_device(0x3E)
lcd_backlight = open_device(0x62)
make_output(green_led_port)
make_output(red_led_port)
make_output(buzzer_port)
make_output(speaker_port)
turn_off(green_led_port) # start with everything off
turn_off(red_led_port)
turn_off(buzzer_port)
speaker_off()
lcd_setup()
temperature = 0
humidity = 0
print("Intruder alarm started. Press Ctrl+C to stop.")
# ---------- Main program ----------
while True:
# 1. ARMING - countdown so you can leave the room
lcd_colour(255, 120, 0) # orange
seconds_left = arming_delay
while seconds_left > 0:
lcd_show("Arming...", "Leave in " + str(seconds_left) + " sec")
turn_on(green_led_port) # blink the green LED...
beep(0.1) # ...and beep
time.sleep(0.4)
turn_off(green_led_port)
time.sleep(0.5)
seconds_left = seconds_left - 1
# 2. LEARNING - what does the room look like when nobody is there?
normal_distance = read_distance()
if normal_distance == 0: # 0 means nothing in range
normal_distance = 400
normal_light = read_light()
write_log("ARMED (normal distance " + str(normal_distance) + " cm, light " + str(normal_light) + ")")
print("Armed. Normal distance:", normal_distance, "cm Normal light:", normal_light)
beep(0.5) # one long beep = armed
# 3. ARMED - keep checking until something changes
lcd_colour(0, 0, 255) # blue
turn_on(green_led_port)
strikes = 0 # how many odd readings in a row
reason = ""
loops = 0
while strikes < 2: # 2 in a row stops false alarms
# The temp & humidity sensor is slow, so only check it every 25 loops
if loops % 25 == 0:
new_temperature, new_humidity = read_temperature_and_humidity()
# Only keep sensible readings (a failed reading is ignored)
if new_temperature > 0 and new_temperature < 60:
temperature = round(new_temperature)
humidity = round(new_humidity)
loops = loops + 1
distance = read_distance()
light = read_light()
lcd_show("ARMED " + str(temperature) + "C " + str(humidity) + "%",
str(distance) + "cm light " + str(light))
if distance > 0 and distance < normal_distance - distance_change:
strikes = strikes + 1
reason = "Movement " + str(distance) + "cm"
elif abs(light - normal_light) > light_change:
strikes = strikes + 1
reason = "Light changed"
elif temperature > heat_limit:
strikes = strikes + 1
reason = "FIRE? " + str(temperature) + "C"
else:
strikes = 0
time.sleep(0.2)
# 4. ALARM!
turn_off(green_led_port)
turn_on(red_led_port)
lcd_colour(255, 0, 0) # red
lcd_show("!!! ALARM !!!", reason)
write_log("ALARM - " + reason + " (room " + str(temperature) + "C, " + str(humidity) + "% humidity)")
print()
print("!!! ALARM !!!", reason)
siren(5) # nee-naw 5 times...
if sound_on:
turn_on(buzzer_port) # ...then the buzzer stays on
# 5. DISARM - keep asking until the right PIN is typed
# getpass hides what you type, so nobody can read the PIN over your shoulder
wrong_tries = 0
typed_pin = getpass.getpass("Enter PIN to stop the alarm: ")
while typed_pin != secret_pin:
wrong_tries = wrong_tries + 1
write_log("WRONG PIN entered (attempt " + str(wrong_tries) + ")")
print("Wrong PIN!")
lcd_show("WRONG PIN!", "Attempts: " + str(wrong_tries))
siren(3)
if sound_on:
turn_on(buzzer_port)
typed_pin = getpass.getpass("Enter PIN to stop the alarm: ")
turn_off(buzzer_port)
turn_off(red_led_port)
lcd_colour(0, 255, 0) # green
lcd_show("Disarmed", "Wrong PINs: " + str(wrong_tries))
write_log("DISARMED after " + str(wrong_tries) + " wrong PIN(s)")
print("Alarm stopped.")
beep(0.1) # two short "all clear" beeps
time.sleep(0.1)
beep(0.1)
input("Press Enter to arm the alarm again...")Copy, paste, save as
intruder_alarm.py, run it. Stand still behind the ranger during the 10-second countdown.When the screen goes blue, walk through the beam. The screen goes red and the siren plays.
Type a wrong PIN first (it is hidden while you type), then the right one:
1234.Open the log:
cat intrusion_log.txt. Every arm, alarm and wrong PIN is there with the time.Fire alarm test: set
heat_limitto a couple of degrees above the room temperature shown on the screen, re-arm, and warm the blue sensor in your hand.
Testing in a full classroom: set sound_on = False while you test, or twenty sirens go off at once. Set arming_delay to 3 so you are not waiting around.
Tinker
- Change the PIN. Then make the alarm give up after 3 wrong PINs and lock for 30 seconds.
- Count how many times the alarm has gone off since the program started and show it on the "Disarmed" screen.
- Make the countdown beep faster in the last 3 seconds.
- Think like a hacker: the PIN is written in the program. Who can read it? The log records every wrong PIN. What would a brute-force attack look like in that file?
Checkpoint
Return fire
Control the USB office cannon from Python, aim it at the doorway, then plug it into your alarm so it fires when an intruder is caught.
Safety first. Foam rockets only, never anything else in the tubes. Never aim at a face. Agree on the "target zone" with your teacher before you arm it. The cannon is a toy, treat it like one.
A different kind of device
The cannon does not plug into the GrovePi+. It is a USB device, like a mouse, so it needs a different library (usb.core) and a different message. Every message is 8 bytes. The first byte is 2 for "move" (or 3 for "the light"), the second byte is the command, and the rest are zeros. There is no "move 10 degrees" command: you tell it to start turning, wait, then tell it to stop. Try it.
nudge in the test program. Park swings the cannon fully down and left, so every run starts from the same spot.| Command number | Name in the program | What the cannon does |
|---|---|---|
1 | cannon_down | tilts the barrels down |
2 | cannon_up | tilts the barrels up |
4 | cannon_left | turns left |
8 | cannon_right | turns right |
16 | cannon_fire | fires one rocket (takes about 4 seconds, then reloads the next tube) |
32 | cannon_stop | stops moving |
Part A: install the library and find the cannon
Plug the cannon's USB cable into the Pi. Install the USB library (one time):
$ sudo apt install -y python3-usbCheck the Pi can see it:
$ lsusb Bus 001 Device 003: ID 2123:1010 Dream Cheeky Thunder
Those two numbers are the cannon's ID: maker
2123, product1010. The program uses them to find the cannon among all the USB devices.Copy the test program, save as
cannon_test.py, run it withsudo. It parks the cannon (10 seconds), then waits for your keys.
# Mission 5A - CANNON TEST
# USB Office Cannon on a Raspberry Pi 5 (Kali Linux)
#
# Plug in: the cannon's USB cable -> any USB port on the Pi
# Install: sudo apt install -y python3-usb
# Run with: sudo python3 cannon_test.py
#
# What you learn: the cannon is a USB device. We send it 8-byte messages:
# 2, command, 0, 0, 0, 0, 0, 0
# where the command number tells it which way to move (or to fire).
#
# Type a letter and press Enter:
# l = left r = right u = up d = down f = FIRE p = park q = quit
import sys
import struct
import time
import usb.core
# ---------- Settings you can change ----------
nudge = 0.3 # seconds the cannon moves for each key press
# ---------- Cannon command numbers ----------
cannon_down = 1
cannon_up = 2
cannon_left = 4
cannon_right = 8
cannon_fire = 16
cannon_stop = 32
# ---------- Cannon helpers ----------
def cannon_send(command):
# 8 bytes: 2 means "a movement command", then the command, then six zeros
message = struct.pack("BBBBBBBB", 2, command, 0, 0, 0, 0, 0, 0)
cannon.ctrl_transfer(0x21, 0x09, 0, 0, message)
def cannon_move(command, seconds):
cannon_send(command) # start moving...
time.sleep(seconds) # ...for this long...
cannon_send(cannon_stop) # ...then stop
def cannon_light(on):
# 3 means "the LED": on = 1 lights it up, on = 0 switches it off
message = struct.pack("BBBBBBBB", 3, on, 0, 0, 0, 0, 0, 0)
cannon.ctrl_transfer(0x21, 0x09, 0, 0, message)
def cannon_shoot(rockets):
for count in range(rockets):
cannon_send(cannon_fire)
time.sleep(4.5) # it takes about 4 seconds to fire and reload
def cannon_park():
# swing all the way down and left, so every run starts from the same place
cannon_move(cannon_down, 2)
cannon_move(cannon_left, 8)
# ---------- Set up ----------
# Every USB device has two ID numbers. These are the Dream Cheeky "Thunder" cannon.
cannon = usb.core.find(idVendor=0x2123, idProduct=0x1010)
if cannon is None:
print("Cannon not found. Is it plugged in? Try: lsusb")
sys.exit()
# Linux grabs the cannon as if it were a keyboard. Ask it to let go.
if cannon.is_kernel_driver_active(0):
cannon.detach_kernel_driver(0)
cannon.set_configuration()
print("Cannon found! Parking it (this takes 10 seconds)...")
cannon_park()
cannon_light(1)
# ---------- Main program ----------
key = ""
while key != "q":
key = input("l/r/u/d/f/p/q then Enter: ")
if key == "l":
cannon_move(cannon_left, nudge)
elif key == "r":
cannon_move(cannon_right, nudge)
elif key == "u":
cannon_move(cannon_up, nudge)
elif key == "d":
cannon_move(cannon_down, nudge)
elif key == "f":
print("FIRE!")
cannon_shoot(1)
elif key == "p":
cannon_park()
cannon_light(0)
print("Bye.")Use l r u d to point the cannon at the target zone. Count your presses. If it took 10 presses of r and 3 of u from parked, that is 3.0 seconds right and 0.9 seconds up. You will type those numbers into the alarm as aim_right and aim_up.
Part B: the alarm that fires back
This is Mission 4's program with the cannon helpers added. The green bars show exactly what changed: a new library, four settings, the cannon functions, finding the cannon at start-up, parking and aiming, and the FIRE lines in stage 4. The cannon only holds 4 rockets, so the program counts them and asks you to reload.
# Mission 5B - RETURN FIRE: Intruder Alarm with USB Cannon
# GrovePi+ and USB Office Cannon on a Raspberry Pi 5 (Kali Linux)
#
# Plug the cannon's USB cable into any USB port on the Pi.
# Plug the parts into the GrovePi+ like this:
# Green LED -> D2
# Red LED -> D3
# Ultrasonic ranger -> D5
# Speaker -> D6
# Buzzer -> D7
# Temp & humidity -> D8 (the blue DHT11 sensor)
# Light sensor -> A0
# LCD RGB Backlight -> any I2C port
#
# Run with: sudo python3 intruder_alarm_cannon.py
# Press Ctrl+C to stop.
#
# How it works:
# 1. ARMING A countdown that beeps every second while you leave the room.
# 2. LEARNING The alarm measures what "normal" looks like: the distance to the
# wall or door, and how bright the room is.
# 3. ARMED It keeps checking. Someone walking through the ultrasonic beam makes
# the distance shorter. A torch, or a light being switched on or off,
# changes the light level. It also watches the temperature, in case
# of a fire. The screen shows the room's temperature and humidity.
# 4. ALARM Red LED, a "nee-naw" siren (speaker and buzzer take turns), a red
# screen - and the time, reason and room conditions go in a log file.
# Then the CANNON FIRES at the intruder!
# 5. DISARM Type the secret PIN to stop it. Every wrong PIN is logged and sets
# the siren off again.
import os
import sys
import fcntl
import struct
import time
import signal
import getpass
import usb.core
# ---------- Settings you can change ----------
green_led_port = 2
red_led_port = 3
ranger_port = 5
speaker_port = 6 # must be D3, D5 or D6 - only these ports can play a tone
buzzer_port = 7
dht_port = 8
light_port = 0 # A0
secret_pin = "1234" # the PIN that stops the alarm
arming_delay = 10 # seconds you get to leave the room
distance_change = 20 # someone this many cm closer than normal = intruder
light_change = 150 # light level changing by this much = intruder
heat_limit = 40 # temperature (C) that counts as a possible fire
sound_on = True # set to False to test quietly in class
log_file_name = "intrusion_log.txt"
aim_right = 3.0 # seconds to turn right from the parked position to aim at the door
aim_up = 0.8 # seconds to tilt up from the parked position
rockets_loaded = 4 # how many rockets you put in the cannon
rockets_per_alarm = 1 # how many to fire each time the alarm goes off
# ---------- Cannon command numbers ----------
cannon_down = 1
cannon_up = 2
cannon_left = 4
cannon_right = 8
cannon_fire = 16
cannon_stop = 32
# ---------- Connecting to the devices ----------
# Every device on the I2C connection has its own address (a number).
def open_device(address):
device = os.open("/dev/i2c-1", os.O_RDWR)
fcntl.ioctl(device, 0x0703, address) # 0x0703 means "talk to this address"
return device
# ---------- GrovePi+ helpers ----------
# Every GrovePi+ message is 5 bytes: 1, the command number, the port, a value, 0
def grovepi_send(command, port, value):
message = struct.pack("BBBBB", 1, command, port, value, 0)
os.write(grovepi, message)
time.sleep(0.02)
# The GrovePi+ answers with 3 bytes: a label, then a number split into two bytes
def grovepi_answer():
reply = os.read(grovepi, 3)
label, high, low = struct.unpack("BBB", reply)
return high * 256 + low
def make_output(port):
grovepi_send(5, port, 1) # command 5 = set a port to be an output
def turn_on(port):
grovepi_send(2, port, 1) # command 2 = digital write, 1 = on
def turn_off(port):
grovepi_send(2, port, 0) # 0 = off
def read_distance():
grovepi_send(7, ranger_port, 0) # command 7 = ultrasonic read
time.sleep(0.1) # wait for the echo
return grovepi_answer()
def read_light():
grovepi_send(3, light_port, 0) # command 3 = analog read (0 = dark, 1023 = bright)
time.sleep(0.05)
return grovepi_answer()
def read_temperature_and_humidity():
grovepi_send(40, dht_port, 0) # command 40 = temp & humidity, 0 = blue DHT11
time.sleep(0.6) # this sensor is slow
reply = os.read(grovepi, 9)
# The reply is 9 bytes: a label, then two decimal numbers of 4 bytes each.
# "<Bff" means: B = one byte, f = a 4-byte decimal number, < = byte order
label, temperature, humidity = struct.unpack("<Bff", reply)
return temperature, humidity
# ---------- Speaker helpers ----------
def speaker_on():
grovepi_send(4, speaker_port, 128) # command 4 = analog write: makes a beep tone
def speaker_off():
grovepi_send(4, speaker_port, 0)
def beep(seconds):
if sound_on:
speaker_on()
time.sleep(seconds)
speaker_off()
def siren(times):
# "nee-naw": the speaker (low note) and the buzzer (high note) take turns
if sound_on:
for count in range(times):
turn_off(buzzer_port)
speaker_on()
time.sleep(0.3)
speaker_off()
turn_on(buzzer_port)
time.sleep(0.3)
# ---------- Cannon helpers ----------
# The cannon is a USB device. Every message is 8 bytes: 2, command, 0, 0, 0, 0, 0, 0
def cannon_send(command):
message = struct.pack("BBBBBBBB", 2, command, 0, 0, 0, 0, 0, 0)
cannon.ctrl_transfer(0x21, 0x09, 0, 0, message)
def cannon_move(command, seconds):
cannon_send(command) # start moving...
time.sleep(seconds) # ...for this long...
cannon_send(cannon_stop) # ...then stop
def cannon_light(on):
# 3 means "the LED": on = 1 lights it up, on = 0 switches it off
message = struct.pack("BBBBBBBB", 3, on, 0, 0, 0, 0, 0, 0)
cannon.ctrl_transfer(0x21, 0x09, 0, 0, message)
def cannon_shoot(rockets):
for count in range(rockets):
cannon_send(cannon_fire)
time.sleep(4.5) # it takes about 4 seconds to fire and reload
def cannon_park():
# swing all the way down and left, so every run starts from the same place
cannon_move(cannon_down, 2)
cannon_move(cannon_left, 8)
def cannon_aim():
# from the parked position, turn and tilt to point at the doorway
cannon_move(cannon_right, aim_right)
cannon_move(cannon_up, aim_up)
# ---------- LCD helpers ----------
# The LCD has two addresses: one for the text, one for the coloured backlight.
def lcd_command(code):
os.write(lcd_text, struct.pack("BB", 0x80, code))
time.sleep(0.005)
def lcd_setup():
lcd_command(0x01) # clear the screen
time.sleep(0.05)
lcd_command(0x0C) # screen on, no cursor
lcd_command(0x28) # use both lines
os.write(lcd_backlight, struct.pack("BB", 0, 0)) # wake up the backlight chip
os.write(lcd_backlight, struct.pack("BB", 1, 0))
os.write(lcd_backlight, struct.pack("BB", 8, 0xAA))
def lcd_colour(red, green, blue):
# each colour is a number from 0 (off) to 255 (full)
os.write(lcd_backlight, struct.pack("BB", 4, red))
os.write(lcd_backlight, struct.pack("BB", 3, green))
os.write(lcd_backlight, struct.pack("BB", 2, blue))
def lcd_write_line(code, text):
lcd_command(code) # 0x80 = start of line 1, 0xC0 = start of line 2
text = text.ljust(16) # pad with spaces to clear old letters
for letter in text:
# ord() turns a letter into its number code, which is what the LCD needs
os.write(lcd_text, struct.pack("BB", 0x40, ord(letter)))
def lcd_show(line1, line2):
# Each line holds 16 characters - keep messages short!
lcd_write_line(0x80, line1)
lcd_write_line(0xC0, line2)
# ---------- Log file ----------
def write_log(message):
log_file = open(log_file_name, "a") # "a" = add to the end of the file
log_file.write(time.strftime("%Y-%m-%d %H:%M:%S") + " " + message + "\n")
log_file.close()
# ---------- Set up ----------
signal.signal(signal.SIGINT, signal.SIG_DFL) # make Ctrl+C stop the program quietly
grovepi = open_device(0x04)
lcd_text = open_device(0x3E)
lcd_backlight = open_device(0x62)
# Every USB device has two ID numbers. These are the Dream Cheeky "Thunder" cannon.
cannon = usb.core.find(idVendor=0x2123, idProduct=0x1010)
if cannon is None:
print("Cannon not found. Is it plugged in? Try: lsusb")
sys.exit()
if cannon.is_kernel_driver_active(0):
cannon.detach_kernel_driver(0) # Linux grabs the cannon as if it were a keyboard - let go
cannon.set_configuration()
make_output(green_led_port)
make_output(red_led_port)
make_output(buzzer_port)
make_output(speaker_port)
turn_off(green_led_port) # start with everything off
turn_off(red_led_port)
turn_off(buzzer_port)
speaker_off()
lcd_setup()
temperature = 0
humidity = 0
rockets_left = rockets_loaded
print("Intruder alarm started. Press Ctrl+C to stop.")
print("Parking and aiming the cannon (about 15 seconds)...")
cannon_park()
cannon_aim()
# ---------- Main program ----------
while True:
# 1. ARMING - countdown so you can leave the room
lcd_colour(255, 120, 0) # orange
seconds_left = arming_delay
while seconds_left > 0:
lcd_show("Arming...", "Leave in " + str(seconds_left) + " sec")
turn_on(green_led_port) # blink the green LED...
beep(0.1) # ...and beep
time.sleep(0.4)
turn_off(green_led_port)
time.sleep(0.5)
seconds_left = seconds_left - 1
# 2. LEARNING - what does the room look like when nobody is there?
normal_distance = read_distance()
if normal_distance == 0: # 0 means nothing in range
normal_distance = 400
normal_light = read_light()
write_log("ARMED (normal distance " + str(normal_distance) + " cm, light " + str(normal_light) + ")")
print("Armed. Normal distance:", normal_distance, "cm Normal light:", normal_light)
beep(0.5) # one long beep = armed
# 3. ARMED - keep checking until something changes
lcd_colour(0, 0, 255) # blue
turn_on(green_led_port)
strikes = 0 # how many odd readings in a row
reason = ""
loops = 0
while strikes < 2: # 2 in a row stops false alarms
# The temp & humidity sensor is slow, so only check it every 25 loops
if loops % 25 == 0:
new_temperature, new_humidity = read_temperature_and_humidity()
# Only keep sensible readings (a failed reading is ignored)
if new_temperature > 0 and new_temperature < 60:
temperature = round(new_temperature)
humidity = round(new_humidity)
loops = loops + 1
distance = read_distance()
light = read_light()
lcd_show("ARMED " + str(temperature) + "C " + str(humidity) + "%",
str(distance) + "cm light " + str(light))
if distance > 0 and distance < normal_distance - distance_change:
strikes = strikes + 1
reason = "Movement " + str(distance) + "cm"
elif abs(light - normal_light) > light_change:
strikes = strikes + 1
reason = "Light changed"
elif temperature > heat_limit:
strikes = strikes + 1
reason = "FIRE? " + str(temperature) + "C"
else:
strikes = 0
time.sleep(0.2)
# 4. ALARM!
turn_off(green_led_port)
turn_on(red_led_port)
lcd_colour(255, 0, 0) # red
lcd_show("!!! ALARM !!!", reason)
write_log("ALARM - " + reason + " (room " + str(temperature) + "C, " + str(humidity) + "% humidity)")
print()
print("!!! ALARM !!!", reason)
siren(2) # nee-naw twice...
cannon_light(1) # ...light up the cannon...
if rockets_left >= rockets_per_alarm:
print("FIRE!")
cannon_shoot(rockets_per_alarm) # ...and FIRE!
rockets_left = rockets_left - rockets_per_alarm
write_log("FIRED " + str(rockets_per_alarm) + " rocket(s), " + str(rockets_left) + " left")
else:
print("Out of rockets!")
siren(3) # nee-naw 3 more times...
if sound_on:
turn_on(buzzer_port) # ...then the buzzer stays on
# 5. DISARM - keep asking until the right PIN is typed
# getpass hides what you type, so nobody can read the PIN over your shoulder
wrong_tries = 0
typed_pin = getpass.getpass("Enter PIN to stop the alarm: ")
while typed_pin != secret_pin:
wrong_tries = wrong_tries + 1
write_log("WRONG PIN entered (attempt " + str(wrong_tries) + ")")
print("Wrong PIN!")
lcd_show("WRONG PIN!", "Attempts: " + str(wrong_tries))
siren(3)
if sound_on:
turn_on(buzzer_port)
typed_pin = getpass.getpass("Enter PIN to stop the alarm: ")
turn_off(buzzer_port)
turn_off(red_led_port)
cannon_light(0)
lcd_colour(0, 255, 0) # green
lcd_show("Disarmed", "Rockets left: " + str(rockets_left))
write_log("DISARMED after " + str(wrong_tries) + " wrong PIN(s)")
print("Alarm stopped. Rockets left:", rockets_left)
beep(0.1) # two short "all clear" beeps
time.sleep(0.1)
beep(0.1)
if rockets_left < rockets_per_alarm:
input("Reload the cannon, then press Enter to arm again...")
rockets_left = rockets_loaded
else:
input("Press Enter to arm the alarm again...")Copy, paste, save as
intruder_alarm_cannon.py. Setaim_rightandaim_upto the numbers you worked out in Part A.Load 4 rockets. Run with
sudo. The cannon parks, aims, then the countdown starts.Send someone through the beam (into the target zone). Siren, FIRE, siren, PIN.
Check the log: the FIRED line tells you how many rockets are left.
Tinker
- Fire two rockets per alarm. Which setting?
- Sweep while firing: turn right for 0.2 s between rockets, so the shots spread across the doorway.
- Warning shot: flash the cannon's light three times and play the siren before firing, to give the intruder a chance to leave.
- Big challenge: add a second ranger on D4, one watching the left of the room and one the right. Aim the cannon at whichever side saw the intruder.
Checkpoint
Invent something
Every program you wrote is made of the same three kinds of building block. Mix them into something new.
Inputs (things you can read)
read_distance()from the rangerread_light()from the light sensorread_temperature_and_humidity()getpass.getpass()orinput()from the keyboardtime.strftime(), the clock
Decisions (things you can test)
- closer than / further than a number
- brighter / darker than normal
- hotter than a limit
- the same as a secret word
- count in a row (strikes), count in total, every Nth loop with
%
Outputs (things you can do)
turn_on()/turn_off()an LED or buzzerbeep(),siren()lcd_show(),lcd_colour()write_log()to a filecannon_move(),cannon_shoot(),cannon_light()
Ideas to start from
Fridge raider
The light sensor sits inside the fridge. Every time the door opens the light changes. Log the time of every raid.
Reverse parking sensor
Beeps get faster as the object gets closer. Solid tone under 10 cm. Show the distance on the screen.
Classroom thermometer
Blue when cold, green when comfortable, red when hot. Log a reading every minute (hint: %).
Door counter
Count how many people walk through the doorway in a lesson. One person should count once, not five times. That is harder than it sounds.
Two-player quick-draw
Random wait, then the green LED lights. First player to type their letter wins. The loser gets a rocket.
Desk guard with a password
Your alarm, but the arming countdown only starts after the right password, and the log records who armed it.
Sentry that tracks
Left ranger sees something: turn left. Right ranger: turn right. Both: fire. Welcome to robotics.
Plan it before you code it
- Write one sentence: "When input is decision, do output."
- Copy the program that is closest to your idea (usually Mission 2 or 4).
- Delete what you don't need. Smaller programs are easier to fix.
- Change one thing, run it, check it. Then the next thing.
Quiz
Teacher notes
One-time Pi setup (do once per Pi, or push with pifleet)
Kali on the Pi 5 does not enable I2C by default and has no raspi-config toggle for it. Edit the config file, install the tools, add the student account to the hardware groups, then reboot.
$ sudo sh -c 'grep -q "^dtparam=i2c_arm=on" /boot/firmware/config.txt || echo dtparam=i2c_arm=on >> /boot/firmware/config.txt' $ sudo apt update $ sudo apt install -y i2c-tools python3-usb $ sudo usermod -aG i2c,gpio,dialout,plugdev kali $ sudo reboot
Replace kali with the student login if it differs. If python3-usb is not in the repo on a given image, sudo python3 -m pip install --break-system-packages pyusb does the same job. The programs run with sudo regardless, which avoids udev rules for the cannon.
USB power for the cannon. The cannon draws more than the 600 mA the Pi 5 allows its USB ports by default, and the firing motor is the hungriest part. With the official 27 W (5 V 5 A) supply the Pi raises the limit to 1.6 A automatically. With any other supply, add usb_max_current_enable=1 to /boot/firmware/config.txt and reboot, and expect low-voltage warnings if the supply is marginal.
Hardware notes and known limits
- Board: this is written for the Dexter Industries GrovePi+ (I2C address 0x04), not the Seeed Base HAT. The 5-byte protocol and command numbers come from Dexter's firmware source. The ultrasonic reading has been verified on your board; the LCD, speaker and DHT code follow Dexter's own examples but were checked in simulation, so run Mission 3 yourself before the lesson.
- Speaker: only D3, D5 and D6 can play a tone (PWM pins). The GrovePi+ gives a fixed pitch, hence the two-part siren. The blue potentiometer on the speaker module is the volume.
- DHT11: about 0.6 s per reading and the occasional failed read (NaN). The alarm polls it every 25 loops and ignores readings outside 0 to 60 °C. Humidity from a DHT11 is ±5 %, good enough for a screen readout.
- Ultrasonic: reliable from about 3 cm to 350 cm. Reading 0 means no echo. Soft furnishings and angled surfaces can swallow the echo; aim it at a flat wall or door.
- Cannon: Dream Cheeky "Thunder" (USB ID 2123:1010), the model Dexter Industries used in the video this extension is based on. Pan is roughly 270°, tilt about 45°, four rockets, about 4 s per shot. The protocol (8-byte HID report, commands 1/2/4/8/16/32) is from Dexter's
office_cannon_v1.py. Iflsusbshows0a81:0701instead, that is the older model: change theusb.core.findline to those IDs and incannon_sendusecannon.ctrl_transfer(0x21, 0x09, 0x0200, 0, struct.pack("B", command)). The older model has no light. - Ctrl+C during an alarm leaves the buzzer on. Running any program again switches it off at start-up.
- Pi 5 Active Cooler: the GrovePi+ will not seat over it. Use low-profile heatsinks or a stacking header on the fleet.
Lesson plan (five lessons)
| Lesson | Missions | Students leave with |
|---|---|---|
| 1 | Setup, Mission 1 | Working kit, blinking LEDs, the 5-byte message explained in their own words |
| 2 | Mission 2 | Distance and light readings on screen, red LED tripwire, one tinker task done |
| 3 | Mission 3 | Siren and LCD working, a custom message and colour |
| 4 | Mission 4 | Full alarm, log file inspected, PIN discussion (plaintext secrets, brute force) |
| 5 | Mission 5 (+ Invent) | Cannon fires on intrusion; fast finishers start an invention |
Mission 5 works best as a demonstration station if you have fewer cannons than kits: each group brings their calibrated aim_right / aim_up numbers to the station.
Differentiation and assessment
- Support: the checkpoints are the minimum. A student who completes Missions 1 to 3 has met the hardware-control outcomes; Mission 4 can be run as a demo with them changing settings only.
- Extend: the Tinker boxes escalate. The two-ranger sentry and the door counter are the genuinely hard ones.
- Evidence: the log file is timestamped evidence of a working alarm. Ask for a screenshot of
cat intrusion_log.txtplus a one-paragraph explanation ofstrikes. - Cybersecurity links: plaintext PIN in source, the wrong-PIN log as an attack record,
getpassversusinput(shoulder surfing), and why the Pi is "listening" on an unencrypted wire. - Quiz: ten questions on the page, self-marking, no storage. Answers are not shown until a choice is made.
All the programs
Each program is also downloadable from its code box. File names: mission1_lights.py, mission2_eyes.py, mission3_voice.py, intruder_alarm.py, cannon_test.py, intruder_alarm_cannon.py. They are independent; a student can start at any mission.