SPIKE™ Prime with Python

Cart Control

Students will explore the distance sensor to control movements.

45 min
Beginner
Years 7-9 OR Key Stage 3

Questions to investigate

• How can a distance sensor be used to provide information for decisions?
• How can sensors be used for more precise moves?

Prepare

• Ensure SPIKE Prime hubs are charged, especially if connecting through Bluetooth.

Engage

(Whole Class, 5 minutes)

Engage students in thinking about ways we use automated machines. Prompt students to think about how these machines use sensors to keep from bumping into objects. Consider showing images and videos of different packing or shipping machines as examples. You might also prompt students to research and find their own examples.

Discuss with students how they see the automated machines moving around successfully.

Explore

(Small Groups, 20 minutes)

Students will build a deliver cart model to investigate different ways to move with the distance sensor.

Direct students to the BUILD section in the SPIKE App. Here students can access the building instructions for the Delivery Cart model. Ask students to build the model. The building instructions are also available at https://education.lego.com/en-us/support/spike-prime/building-instructions.

Direct students to open a new project in the Python programming canvas. Ask students to erase any code that is already in the programming area. Students should connect their hub.

Cart Under Control

Students will investigate how to use the distance sensor.

Ask students to review this program. Discuss with them if there are any bugs. When they realize there are not, ask them why this program is not going to work well. Students should realize that the motors will continue to run forever and eventually run into something.

import motor_pair
import runloop
from hub import port

async def main():
    # Pair motors on port A and B
    motor_pair.pair(motor_pair.PAIR_1, port.A, port.B)

    # Move straight at a specific velocity
    motor_pair.move(motor_pair.PAIR_1, 0, velocity=500)

runloop.run(main())

Prompt students to think about ways to keep the cart from bumping into an object. Students may think about including a stop in the program or adding a force sensor to the cart based on previous experiences. Tell students they will be using a different sensor.

Ask students to locate the distance sensor they built at the bottom of their cart. Provide students with this sample code to move the cart using the distance sensor. Students will need to type this program into the programming canvas.

Ask students to go through each line of code with their partners. Determine what the program is intended to do.

Ask students to run the program.

import runloop
import motor_pair
import distance_sensor
from hub import port

def distance_sensor_greater_than():
    # return if the distance sensor is greater than 150 mm
    distance = distance_sensor.distance(port.B)
    return distance == -1 or distance > 150  
  
def distance_sensor_less_than():
    #return if the distance sensor is less than 100 mm  
    distance = distance_sensor.distance(port.B)
    return distance < 100 and distance > -1

async def main():
    # pair motors
    motor_pair.pair(motor_pair.PAIR_1, port.E, port.A)
    
    # wait until the distance sensor reads more than 150 mm
    await runloop.until(distance_sensor_greater_than)    # turn on motor pair
    motor_pair.move(motor_pair.PAIR_1, 0, velocity=500)

    # wait until the distance sensor reads less than 50 mm
    await runloop.until(distance_sensor_less_than)

    # stop motor
    motor_pair.stop(motor_pair.PAIR_1)

runloop.run(main())

If students struggle to have the program work, give them a hint. Students will need to hold an object such as a book or a hand in front of the distance sensor when they start the program. Once the program is running take the object away, the cart should start moving. Place the object back in front of the sensor and it should stop. Make sure the object is farther away than 100 mm. Ask students to try the program multiple times with the delivery cart at different distances away from the object.

Allow the students to explore the program varying the starting distance from the object and re-running the program several times.

Note: The distance to start the motors does not have to be equal to the distance to stop the motors.

Explain

(Whole Group, 5 minutes)

Review the program together as a group.

Ask students additional questions like:
• What are the lines await runloop.until(distance_sensor_greater_than) and await runloop.until(distance_sensor_less_than) telling the cart to do
• Why was an object needed to make the program work?
• What happens when you start the cart further back from the object?
• How does the distance sensor work?

Explain to students that the distance sensor on the cart is an ultrasonic sensor. Have students look at the top left area of the programming canvas near where they connect their hub. Here they should see live data coming in from the cart. All hardware attached to the cart, motors and sensors, will provide live data. This live data is in cm, but students should know that the sensor outputs in mm.

Ask students to look at the distance sensor and then move their hands close to it, then further away. The number should change, increasing as the hand moves further away. Describe how the sensor works by sending a sonic pulse from one circle or “eye” which will bounce off any objects in front of the sensor and return to the other circle or “eye”. The sensor uses the time it takes that pulse to return to “measure” the distance to the object. The sensor uses a mathematical formula to change the time into a distance measurement.

Elaborate

(Small Groups, 10 minutes)

Students may have noticed that the rear wheels on the cart can keep the cart from moving in a straight line. When running the program above, students may have seen the cart turn to one side unless the rear wheels are straight. Consider demonstrating for students.

Ask students why a turning cart could be an issue for the distance sensor when it is detecting the distance to an object using an ultrasonic pulse. Discuss ideas with students about how to keep the cart moving straight.

Students should identify that because the rear wheels are attached to a motor, a piece of code can be added to help the cart stay straight. Students may also think to change the build to fix the motor in place. Consider discussing how that could limit the movement of the cart and re-focus students on the code instead.

