Fly with Python - Mission 7: Multitasking

Mission 7 Lesson Plan

Multitasking

Mission 7 opens Unit 3 with one of the most powerful ideas in real-world programming: doing many things at the same time. Students learn the StateMachine task scheduler, a built-in API that calls non-blocking functions on a periodic schedule. They build TaskMaster, a program that blinks LEDs at different intervals, schedules a one-time speaker beep, and uses non-blocking sensor checks to react when an object is near. The mission lays the foundation for every multi-tasking program in the rest of Unit 3.

⏱ 45-60 min 🎯 Grades 6-12+ 💻 CodeSpace 🚁 CodeAIR 🐍 Python
View Lesson Outline
📋

Overview

Mission 7 kicks off Unit 3. Students learn how to escape sequential, blocking code by using a task scheduler. They create a StateMachine instance, schedule periodic tasks (like blinking LEDs at different intervals), schedule one-off delayed callbacks, and write non-blocking sensor checks so the drone can react to objects without freezing the rest of the program. The mission centers on one program, TaskMaster, and sets up the multitasking patterns used through the rest of Unit 3.

🎯 Mission Goal: Students will program a drone to perform multiple tasks at the same time without blocking program execution.

🎯

Learning Targets

  • I can create an instance of the StateMachine.
  • I can use the StateMachine module to schedule multiple tasks that run at the same time.
  • I can write non-blocking code for sounds and sensors.
  • I can have the drone respond without blocking when an object is near.
💡

Key Concepts

  • The task scheduler is like a super-efficient assistant for your code. It calls non-blocking functions periodically, at specified intervals. The periodic rate is in seconds.
  • When scheduling a task, you don't call the function. You just give the name as an argument.
  • Enabling debug will allow StateMachine to print to the console.
  • Some blocking functions have options to make them non-blocking.

Assessment Opportunities

  • Quiz after Objective 2
  • Quiz after Objective 4
  • Complete the program TaskMaster
  • Mission 7 Assignment
  • Mission 7 Review Questions
☑️

Success Criteria

  • Use the task scheduler to blink an LED
  • Use the task scheduler to blink two LEDs at different intervals
  • Schedule a function to run one time
  • Implement a non-blocking sensor check
  • Have the drone respond when an object is near
🧰

Classroom Materials

  • Laptop/computer with Chrome browser
  • CodeAIR drone and USB cable
🌍

Real-World Applications

⏱️Task schedulers are at the heart of every modern operating system. The same idea students learn here - running multiple tasks at controlled intervals - is how Windows, macOS, and Linux juggle hundreds of programs at once.
🚦Embedded systems like traffic lights, smart thermostats, and medical devices all use cooperative multitasking - non-blocking functions that share the CPU so the system stays responsive.
🎮Video game engines use a "game loop" that's conceptually identical to sm.run_tasks() - checking input, updating physics, and rendering graphics on each tick.
🤖Autonomous robots and self-driving cars use real-time schedulers so that critical safety checks (like obstacle detection) never get blocked by slower tasks (like logging or mapping).
🚀

Extensions & Cross-Curricular

ExtensionSchedule a unique light show using the pixel LEDs, the blue LEDs, and the speaker.
ExtensionSchedule a task to monitor battery voltage using the safety module.
ExtensionSchedule a task that changes the LED blink pattern based on a sensor reading. If an object is in front, turn a specific color. If the object is above, another color, and if below, use a different color.
ExtensionCombine the utility module's select_index with the scheduler to launch different sets of tasks.
MathThe scheduler keeps track of when to run tasks. Do the math yourself! Start with the first two LEDs blinking. What is the timing if you were to turn them on sequentially?
Lang ArtsSummarize the drawbacks of blocking functions when working with a drone, and how this problem can be solved.
🔤

Vocabulary

Sequentially -Running the code one statement at a time, in order.
Task Scheduling -The process of organizing and executing tasks at specific times or in a specific order.
Scheduler -An API that lets you run non-blocking functions periodically, at specified intervals.
Gridlock -A situation where no progress can be made, like a stalemate or logjam.
🐍

New Python Code

from state_machine import StateMachineImport the StateMachine object.
sm = StateMachine()Create a StateMachine instance.
sm.enable_debug(True)Enable debugging so the StateMachine can print to the console.
sm.add_task(callback, interval)
sm.add_task(toggle_led9_task, 0.5)
Schedule a task - use the name of the function only!
sm.run_tasks()Check for scheduled tasks and run them.
speaker.beep(440, 0)Non-blocking beep, using 0 as the duration.
sm.schedule(callback, delay)
sm.schedule(speaker.off, 2.0)
A scheduler function that runs a function just once after a specific delay - use the name of the function only.
data = get_data(RANGERS, wait=False)Optional parameter changes get_data to a quick-check mode for a non-blocking function; returns None if no new data.
if data is not None:
    fwd, up, down = data
