Python Level-1 with Virtual Robotics - Mission 9: Line Following

Mission 9 Lesson Plan

Line Following

Students use sensor inputs to program the 'bot to follow a line course, building toward a PID controller that continuously calculates and corrects for error.

⏰ 3-5 hours 🎯 Grades 9-12+ πŸ’» CodeSpace πŸ€– Virtual CodeBot 🐍 Python
View Lesson Outline
πŸ“‹

Overview

In this mission, students move from basic line sensing to building a full PID controller that keeps CodeBot precisely on a line course. They use the Debugger and REPL to inspect global and local variables in real time, learn to define and use dictionaries with the get() method to avoid KeyErrors, and combine these skills to define a PID controller function that continuously calculates an error value. Students also write a function to collect statistics on that error, tuning constants until CodeBot can complete a complex path in under five minutes.

🎯 Mission Goal: Students use sensor inputs to program the 'bot to follow a line course.

🎯

Learning Targets

  • I can use the Debugger to track global and local variables.
  • I can test code using REPL.
  • I can define and use a dictionary.
  • I can avoid KeyErrors by using get().
  • I can define a function for a PID controller that continuously calculates the error value.
  • I can define a function to collect stats on the error values.
  • I can write code that makes the 'bot follow a complex path in under five minutes.
πŸ’‘

Key Concepts

  • The REPL is a way to experiment with code.
  • A tuple is a read-only list and is defined with parentheses instead of square brackets.
  • A dictionary allows you to look up a value using a key, like a label.
  • A default value can be returned if a key is not in the dictionary to avoid KeyError.
  • A control loop mechanism that employs feedback by continuously calculating the error value is called a PID controller.
βœ…

Assessment Opportunities

  • Quiz after Objective 2
  • Quiz after Objective 4
  • Quiz after Objective 6
  • Quiz after Objective 8
  • Objective 5 Line Sensor Chart (in assignment)
  • Code Tracing Chart as a debugging tool
  • Give students printed code from an objective and have them explain each line
  • Give extra practice with dictionaries
  • Compare and contrast global / local variables
  • Submit the line_scanner.py program
  • Submit the bang_bang.py program
  • Submit final line_follower.py program
  • Level-1 Mission 9 Review Kahoot!
β˜‘οΈ

Success Criteria

  • Use previous knowledge of the motors and line sensing to make CodeBot follow a path.
  • Use the Debugger and REPL to track variables and test code.
  • Define and use a dictionary without errors.
  • Define functions that create a PID controller.
  • CodeBot follows a complex path without veering off course.
  • CodeBot stays on the white board for the entire course.
  • CodeBot finishes the course within the time limit.
🧰

Classroom Materials

  • β–ΈComputer or Chromebook with internet access
🌍

Real-World Applications

πŸš—Staying on the path is the staple of self-driving cars, autonomous flying drones and other computing systems that navigate on their own.
🏁Line followers are a staple of robotics competitions, like races or mazes.
πŸ“¦Robots zip through warehouse distribution centers following lines.
πŸŽ“The coding skills learned in this Mission can be used in industrial and commercial robotics applications. They are also useful for school and club robotics competitions.
πŸš€

Extensions & Cross-Curricular

ExtensionHave a competition to see who's 'bot can reach the finish line the quickest.
ExtensionAdd sound to the moving 'bot. Vary the pitch according to speed or turning angle.
ExtensionSet user LEDs to indicate the speed of the 'bot.
ExtensionSet up a track and try the code on a physical CodeBot.
Lang ArtsHave students compare and contrast how the line sensors are used in Mission 8 and Mission 9. What are the similarities and differences?
ScienceHave a lesson on PID controllers.
MathThe equation for PID uses an integral and derivative. If your students are in calculus, go over the math.
MathThe mission uses statistics to inform the speed and turning ratio of the 'bot. Go over the math involved.
MathThe PID controller uses proportions and ratio to affect the speed of each wheel. Discuss how it relates to the code.
πŸ”€

Vocabulary

β–Ύ
Global variables:Variables defined outside a function. They are available throughout the entire program. If a global variable is changed inside a function, it must be declared in the function with "global".
Local variables:Variables created inside functions; they only exist while the function is running and can only be used inside the function.
REPL:Read Evaluate Print Loop - the command line that lets you type Python statements directly and observe what happens.
List comprehension:A shortcut for appending items to a list using a for loop inside the square brackets.
Tuple:An immutable sequence of items that you access with an index. It is similar to a list, but the items in the tuple are read-only. Use parentheses to define a tuple instead of square brackets.
None:"None" means no value, or null. It is a special object with type "nonetype".
Dictionary:A container that holds keys and values. It supports fast lookup of a value based on a given key. Dictionaries are defined with curly braces {}.
KeyError:Result when a key is given that is not in a dictionary.
get() method:A dictionary method that returns a default value instead of raising a KeyError when a key is not found.
PID controller:A control loop mechanism employing feedback that is widely used in industrial control systems by continuously calculating the error value.
🐍

New Python Code

