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

Step 1: Print Distance

Open a new Python project named Parking Beeper.

Start with this short code:

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:

CODE
from hub import port, sound

Add this inside the loop after the print:

EDIT VIEW · Gray = already there; dark = add or change
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:

EDIT VIEW · Gray = already there; dark = add or change
        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:

EDIT VIEW · Gray = already there; dark = add or change
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.

Extra setup idea: Use the Parking Wall setup from the Challenge Setups sheet.

Teacher Check

Show your teacher:

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.