If new data is found, unpack the tuple into separate variables for easier use.
📐

Standards

CSTA Standards - Grades 6-8

2-CS-02 2-AP-12 2-AP-13 2-AP-14 2-AP-17

CSTA Standards - Grades 9-10

3A-CS-03 3A-AP-16 3A-AP-17 3A-AP-18

CSTA Standards - Grades 11-12

3B-CS-02 3B-AP-14 3B-AP-15 3B-AP-16 3B-AP-22
📝
Preparing for the Lesson
  • This mission is short (45-60 minutes) and stays mostly on-the-ground. No flight space is required for the core objectives.
  • Review the StateMachine task scheduler concepts before class - students will reuse this pattern in every Unit 3 mission.
  • Have CodeAIR drones charged and connected to laptops via USB.
  • Be ready to reinforce the difference between calling a function (my_func()) and passing a function reference (my_func) - this is the most common student mistake in this mission.

🧑‍🏫
Teacher Notes
  • This is a fairly straight-forward and relatively short lesson. It uses concepts from earlier missions, like using the speaker, blinking LEDs, and reading the ranger sensors. It sets the tone for future missions, so don't go too fast and make sure students are clear on the concepts and code.
  • Review questions can be used as a class review, made into a Kahoot!, or used to create an exam in your learning management system.
  • Extensions and cross-curricular projects are included to enhance the concepts in the mission. You can use the extensions to extend students' programming experience. A remix is planned after Mission 10.
🗺️

Lesson Outline

🗣️Warm-up / Hook

Students access prior knowledge by answering questions in the pre-mission section of the assignment doc.

Connect multitasking to real-world experiences through a brief discussion.

  • Ask: "How does your phone play music while you're texting? How does a video game render graphics, check controller input, and update physics all at once?"
  • Ask: "In Unit 2, we used fly.steady() to make the drone hover. What was happening to the rest of our code while it ran?" - bring out the gridlock problem.
Teaching tip: Use the analogy of a chef in a kitchen - a good chef puts water on to boil and chops vegetables while the water heats up. Bad chef: stand and watch the water until it boils. The scheduler is the good chef.
📖Introduce the Mission

Front-load the key new programming concepts before students start coding.

  • Introduce the StateMachine task scheduler - explain that it calls non-blocking functions periodically at intervals you set.
  • Demonstrate the difference between calling a function (my_func()) and passing a function as an argument (my_func) - this is critical for understanding sm.add_task().
  • Preview the non-blocking versions of familiar functions: speaker.beep(440, 0) for continuous tone, get_data(RANGERS, wait=False) for instant sensor read.
  • Set expectations: this is a 45-60 minute mission focused on one program, TaskMaster.
Teaching tip: Have students enable debug (sm.enable_debug(True)) early - it gives helpful console feedback as tasks run.
💻Coding Time

Students build the TaskMaster program, layering in scheduled tasks one at a time. As they work through the objectives, they should take notes and answer questions in their assignment doc.

  1. Schedule a single task - create a StateMachine, define a callback function that toggles an LED, and use sm.add_task() with an interval (Objectives 1-2; quiz after Objective 2).
  2. Schedule multiple tasks at different intervals - add a second LED toggling at a different rate to show parallel execution.
  3. One-time scheduling - use sm.schedule() to start a continuous beep with speaker.beep(440, 0), then schedule speaker.off to fire once after a delay (Objective 3).
  4. Non-blocking sensor check - use get_data(RANGERS, wait=False) inside a scheduled task; check for None before unpacking (Objective 4; quiz after Objective 4).
  5. React to a nearby object - combine the sensor check with an LED or sound response so the drone reacts the moment something gets close.
Teaching tip: The most common bug: students write sm.add_task(my_callback(), 0.5) with parentheses. The parentheses call the function immediately and pass None to add_task. The correct form is sm.add_task(my_callback, 0.5) - no parentheses.
Teaching tip: Make sure the main loop calls sm.run_tasks() repeatedly - without it, no task ever fires.
🧑‍🤝‍🧑Class Debrief

Bring the class together to consolidate multitasking ideas before moving to the next mission.

  • Ask: "What's the difference between a blocking and a non-blocking function? Give an example of each from this mission."
  • Ask: "Why don't we put parentheses on the function name when we add a task?"
  • Ask: "What real-world systems use task schedulers like this?" - connect to the Real-World Applications section.
Teaching tip: Have a few students share creative ideas for what they'd schedule next - this primes them for the upcoming mission's flight programs.
✏️Wrap-up & Review

Students answer the reflection question in the assignment doc and then submit.

Use the Mission 7 Review Questions through a preferred method - class discussion, Kahoot!, or LMS quiz.

Teaching tip: Mission 7 sets the tone for Unit 3 - every later mission relies on the StateMachine. If students are shaky, take an extra day before moving on.