β–Ύ
even_numbers = [x*2 for x in range(5)] sensors = [ls.read(i)>2000 for i in range(5)] List comprehension (a shortcut for populating a list).
vals = ls.check(2000) Function that reads all line sensors and compares the reading to a threshold, then returns a Boolean list.
if vals != prev_vals: != is the "not equals" operator.
elif vals[1] or vals[2] or vals[3]: Using a logical operator in a compound condition.
ls_err = { (0,0,1,0,0) : 0, (0,1,1,1,0) : 0, } Define a dictionary with a key and value. The syntax is key : value. This example uses a tuple as the key and an integer as the value.
err = ls_err[vals] Look up a value from a dictionary using a key (vals).
err = ls_err.get(vals, err) Using the get() method to avoid a KeyError.
def apply_control(err): Kp = 0.1 steering = err * Kp drive(SPEED, steering) PID controller - initial function, before adding in stats.
πŸ“

Standards

β–Ύ

CSTA Standards - Grades 9-10

3A-CS-03 3A-DA-10 3A-DA-12 3A-AP-13 3A-AP-14 3A-AP-15 3A-AP-16 3A-AP-17 3A-AP-18 3A-AP-19 3A-AP-21 3A-AP-22 3A-AP-23 3A-AP-26

CSTA Standards - Grades 11-12

3B-CS-02 3B-DA-05 3B-AP-10 3B-AP-14 3B-AP-15 3B-AP-16 3B-AP-17 3B-AP-20 3B-AP-21 3B-AP-22 3B-AP-23

Certiport IT Specialist: Python Standards

1.1 1.2 1.3 1.4 2.1 2.2 4.1 4.2 5.1

PCEP: Certified Entry-Level Python Programmer

1.1 1.2 1.3 1.4 1.5 2.1 2.2 3.1 3.2 3.3 4.1 4.2 4.3
πŸ“
Preparing for the Lesson
  • When using the Debugger, expand the list for Globals and Locals by clicking on the > to see them. You can also expand the window panel.
  • You can use the Code Tracing Chart and have the class go through some code together - Obj 1 and/or Obj 4 are good choices.
  • A chart for Objective 5 Line Sensor Readings is included as part of the assignment.
  • Some new programming concepts are used in the later objectives - dictionaries, and global and local variables. Students may need extra help and/or practice with these.

πŸ§‘β€πŸ«
Teacher Notes
  • Objective 3 still works on Obj 4 without making the changes, but this is a good place for experimenting. Have students try making the speed faster when a line is detected (last elif branch) and see what happens.
  • For the final objective, students need to tweak the speed and/or other constants. Encourage students to change one variable at a time and keep track of the changes so they can return to the previous value if needed - small changes can make a big difference.
πŸ—ΊοΈ

Lesson Outline

πŸ—£οΈWarm-up / Hook

Ask students where they've seen a machine or vehicle "follow a path" on its own - self-driving cars, warehouse robots, robotic vacuums, competition robots racing a track. Have a few students guess how a robot might sense where the line is and decide which way to turn. Connect this to the mission: CodeBot will use its line sensors, a dictionary lookup, and eventually a PID controller to stay on a line course.

1️⃣Objectives 1-2: Debugger, REPL and List Comprehension
  • Introduce the Debugger to track global and local variables, and use the REPL to experiment with code directly.
  • Introduce list comprehension as a shortcut for building a list, and use it to check all line sensors against a threshold at once.
  • Administer the Quiz after Objective 2.
  • Have students submit their line_scanner.py program.
Teaching tip:Expand the Globals and Locals lists in the Debugger panel by clicking the > arrow, and expand the window panel so students can see both at once.
2️⃣Objectives 3-4: Bang-Bang Control
  • Use ls.check(2000) to return a Boolean list from all line sensors, and compare readings with != to detect a change in state.
  • Combine logical operators in a compound condition (or) to react to multiple sensors at once.
  • Administer the Quiz after Objective 4.
  • Have students submit their bang_bang.py program.
Teaching tip:Objective 3 still works on Obj 4 without changes, but it's a good place to experiment. Have students try making the speed faster when a line is detected (the last elif branch) and see what happens.
3️⃣Objectives 5-6: Dictionaries and get()
  • Introduce tuples as read-only lists, and use one as a dictionary key: ls_err = {(0,0,1,0,0): 0, ...}.
  • Look up an error value from the dictionary with ls_err[vals], then use get() instead to return a default value and avoid a KeyError.
  • Have students complete the Objective 5 Line Sensor Chart in the assignment.
  • Administer the Quiz after Objective 6.
Teaching tip:Give students extra practice with dictionaries here, and take time to compare and contrast global and local variables before moving on.
4️⃣Objectives 7-8: Building the PID Controller
  • Define apply_control(err), a PID controller function that continuously calculates the error value and steers the 'bot.
  • Define a function to collect stats on the error values, then tune constants like speed and turning ratio one at a time.
  • Administer the Quiz after Objective 8.
  • Have students submit their final line_follower.py program, aiming to complete the course in under five minutes.
Teaching tip:Encourage students to change one constant at a time and keep track of each change so they can return to a previous value if needed - small changes can make a big difference.
πŸŽ‰Wrap-up / Review

Close with the Level-1 Mission 9 Review Kahoot! to reinforce the Debugger, REPL, dictionaries, get(), and PID controllers before wrapping up the unit.