STARLEAP / SPIKE PRIME PYTHON / 2026–27

Build 2026.09.22-090630-0400

On this page

Project 05: Force Button Machine

You need: a LEGO SPIKE Prime set and the SPIKE App Python editor.

Goal

Use a force sensor to start and stop a motor.

Build

Connect:

Attach the motor to any small machine: spinner, fan, pointer, arm, gate, or wheel.

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: Test The Press

Open a new Python project named Force Button.

Start with this short code:

CODE
from hub import port
import runloop
import force_sensor

force_port = port.B

def is_pressed():
    return force_sensor.pressed(force_port)

async def main():
    await runloop.until(is_pressed)
    print("pressed")

runloop.run(main())

Run the program, then press the force sensor.

Observe: The console prints pressed.

Step 2: Start The Motor

Add this import:

CODE
import motor

Add this label:

EDIT VIEW · Gray = already there; dark = add or change
force_port = port.B
motor_port = port.A

Add this line after the wait:

EDIT VIEW · Gray = already there; dark = add or change
async def main():
    await runloop.until(is_pressed)
    await motor.run_for_time(motor_port, 500, 300)
    print("pressed")

Run the program.

Observe: Pressing the force sensor runs the motor for half a second, then stops it. Run the program again for another press.

Step 3: Stop On Release

Add this function above main(), with its def line at the left edge:

CODE
def is_released():
    return not force_sensor.pressed(force_port)

Replace the timed motor line with these lines. Keep the wait for is_pressed above them:

EDIT VIEW · Gray = already there; dark = add or change
async def main():
    await runloop.until(is_pressed)
    motor.run(motor_port, 300)
    await runloop.until(is_released)
    motor.stop(motor_port)
    print("pressed")

Run the program.

Observe: Press and hold to run. Release to stop. This version handles one press; run the program again for the next trial.

Physical Challenge

Make a press-controlled machine:

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.