Raspberry Pi 5 · GrovePi+ · Python

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.

doorway 186 cm from the sensor ultrasonic "tripwire" beam GrovePi+ ARMED Pi 5 + GrovePi+ with sensors, LEDs, buzzer and LCD 186 cm USB cannon ! Stage 3 · ARMED
Hover to pause · the loop takes about 15 seconds
The LCD screen
LEDs
greenred
Terminal
intrusion_log.txt

What you will build

  1. A board that listens to your Python program (Mission 1).
  2. A sensor "tripwire" across a doorway (Mission 2).
  3. A siren and a screen that tells you what's going on (Mission 3).
  4. The full alarm: arm it, learn the room, catch the intruder, disarm with a PIN (Mission 4).
  5. 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.
0mission

Set up the kit

about 15 minutes
Goal

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.

Grove cables only fit one way round. Push until they click. The LCD can go in any of the three I2C ports.
PartPortWhat it does in the alarm
Green LEDD2"Armed" light
Red LEDD3"Alarm!" light
Ultrasonic rangerD5The invisible tripwire: measures distance in cm
SpeakerD6Beeps and the low note of the siren (only D3, D5 and D6 can play a tone)
BuzzerD7The high note of the siren
Temperature & humidity (blue DHT11)D8Fire alarm, and room conditions on the screen
Light sensorA0Catches a torch, or a light switched on or off
LCD RGB Backlightany I2CShows the stage, readings and messages. Its colour tells you the stage at a glance.
USB office cannonUSB port on the PiMission 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).

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.
  1. Check the GrovePi+ is pushed all the way down onto the Pi's pins and the Pi's green light is on.
  2. 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).
  3. Only 04 missing? Unplug and replug the LCD. Only 3e and 62 missing? 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):

terminal
$ mkdir -p ~/sentry && cd ~/sentry
terminal
$ sudo python3 mission1_lights.py

sudo 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

1mission

Lights

about 20 minutes
Goal

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.

The first byte is always 1 and the last is always 0. The middle three are the ones you choose: command, port, value.
Command numberMeansPortValue
5Set up a portD2, D3, ...1 = output (we will drive it), 0 = input
2Switch a port on or offD2, D3, ...1 = on, 0 = off
7Measure distance (Mission 2)D5ignored
3Read a light level (Mission 2)A0ignored
4Play a tone (Mission 3)D6128 = tone on, 0 = off
40Read temperature and humidity (Mission 4)D80 = 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).

mission1_lights.py
Python · plain text · paste into your editor and save as mission1_lights.py
  1. Press Copy, paste into your editor, save as mission1_lights.py in your sentry folder.

  2. 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).

  3. Find the line blink_speed = 0.5 and 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

2mission

Eyes

about 25 minutes
Goal

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.

Two readings matter: 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.

mission2_eyes.py
Python · plain text · paste into your editor and save as mission2_eyes.py
  1. 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.

  2. Cover the light sensor with your thumb, then shine your phone torch on it. Watch the light number.

  3. Walk towards the ranger. The red LED should come on when you are closer than tripwire (50 cm). Change tripwire to 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 light with a number, like 200).
  • Make it a parking sensor: the closer the object, the shorter the time.sleep between red blinks.

Checkpoint

3mission

Voice

about 25 minutes
Goal

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.

(3 seconds, quiet)

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).

mission3_voice.py
Python · plain text · paste into your editor and save as mission3_voice.py
  1. Copy, paste, save as mission3_voice.py, run it. Turn the blue knob on the speaker if it is too quiet or too loud.

  2. Change countdown_from to 3 and the message to your name. Run again.

  3. 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

4mission

The brain

about 50 minutes
Goal

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.

greenred

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.

intruder_alarm.py
Python · plain text · paste into your editor and save as intruder_alarm.py
  1. Copy, paste, save as intruder_alarm.py, run it. Stand still behind the ranger during the 10-second countdown.

  2. When the screen goes blue, walk through the beam. The screen goes red and the siren plays.

  3. Type a wrong PIN first (it is hidden while you type), then the right one: 1234.

  4. Open the log: cat intrusion_log.txt. Every arm, alarm and wrong PIN is there with the time.

  5. Fire alarm test: set heat_limit to 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

