Fly with Python - Mission 9: Attitude Control

Mission 9 Lesson Plan

Attitude Control

Students explore CodeAIR's accelerometer and gyroscope to build a feedback system, charting roll rate live, painting a flight data recorder chart, and using LEDs and motors to give the drone visual and haptic responses to tilt and spin.

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

Overview

Mission 9 takes students inside the accelerometer and gyroscope - the sensors at the heart of the CodeAIR's stability system. Students begin by exploring both sensors interactively in the REPL, then build a live chart of the drone's roll rate using the data pipe and paint a chart of the drone's movements using the flight data recorder. From there, they build DipDetector, a haptic feedback program that lights pixels in response to tilt, then Balance, a haptic system where the motors execute corrective push back. The mission wraps up with SpinCycle, mastering multi-axis control by combining sensor data to command individual corner motors.

🎯 Mission Goal: Students will build a feedback system for the drone that uses sensor data for visual feedback and haptic responses.

🎯

Learning Targets

  • I can explore the accelerometer and gyroscope interactively using REPL.
  • I can chart the drone's roll rate in real-time.
  • I can use the flight data recorder to paint a chart with the drone's physical movements.
  • I can build a dip detector that provides instant visual feedback with LEDs.
  • I can create a haptic balancing system where the motors execute corrective push back.
  • I can master multi-axis control by combining sensor data to command individual corner motors.
💡

Key Concepts

  • The CodeAIR uses an accelerometer and gyroscope to stay perfectly balanced.
  • The accelerometer measures the pull of gravity in three dimensions. This enables it to calculate its tilt angle in any direction.
  • The gyroscope constantly measures its rate of rotation. The three axes are roll, pitch and yaw.
  • You can visualize the drone's data using the data pipe and data panel. All sorts of data can be visualized in real time using pipe.chart() as the go-to for live-plotting data. The data can also be sent to the flight data recorder for later analysis.
  • The drone can use haptic feedback by turning on pixels and motors as a result of data from the sensors.

Assessment Opportunities

  • Quiz after Objective 4
  • Quiz after Objective 6
  • Complete the program AttitudeChart
  • Complete the program DipDetector
  • Complete the program Balance
  • Complete the program SpinCycle
  • Mission 9 Assignment
  • Mission 9 Review Questions
☑️

Success Criteria

  • Read the data from ACCEL to the console
  • Read the data from GYRO to the console
  • Schedule a task that uses sensor data from GYRO to display a live chart
  • Redirect the GYRO reading to the flight data recorder to capture untethered data
  • Have the drone react to a tilt by lighting pixels
  • Spin the motors as a reaction to a tilt
  • Give the drone four-corner control using a data structure
  • Give the drone stabilization from a spin
🌍

Real-World Applications

📱Gyroscopes are inside every smartphone, gaming controller, and VR headset - they detect tilt and rotation for orientation-based features like screen auto-rotate and motion controls.
🚁Real drones use the same gyro-driven feedback loop students build here. Without it, a quadcopter can't stay level - millisecond-by-millisecond corrections from the gyro keep it stable in the air.
📊Live data charting is how engineers monitor satellites, race cars, and industrial robots in real time - the same pipe.chart() pattern students learn here is used in professional telemetry systems.
🎮Haptic feedback - vibration in game controllers, taptic engines in phones, force-feedback steering wheels - uses the same sensor-driven actuator pattern students implement in DipDetector.
🚀

Extensions & Cross-Curricular

ExtensionModify the handle_attitude_feedback() function to play a different sound for a left tilt vs a right tilt.
ExtensionHave different thresholds for a slow tilt (different pixel color and motor power) and a faster tilt (different pixel color and motor power).
ExtensionMake the haptic feedback proportional. Adjust the motor power according to the data.
ExtensionAdd LEDs to Objective 8, indicating which way the drone is spinning, or which motors are powered.
ExtensionCombine the two haptic feedback systems into one system.
MathAnalyze a chart after tilting the drone. Can you calculate the rate of rotation?
ScienceThe drone has both an accelerometer and a gyroscope. Research both.
ScienceLaws of physics are discussed in this mission. Discuss Newton's Laws and how they apply to a drone.
ScienceHave a lesson on torque.
Lang ArtsWrite a paper that compares and contrasts the gyroscope and accelerometer.
🔤