Provide students with this sample code to set the back motor and wheels straight. Students should purposefully move the large motor with rear wheels to ensure it is not straight. Ask students to run the program.

import motor_pair
import runloop
import distance_sensor
import motor
from hub import port

def distance_sensor_closer_than():
  #return if the distance sensor is less than 150 mm  
    distance = distance_sensor.distance(port.B)
    return distance < 150 and distance > -1

async def main():
    # Pair motors on port A and B
    motor_pair.pair(motor_pair.PAIR_1, port.E, port.A)

    # Move the rear motor to the 0 degree position to make the cart move straight
     await motor.run_to_absolute_position(port.C, 0, 250)

    # start motor pair moving
    motor_pair.move(motor_pair.PAIR_1, 0, velocity=200)
    
    # wait until the distance sensor is clower than 150 mm
    await runloop.until(distance_sensor_closer_than)

    # The cart will stop when the distance is less than 150 mm.
    motor_pair.stop(motor_pair.PAIR_1)

runloop.run(main())

Discuss the program with students and how ensuring the rear wheels being straight allows the sensor to work more effectively. When the sensor is perpendicular to an object, the sound waves bounce back more directly giving a good reading.

Debugging
Ask students to review the following program to consider how to address the error message received.

Debug Activity #1

import motor_pair
import runloop
import motor
from hub import port

def distance_sensor_closer_than():
    # return if the distance sensor is less than 150 mm  
    distance = distance_sensor.distance(port.B)
    return distance < 150 and distance > -1

async def main():
    # Pair motors on port A and B
    motor_pair.pair(motor_pair.PAIR_1, port.E, port.A)

    # Move the rear motor to the 0 degree position to make the cart move straight
     await motor.run_to_absolute_position(port.C, 0, 250)

    # start motor pair moving
    motor_pair.move(motor_pair.PAIR_1, 0, velocity=200)
    
    # wait until the distance sensor is clower than 150 mm
    await runloop.until(distance_sensor_closer_than)

    # The cart will stop when the distance is less than 150 mm.
    motor_pair.stop(motor_pair.PAIR_1)

runloop.run(main())


Traceback (most recent call last):
File "delivery cart new", line 25, in <module>
File "delivery cart new", line 20, in main
File "delivery cart new", line 6, in distance_sensor_closer_than
NameError: name 'distance_sensor' isn't defined

Discuss the error message with students. Students should recognize that the error refers to line 6. However, the error is actually in line 1. The issue is that a distance sensor is used in the program, but the distance sensor is not imported in line 1.

Debug Activity #2

import motor_pair
import runloop
import distance_sensor
import motor
from hub import port

def distance_sensor_closer_than():
    #return if the distance sensor is less than 150 mm
    distance = distance_sensor.distance(port.B)
    return distance < 150 and distance > -1  

async def main():
    # Pair motors on port A and B
    motor_pair.pair(motor_pair.PAIR_1, port.B, port.A)

    # Move the rear motor to the 0 degree position to make the cart move straight
    await motor.run_to_absolute_position(port.C, 0, 250 )

    # start motor pair moving
    motor_pair.move(motor_pair.PAIR_1, 0, velocity=200)
    
    # wait until the distance sensor is clower than 150 mm
    await runloop.until(distance_sensor_closer_than)

    # The cart will stop when the distance is less than 150 mm.
    motor_pair.stop(motor_pair.PAIR_1)

runloop.run(main())

Traceback (most recent call last):
File "delivery cart new", line 25, in <module>
File "delivery cart new", line 11, in main
OSError: [Errno 19] ENODEV

Discuss the error message with students. Students should recognize that the error is pointing to line11. The issue is that the MotorPair variable is not defined as a port that has a motor plugged in. Students should check the ports that the motors are plugged into and change the variable to set the correct ports.

Evaluate

(Group Exercise, 5 minutes)

Teacher Observation
Discuss the program with students. Ask students questions like:
• How did the distance sensor work to control your cart?
• How does the design of the rear wheel affect how the cart moves and potential the effectiveness of the sensor?
• What are some ways you could use the distance sensor?

Self-Assessment
Have students answer the following in their journals:
• What did you learn today about using the distance sensor to keep from bumping into objects?
• What characteristics of a good teammate did I display today?
• Ask students to rate themselves on a scale of 1-3, on their time management today.
• Ask students to rate themselves on a scale of 1-3, on their materials (parts) management today.

Teacher Support

Students will:
• Program the distance sensor.
• Explore movements with distance.
• Understand ultrasonic.

• SPIKE Prime sets ready for student use.
• Devices with the SPIKE App installed.
• Student journals

CSTA
2-CS-02 Design projects that combine hardware and software components to collect and exchange data.
2-AP-10 Use flowcharts and/or pseudocode to address complex problems as algorithms.
2-AP-13 Decompose problems and subproblems into parts to facilitate the design, implementation, and review of programs.
2-AP-16 Incorporate existing code, media, and libraries into original programs, and give attribution.
2-AP-17 Systematically test and refine programs using a range of test cases.
2-AP-19 Document programs in order to make them easier to follow, test, and debug.