5mission

Return fire

about 50 minutes
Goal

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.

press a button
Rockets: 4 ·
Each button is 0.3 seconds of movement, exactly like nudge in the test program. Park swings the cannon fully down and left, so every run starts from the same spot.
Command numberName in the programWhat the cannon does
1cannon_downtilts the barrels down
2cannon_uptilts the barrels up
4cannon_leftturns left
8cannon_rightturns right
16cannon_firefires one rocket (takes about 4 seconds, then reloads the next tube)
32cannon_stopstops moving

Part A: install the library and find the cannon

  1. Plug the cannon's USB cable into the Pi. Install the USB library (one time):

    terminal
    $ sudo apt install -y python3-usb
  2. Check the Pi can see it:

    terminal
    $ lsusb
    Bus 001 Device 003: ID 2123:1010 Dream Cheeky Thunder

    Those two numbers are the cannon's ID: maker 2123, product 1010. The program uses them to find the cannon among all the USB devices.

  3. Copy the test program, save as cannon_test.py, run it with sudo. It parks the cannon (10 seconds), then waits for your keys.

cannon_test.py
Python · plain text · paste into your editor and save as cannon_test.py

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.

intruder_alarm_cannon.py
Python · plain text · paste into your editor and save as intruder_alarm_cannon.py
  1. Copy, paste, save as intruder_alarm_cannon.py. Set aim_right and aim_up to the numbers you worked out in Part A.

  2. Load 4 rockets. Run with sudo. The cannon parks, aims, then the countdown starts.

  3. Send someone through the beam (into the target zone). Siren, FIRE, siren, PIN.

  4. 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

★bonus

Invent something

as long as you like
Goal

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 ranger
  • read_light() from the light sensor
  • read_temperature_and_humidity()
  • getpass.getpass() or input() from the keyboard
  • time.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 buzzer
  • beep(), siren()
  • lcd_show(), lcd_colour()
  • write_log() to a file
  • cannon_move(), cannon_shoot(), cannon_light()

Ideas to start from

easy

Fridge raider

light sensorbrighter thanlog filebuzzer

The light sensor sits inside the fridge. Every time the door opens the light changes. Log the time of every raid.

easy

Reverse parking sensor

rangercloser thanbeepLCD

Beeps get faster as the object gets closer. Solid tone under 10 cm. Show the distance on the screen.

easy

Classroom thermometer

temperaturehotter thanLCD colour

Blue when cold, green when comfortable, red when hot. Log a reading every minute (hint: %).

medium

Door counter

rangerstrikescount in totalLCD

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.

medium

Two-player quick-draw

keyboardclockthe same asLEDcannon

Random wait, then the green LED lights. First player to type their letter wins. The loser gets a rocket.

hard

Desk guard with a password

rangerlightkeyboardstrikeseverything

Your alarm, but the arming countdown only starts after the right password, and the log records who armed it.

hard

Sentry that tracks

two rangerscloser thancannon_move

Left ranger sees something: turn left. Right ranger: turn right. Both: fire. Welcome to robotics.

Plan it before you code it

  1. Write one sentence: "When input is decision, do output."
  2. Copy the program that is closest to your idea (usually Mission 2 or 4).
  3. Delete what you don't need. Smaller programs are easier to fix.
  4. Change one thing, run it, check it. Then the next thing.
?check

Quiz

10 questions
Tteacher

Teacher notes

read before lesson 1
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.

terminal · one time per Pi
$ 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. If lsusb shows 0a81:0701 instead, that is the older model: change the usb.core.find line to those IDs and in cannon_send use cannon.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)
LessonMissionsStudents leave with
1Setup, Mission 1Working kit, blinking LEDs, the 5-byte message explained in their own words
2Mission 2Distance and light readings on screen, red LED tripwire, one tinker task done
3Mission 3Siren and LCD working, a custom message and colour
4Mission 4Full alarm, log file inspected, PIN discussion (plaintext secrets, brute force)
5Mission 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.txt plus a one-paragraph explanation of strikes.
  • Cybersecurity links: plaintext PIN in source, the wrong-PIN log as an attack record, getpass versus input (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.