Vocabulary

Attitude -The drone's orientation in 3D space.
Sensor Fusion -The process of combining sensor data so the resulting information has less uncertainty than sources used individually.
Accelerometer -A sensor that measures the force of gravity; used to calculate a device's exact angle relative to the ground.
Gyroscope -A sensor that measures the active rate of rotation around three axes.
Rolling -Tilting side to side.
Pitching -Tilting front to back.
Yaw -Turning left or right.
Data Panel -The mission control dashboard (in REPL).
Data Pipe -High-speed data link that feeds information directly from the drone to the data panel.
Haptic Feedback -Communication through the sense of touch.
Attitude Torque -Pitch and roll; generated by differential motor thrust; an imbalance of lift.
Reaction Torque -Yaw; like a kickback, every spinning propeller exerts an equal and opposite force on the drone's frame.
Data Structure -A specific way of organizing and managing data so it can be accessed efficiently; lists and tuples are examples.
Refactoring -The process of improving the design of your code.
🐍

New Python Code

get_data(ACCEL)Reads data from the accelerometer - pull of gravity.
get_data(GYRO)Reads data from the GYRO - active rotation around three axes.
pipe.chart()
pipe.chart("Roll Rate", roll_rate)
Function for live-plotting data. Two parameters: chart name and data.
data = get_data(GYRO, wait=False)Reads data from the GYRO, unblocked.
pipe.connect(rec)Redirect the pipe to send its data to the flight data recorder.
recorder.print_report()Print the file from the last flight.
LEFT_PIXELS = (TOP_FRONT_LEFT, TOP_REAR_LEFT)Group pixels into a tuple.
for i in LEFT_PIXELS:
    pixels.set(i, RED)
Set all pixels in the tuple LEFT_PIXELS to RED.
for motor in motors:
    set_param(motor, MOTOR_POWER)
Set all the motors in motors to MOTOR_POWER.
for pixel in pixels_to_light:
    pixels.set(pixel, RED)
Set all the pixels in pixels_to_light to RED.
finally:The block of code is guaranteed to run when the program stops.
ALL_MOTORS = (MOTOR_FR, MOTOR_FL, MOTOR_RR, MOTOR_RL)Group all motors into a tuple.
for motor in ALL_MOTORS:
    set_param(motor, 0)
Iterate over the ALL_MOTORS tuple to set all motor power to 0 (off).
📐

Standards

CSTA Standards - Grades 9-10

3A-CS-033A-DA-103A-DA-113A-DA-123A-CS-133A-CS-143A-AP-163A-AP-173A-AP-18

CSTA Standards - Grades 11-12

3B-DA-053B-DA-063B-DA-073B-AP-103B-AP-123B-AP-143B-AP-153B-AP-163B-AP-21

AI4K12 Standards - Grades 9-12

1-A-ii1-A-iii2-B-i
📝
Preparing for the Lesson
  • This mission stays mostly hands-on with the drone - no flight space needed. Students hold and tilt the drone to test the sensor feedback.
  • Charge CodeAIR drones and have USB cables ready - Objective 4 requires a brief untethered moment to capture flight recorder data.
  • Open the data panel in REPL ahead of class and demonstrate the "CLEAR DATA" button - students will need to clear data between runs to keep charts readable.
  • Review the difference between roll, pitch, and yaw - students often confuse these when reading gyro data.

