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:
- motor to Port A
- force sensor to Port B
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
- A sensor function can return
TrueorFalse. runloop.until()waits until a function returnsTrue.- Press and release can be two different events.
Step 1: Test The Press
Open a new Python project named Force Button.
Start with this short 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:
import motor
Add this label:
force_port = port.B
motor_port = port.A
Add this line after the wait:
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:
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:
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:
- Level 1: press to start, release to stop
- Level 2: reverse the motor direction
- Level 3: change the speed so it is useful but safe
- Level 4: add a hub image while the motor is running
Teacher Check
Show your teacher:
- the press function
- the release function
- the motor starting and stopping from the sensor
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.