SPIKE™ Prime with Python

Clean Indicator

Investigate the role of parameters in functions

45 min
Intermed.
Years 7-9 or Key Stage 3

Questions to investigate

• How can you use parameters within your functions?

Prepare

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

Engage

(Group Activity, 5 minutes)

Engage students in a discussion about creating graphs and ways to visualize information or data.

Ask students to stand up and be ready to vote by moving their feet. Pose a question to students that has several options that students can chose from. Students will indicate their answer by moving to the spot that is for their choice. This could be different corners in the room or any area you designate. Once students have made their vote, have them move together in a line to create a human bar graph.

Some example questions might be:
• What is your favorite ice cream flavor? (choose 4 flavors to list)
• What is your favorite book genre? (choose 3-4 to list)
• Which character are you most like? (choose a book or movie)

Explore

(Small Groups, 20 minutes)

Students will investigate using parameters in their functions.

Direct students to the BUILD section in the SPIKE App. Here students can access the building instructions for the Wind Indicator 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. 

Ask students to make a change to the model design. Ask students to change the stack of two yellow and two blue bricks to the side should be replaced with red on the bottom, then violet, then yellow, and green at the top. Students also need to add the color sensor in a place that will not obstruct the movement of the wind indicator.

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.  

Prompt students to think about how they can use a function for the indicator to show if the environment is clean (at the green level) or not (at the red level). The indicator should move to the appropriate color brick in the stack to show the level.

Ask students to write a pseudocode program for what the function could look like in the program. Pseudocode is writing in words what you want the program to do.

Sample Pseudocode:
• Define function
• Color sensor detect level of clean
• Move motor to the position based on color reading
• Print the color in the console

Discuss Pseudocode together.

Adding Parameters
Challenge students to add parameters to their program and “scan” their environment to indicate how clean it is.
Students will need a red, violet, yellow, and green 2x4 bricks from their set that will be scattered on the table as their environment to scan. Additionally, ask students to add the color sensor to their model by connecting it to the hub, but not attaching it to the model.
Ask students to modify their program to set parameters in their function for “scanning” the environment (extra bricks) using their color sensor. A parameter is like a variable but can only be used in a function. The parameter is data that is inputted from the user. It acts as a place holder for the new information that can be added when the function is called.
Sample Program:

from hub import port, button
import runloop
import motor
import color_sensor
import color

# define function for reporting the clean level
def report(height, color):
    runloop.run(motor.run_to_absolute_position(port.A, height, 500))
    print('Clean Level', color)

async def main():
    while True:
        await runloop.until(lambda: button.pressed(button.LEFT))
        #when sensing a color, the height is set
        if color_sensor.color(port.E) is color.RED:
            report(70, 'Red')
        elif color_sensor.color(port.E) is color.YELLOW:
            report(60, 'Yellow')
        elif color_sensor.color(port.E) is color.BLUE:
            report(50, 'Blue')
        elif color_sensor.color(port.E) is color.GREEN:
            report(25, 'Green')
        #if it doesn't sense a color, it moves to the 0 position
        else:
            await motor.run_to_absolute_position(port.A, 0, 1000)  
            print("No Reading")

runloop.run(main())

Allow students time to explore their program and take multiple readings of the environment.

Explain

(Whole Group, 5 minutes)

Discuss with students how the program worked.
Ask students questions like:
• Why did we add parameters to our function?
• What is the different between a parameter and a variable?
• How did using a function in your program make the program more efficient?

Elaborate

(Small Groups, 10 minutes)

Challenge students to try a new game where they are not detecting colors, but checking for bugs.

Show students each program and error message. Have students discuss what needs to change in each code to fix the bug or add the missing code. Consider making the changes as a class and ensuring the program runs correctly after each change.  

Debug Activity 1:

from hub import port, button
import runloop
import motor
import color_sensor
import color

# define function for reporting the clean level
def report(     ):
    runloop.run(motor.run_to_absolute_position(port.A, height, 500))
    print('Clean Level', color)

async def main():
    while True:
        await runloop.until(lambda: button.pressed(button.LEFT))
        #when sensing a color, the height is set
        if color_sensor.color(port.E) is color.RED:
            report(70, 'Red')
        elif color_sensor.color(port.E) is color.YELLOW:
            report(60, 'Yellow')
        elif color_sensor.color(port.E) is color.BLUE:
            report(50, 'Blue')
        elif color_sensor.color(port.E) is color.GREEN:
            report(25, 'Green')
        #if it doesn't sense a color, it moves to the 0 position
        else:
            await motor.run_to_absolute_position(port.A, 0, 1000)
            print("No Reading")

runloop.run(main())
    
Traceback (most recent call last):
File "Project 6", line 26, in <module>
File "Project 6", line 20, in main
TypeError: function takes 0 positional arguments but 2 were given

The error should draw attention to line 20, which does not seem to have an error. The actual error is occurring in line 5 where the function is defined. When defining the function, the parameters must be set so that when the function is called the value for the parameter can be provided. The value for the parameter provided now is not able to reference a parameter provided.

Debug Activity 2:

from hub import port, button
import runloop
import motor
import color_sensor
import color

# define function for reporting the clean level
def report(height, color):
    runloop.run(motor.run_to_absolute_position(port.A, height, 500))
    print('Clean Level', color)

async def main():
    while True:
        await runloop.until(lambda: button.pressed(button.LEFT))
        #when sensing a color, the height is set
        if color_sensor.color(port.E) is color.RED:
            report(70)
        elif color_sensor.color(port.E) is color.YELLOW:
            report(60, 'Yellow')
        elif color_sensor.color(port.E) is color.BLUE:
            report(50, 'Blue')
        elif color_sensor.color(port.E) is color.GREEN:
            report(25, 'Green')
        #if it doesn't sense a color, it moves to the 0 position
        else:
            await motor.run_to_absolute_position(port.A, 0, 1000)
            print("No Reading")

runloop.run(main())

Traceback (most recent call last):
File "Project 6", line 26, in <module>
File "Project 6", line 14, in main
TypeError: function takes 2 positional arguments but 1 were given

Note: the line reference in this error message will depend on which color you scan.
This error should indicate to students to check line 14. Students should recognize that the function is being called with a reference to the parameter. However, there should be two arguments but only
1 is given, which is causing the error. The 70 is the first, but it also needs a color

Ask students to consider other comment errors that might occur in this type of program and ideas for debugging when they do get errors.

Evaluate

(Group Exercise, 5 minutes)

Teacher Observation:
Discuss the program with students.
Ask students questions like:
• What type of errors should you watch for when programming with functions and parameters?
• What are ways that you can use parameters within your functions?

Self-Assessment:
Have students answer the following in their journals:
• What did you learn today about using parameters in functions?
• 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:
• Create functions that use parameters
• Investigate debugging functions and functions that use parameters

• 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.