🧑‍🏫
Teacher Notes
  • Objective 1 uses the accelerometer. Then Objectives 2-4 use the gyroscope before transitioning back to the accelerometer for the remainder of the objectives.
  • Objective 3: The data in the chart can be cleared by clicking "CLEAR DATA" at the bottom of the window before running code, so only the most recent data is displayed.
  • Objective 4 requires untethered movement and then reconnecting to see the chart from the flight recorder. Meeting the goals of the objective aren't just typing in the code, but also looking at the flight recorder data. The validator won't check this. You could ask students to include a screenshot of their table to make sure they don't skip this step.
  • Make sure to read the Hints, especially for Objectives 5-8.
  • Objectives 6-8 use the drone's motors for feedback. Students will not fly the drone. It may take a little time for the feedback loop to work. Give it some time, like 30 seconds or so.
  • 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 attitude sensing to real-world examples through a brief discussion.

  • Ask: "How does your phone know to rotate the screen when you tilt it? What sensor is doing that?"
  • Ask: "What would happen to a quadcopter if there was no sensor watching for tilt? Why does it need to constantly correct itself?"
Teaching tip: Have students stand up and try to balance on one foot. The constant micro-corrections their inner ear and muscles make are exactly what the accelerometer, gyroscope, and motors do for the drone.
📖Introduce the Mission

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

  • Introduce the accelerometer (measures the pull of gravity, calculates tilt angle) and the gyroscope (measures rate of rotation) and the three axes: roll, pitch, and yaw.
  • Demonstrate get_data(ACCEL) and get_data(GYRO) in REPL - show how each sensor returns different information about the drone's orientation.
  • Preview pipe.chart() for live data visualization in the data panel.
  • Show how pipe.connect(rec) redirects pipe data to the flight recorder for capturing untethered runs.
  • Set expectations: this is a 45-60 minute mission with four programs - AttitudeChart, DipDetector, Balance, and SpinCycle.
Teaching tip: Show students the data panel before they start coding - clearing data between runs keeps charts readable.
💻Coding Time

Students build four programs that progressively use the accelerometer and gyroscope for visualization and feedback. As they work through the objectives, they should take notes and answer questions in their assignment doc.

  1. Explore ACCEL in REPL (Objective 1) - read get_data(ACCEL) interactively and see how the values change as the drone is tilted.
  2. AttitudeChart - explore GYRO and live charting (Objectives 2-4; quiz after Objective 4) - read get_data(GYRO) in REPL, schedule a task that feeds pipe.chart("Roll Rate", roll_rate) to plot live data, then redirect the pipe with pipe.connect(rec) to capture an untethered tilt on the flight recorder.
  3. DipDetector - visual feedback (Objective 5) - back to the accelerometer: light up the LEFT or RIGHT pixel group when the tilt angle exceeds a threshold.
  4. Balance - haptic push back (Objective 6; quiz after Objective 6) - spin the corner motors as a corrective, tactile response to tilt.
  5. SpinCycle - multi-axis control (Objectives 7-8) - group pixels and motors into tuples (e.g., LEFT_PIXELS, ALL_MOTORS) to combine sensor data for four-corner control, then add stabilization from a spin.
Teaching tip: For Objective 4, students need to take the drone untethered, tilt it, and reconnect. Have them log a screenshot of the recorded chart since the validator can't check this step.
Teaching tip: In Objectives 6-8, students will hold the drone - keep motor power low to prevent take-off, and use a finally: block to ensure motors always shut off when the program ends. It may take about 30 seconds for the feedback loop to settle - give it time before increasing power.
🧑‍🤝‍🧑Class Debrief

Bring the class together to consolidate the feedback-loop and data-structure ideas.

  • Ask: "What's the difference between what the accelerometer measures and what the gyroscope measures? Why does the drone need both?"
  • Ask: "How did using a tuple of motors change your code? Why is that better than four separate set_param() calls?"
  • Ask: "What other devices could you build using the same sensor-to-reaction feedback loop?" - connect to haptic feedback in real-world devices.
Teaching tip: Have students share their charts from Objective 4 - comparing different tilt speeds is a great visual reinforcement of "rate."
✏️Wrap-up & Review

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

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

Teaching tip: Mission 10 will combine the sensor feedback ideas with full autonomous flight - set the stage by previewing how all of Unit 3's tools will come together.