Fly with Python - Mission 8: Drone Director

Mission 8 Lesson Plan

Drone Director

Students combine the task scheduler with formal state handlers to fly precision flight profiles, using the flight data recorder, non-blocking flight commands, and event injection to direct CodeAIR like a film director directs a scene.

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

Overview

Mission 8 brings together the task scheduler from Mission 7 with the flight commands from Unit 2. Students build TaskSeq using state variables and the flight data recorder, then refactor it into FormalStates using state handler functions registered with the StateMachine. Along the way they learn non-blocking flight commands (fly.start_up(), fly.start_down()), how to log to and read from the on-board flight recorder, and how to inject sensor-data events into the state machine for precision altitude control.

🎯 Mission Goal: Students will program a drone, using the scheduler and state handlers, to fly intelligently while simultaneously managing other operations.

🎯

Learning Targets

  • I can apply the scheduler to manage sequential flight.
  • I can record to the flight data recorder and print the data to the console.
  • I can implement non-blocking flight commands within state handlers.
  • I can write functions for state handlers for formal flight states.
  • I can integrate fly.steady() into the flight profile.
  • I can design and execute timed flight profiles that combine precise altitude control with concurrent background tasks.
💡

Key Concepts

  • Flight tasks and the scheduler were introduced separately. This mission combines them for powerful drone control.
  • The drone has a flight data recorder on board that acts like its "black box." It saves important information that prints to the console. Data from the previous run is printed, so the code must be run a second time to see results of the first run.
  • Formal states are more efficient than state variables. Formal states use state handler functions that each perform their own tasks. State handlers must be added to the state machine.
  • Sensor data can be scheduled as a task and run simultaneously with a flight profile, enabling the drone to use data for precise control.

Assessment Opportunities

  • Quiz after Objective 3
  • Quiz after Objective 5
  • Complete the programs TaskSeq and FormalStates
  • Mission 8 Assignment
  • Mission 8 Review Questions
☑️

Success Criteria

  • Use the task scheduler for flight tasks
  • Use the flight recorder to save and print data
  • End a flight task by one-time scheduling a state transition callback
  • Schedule flight tasks using state handlers
  • Schedule the non-blocking fly.steady() to run every 0.1 seconds
  • Inject an event handler for sensor data updated
🧰

Classroom Materials

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

Real-World Applications

📼Real aircraft carry flight data recorders ("black boxes") that log altitude, speed, and control inputs - investigators use them to reconstruct what happened during incidents. Students experience the same workflow on a small scale.
🎬State machines are used everywhere: video game enemy AI, traffic light controllers, vending machines, and washing machines all use the same formal-state pattern students learn here.
🚀Spacecraft and autonomous vehicles use event-driven state machines so that sensor updates can interrupt and redirect the current activity - the same pattern as the sensor-data event injection in this mission.
🧱"Separation of concerns" is one of the most important principles in professional software engineering - breaking a complex program into focused modules that each do one thing well.
🚀

Extensions & Cross-Curricular

ExtensionAdd more states to the flight profile so the drone does more than fly up and back down. Start with it flying a precise distance forward before landing. Can you make the drone fly in a specific pattern?
ExtensionSchedule more LEDs to blink at different rates for a fun light show while the drone flies.
STEMThe mission uses "states" - both state variables and state handlers. Research other tech devices that use states. What are their states and what determines the change from one state to the next?
STEMThe mission uses several stand-alone functions that work together for precision flight control. This is an excellent example of abstraction. Discuss abstraction: what it is and how it is used in this program to hide underlying implementation details.
Lang ArtsWrite a technical report about formal states and how the task scheduler can be used to execute a precise flight pattern.
🔤

Vocabulary

State Variable - A variable that holds the name of the current state of a machine. The variable is updated to the next state once the current state is completed.
State Handler - A Python function that acts as a mini-director for one flight step. When it is its turn the code runs, and it reports back so the next state handler can start.
Instantiate - Create an instance, or object, of a class.
Flight Data Recorder - A log of flight information saved in a file on the drone, like an aircraft "black box."
Refactor - Rewrite working code to make it cleaner, more efficient, or easier to extend - without changing what it does.
Separation of Concerns - A design principle that breaks a program into distinct sections, each handling one specific concern or job.
Non-Blocking - A command that returns control to the program right away instead of pausing while it finishes. Non-blocking code lets the scheduler run other tasks at the same time.
Event - A signal injected into the StateMachine. Events have an event_type (a string) and event_data (any payload, like a sensor reading).
🐍

New Python Code

if state == 'begin':
    state = 'ascend'
    # more lines of code here
Use a state variable to control program flow. The state variable needs to be updated when a state changes.
state = 'begin'
while state != 'end':
    sm.run_tasks()
Run the scheduled tasks until the state is 'end' (not an infinite loop).
recorder.print_report()Displays the flight data recorder log on the console.
sm.enable_debug(True, recorder.log)
sm.enable_debug(True, rec.log)
Add the second parameter to log information to the flight data recorder.
with recorder as rec:Manage the recorder. This command automatically opens the recorder and remembers to close the file when done.
rec.log('Starting up!')
rec.log(state)
Logs a message to the flight data recorder. Logs current state to the flight data recorder.
def ascend():
    global state
    state = 'ascend'
