STARLEAP / SPIKE PRIME PYTHON / 2026–27
Build 2026.09.22-090630-0400
On this page
Project 07: Parking Beeper
You need: a LEGO SPIKE Prime set and the SPIKE App Python editor.
Goal
Make a parking sensor that reads a distance number and beeps differently when an object is close or medium distance.
Build
Connect the distance sensor to Port B. Put a wall, bin, book, or your hand in front of it.
Using the code: gray lines are already in your program; dark lines are the edit. Keep the shown indentation. Replace a displayed main() definition as a whole, keeping imports and the final start call.
What You Will Learn
- A sensor reading can be stored in a variable.
- Distance is measured in millimeters.
if,elif, andelselet the program choose a reaction.-1means the distance sensor does not see anything in range.
Step 1: Print Distance
Open a new Python project named Parking Beeper.
Start with this short code:
from hub import port
import runloop
import distance_sensor
distance_port = port.B
async def main():
while True:
distance = distance_sensor.distance(distance_port)
print(distance)
await runloop.sleep_ms(500)
runloop.run(main())
Run the program and move your hand closer and farther away.
Observe: The number changes. Smaller means closer.
Step 2: Beep When Close
Change the first import:
from hub import port, sound
Add this inside the loop after the print:
async def main():
while True:
distance = distance_sensor.distance(distance_port)
print(distance)
if distance > -1 and distance < 100:
await sound.beep(800, 100, 100)
await runloop.sleep_ms(500)
Run the program.
Observe: The hub beeps when something is close.
Step 3: Add Medium Distance
Add an elif:
if distance > -1 and distance < 100:
await sound.beep(800, 100, 100)
elif distance > -1 and distance < 200:
await sound.beep(500, 100, 100)
await runloop.sleep_ms(500)
Run the program.
Observe: Close and medium distances sound different.
Step 4: Add Labels
Add print labels in each path:
async def main():
while True:
distance = distance_sensor.distance(distance_port)
print(distance)
if distance > -1 and distance < 100:
print("close")
await sound.beep(800, 100, 100)
elif distance > -1 and distance < 200:
print("medium")
await sound.beep(500, 100, 100)
else:
print("clear")
await runloop.sleep_ms(500)
Run the program.
Physical Challenge: Parking Sensor Test
Use a box or bin as a wall.
- Level 1: beep when closer than 10 cm
- Level 2: use a different beep when closer than 20 cm
- Level 3: tune the cutoffs so the warning feels useful
- Level 4: add a hub image for
close
Extra setup idea: Use the Parking Wall setup from the Challenge Setups sheet.
Teacher Check
Show your teacher:
- distance numbers changing
- the close cutoff
- the medium cutoff
- two different beep reactions
Before You Put The Kit Away
Save your program. Stop the program before moving wires or changing the build. Show the teacher your working behavior, point to one changed line, and explain what it controls. Keep your place for next time.