Define a callback function that changes the state. This function can be scheduled to run after a delay without blocking.
fly.enable_flying(True)Command that unlocks CodeAIR's ability to respond to flying commands without halting other tasks. It takes a second to calibrate the sensors. Set to False to turn off the ability.
fly.start_up(0.2)Start the non-blocking function for upward movement at 0.2 m/s.
fly.start_down(0.2)Start the non-blocking function for downward movement at 0.2 m/s.
def begin(sm, event_type, event_data, st_time):State handler function with parameters, which are automatically passed by the state machine.
if event_type == 'enter':Block of code that runs only once when the state is first entered.
sm.next_state(ascend, 2.0)Directly command a transition by calling the next state handler.
sm.add_state(begin)Register each state handler function. This creates a clear definition of all possible states in your flight plan.
sm.start()Start the well-defined flight sequence.
while not finished:Use a Boolean variable (finished) to end the loop.
fly.steady()The function (no parameter) keeps the flight controller engaged and processing non-blocking commands.
elif event_type == 'sensor_data_updated':A new event handler that can pass sensor data to the event handler in the event_data argument.
📐

Standards

CSTA Standards — Grades 6–8

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

CSTA Standards — Grades 9–10

3A-CS-01 3A-CS-03 3A-AP-16 3A-AP-17 3A-AP-18 3A-IC-26

CSTA Standards — Grades 11–12

3B-AP-10 3B-AP-14 3B-AP-16 3B-AP-21 3B-AP-22
📝
Preparing for the Lesson
  • Reserve a clear flight space - this mission has students fly the drone for the first time in Unit 3.
  • Charge all CodeAIR drones fully. Have spare batteries ready.
  • Review the flight data recorder workflow - students will need to run their code twice to view recorded data, since the recorder prints data from the previous run.
  • Be ready to explain the deliberate "bugs" in Objectives 1-3 - they are intentional, and students will fix them when they refactor into formal state handlers in Objectives 4-6.

🧑‍🏫
Teacher Notes
  • Starting with Objective 2, students need to run the code and fly the drone. Then connect the drone again and run again, but this time instead of flying the drone they check the recorder log on the console panel. This is an important step! Meeting the goals of the objective aren't just typing in the code, but also looking at the flight recorder data. Don't let your students skip this!
  • Several objectives give code that meets the goals but won't fly the drone correctly. This is intentional. When a drone doesn't fly as expected, check the code thoroughly and check the flight recorder data. If everything is following the instructions, just move on. The "bug" will be fixed in the next objective.
  • A lot of code in Objectives 1-3 will be replaced with state handlers in Objectives 4-6.
  • 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 state machines and flight directors to real-world examples through a brief discussion.

  • Ask: "How does a film director coordinate a complex scene - actors, lighting, sound, camera - all at once? How is that different from one person trying to do it all sequentially?"
  • Ask: "In Mission 7 we scheduled tasks. What was missing if we wanted the drone to perform a sequence of flight steps in a particular order?"
Teaching tip: Frame the mission name "Drone Director" - the StateMachine is the director, and the state handlers are the actors who each know their role.
📖Introduce the Mission

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

  • Introduce the flight data recorder - explain that it records to a file and the data from the previous run prints when the program starts.
  • Demonstrate the state-variable approach (Objectives 1-3) - using a while loop with if branches.
  • Preview the formal-state approach (Objectives 4-6) - state handler functions registered with sm.add_state().
  • Introduce non-blocking flight commands: fly.start_up(), fly.start_down(), and fly.steady() with no parameter.
  • Set expectations: this is a 45-60 minute mission with two programs - TaskSeq and FormalStates.
Teaching tip: Some of the code in Objectives 1-3 has bugs intentionally. Students learn to use the flight recorder to investigate, then fix the bugs in 4-6.
💻Coding Time

Students build two programs that progress from a state-variable approach to a formal-state-handler architecture. As they work through the objectives, they should take notes and answer questions in their assignment doc.

  1. TaskSeq - state variables (Objectives 1-3; quiz after Objective 3): use a state variable in a while loop, log to the flight recorder with rec.log(), and end a flight task by one-time-scheduling a state-transition callback.
  2. Run twice to see recorder output - the recorder prints data from the previous run, so every objective requires a fly-then-check cycle. Don't skip the check.
  3. FormalStates - state handlers (Objectives 4-5; quiz after Objective 5): refactor TaskSeq into state handler functions (def begin(sm, event_type, event_data, st_time):), register each with sm.add_state(), and use sm.next_state() for transitions.
  4. Add non-blocking flight - schedule fly.steady() as a 0.1-second task so the flight controller stays engaged while other tasks run.
  5. Inject a sensor-data event (Objective 6) - extend the state handler to respond to 'sensor_data_updated' events for precision altitude control.
Teaching tip: Don't let students skip viewing the flight recorder data. Run, fly, reconnect, run again, check the console - that's the whole loop.
Teaching tip: When Objective 1-3 code doesn't fly correctly, that's expected. Verify the code matches the instructions, then move on. Objectives 4-6 fix the issues by refactoring into formal states.
🧑‍🤝‍🧑Class Debrief

Bring the class together to compare the two architectures and reinforce the design principles.

  • Ask: "What was the advantage of refactoring TaskSeq into FormalStates? What did formal state handlers make easier?"
  • Ask: "What is separation of concerns? How does using state handlers demonstrate it?"
  • Ask: "How did the flight data recorder help you debug?"
Teaching tip: Show students how to read the recorder output - log lines from the previous run are gold for diagnosing flight behavior.
✏️Wrap-up & Review

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

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

Teaching tip: The state-handler pattern from this mission is foundational for Missions 9 and 10 - make sure students can trace the flow before moving on.