Teacher Resources - Fly with Python Mission 12

Mission 12 Lesson Plan

Line Patrol

Students turn raw camera pixels into machine vision, teaching CodeAIR to see a black line by its brightness and follow it on its own, then land when the line ends.

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

Overview

Mission 12 is CodeAIR's first step into machine vision. Students start by reading every pixel in a camera frame and building a new image from it, first a negative, then a greyscale version, then a black and white image made with a threshold.

From there they scan just a few rows of the image for speed, find the center of the dark line in each row, and turn those centers into a heading angle and a position error. In the final objective they close the loop: the error feeds the flight controller using proportional control, and CodeAIR follows a black line on its own and lands gracefully when it is done.

🎯 Mission Goal: Students will program a drone to follow a black line using machine vision.

🎯

Learning Targets

  • I can look at a camera frame and read every pixel.
  • I can reduce a color image to greyscale.
  • I can reduce a greyscale image to black & white.
  • I can set a threshold to distinguish a black line from a background.
  • I can find the center of a line by scanning a few rows for speed.
  • I can turn centers into a heading and a centering error.
  • I can close the loop by feeding the error to the flight controller and following the line.
💡

Key Concepts

  • The drone's camera frame is a bitmap of all the pixels used to create the image. The image size is 160x120 pixels. Each pixel packs red, green and blue into 16 bits in a format called RGB565.
  • The camera frame is read-only, but the data can be used to build a new image. Use nested loops to access every pixel.
  • Hexadecimal numbers are base 16. Using hex is a compact way to write bit patterns, since each digit represents 4 bits.
  • Bitwise operators work with individual bits. They can be used when working with images to flip bits and shift bits either left or right.
  • The continue command can be used to return to the top of a loop, skipping instructions below the command.
✅

Assessment Opportunities

  • Quiz after Objective 3
  • Quiz after Objective 6
  • Complete the program LinePatrol_Vision
  • Complete the program LinePatrol_Scan
  • Complete the program LinePatrol_Fly
  • Mission 12 Assignment
  • Mission 12 Review Questions
☑️

Success Criteria

  • Snap a photo and display the negative
  • Snap a photo and display the greyscale image
  • Use a threshold to make an image black and white
  • Snap a photo, scanning only every other pixel in three lines - top, middle and bottom
  • Display the top, middle and bottom line centers
  • Compute the heading angle and position error
  • Use format specifiers to display decimal numbers
  • Program the CodeAIR to follow a line and land gracefully when done
📂

Digital Resources

🧰

Classroom Materials

  • ▸Laptop/computer with Chrome browser
  • ▸CodeAIR drone and USB cable
  • ▸White sheet of paper with a line made with ¾-inch black electrical tape
  • ▸Light floor or posterboard with a line made with ¾-inch black electrical tape
🌍

Real-World Applications

🚗Self-driving cars and lane-keeping assist use cameras to find lane lines and steer to stay centered, the same idea as the heading angle and position error CodeAIR uses in this mission.
🏭Warehouse and factory robots follow lines on the floor to carry loads from station to station, using a camera or sensor to stay centered on the path.
⚡Inspection drones follow pipelines and power lines, keeping the line in view and centered in the camera frame so they can check long stretches without a pilot steering every turn.
🚀

Extensions & Cross-Curricular

ExtensionInstead of hard-coding the threshold, have the program sample the frame, find the average brightness, and set the threshold a little below the average. Does it work better when the lighting changes?
ExtensionUse the speaker to beep when the line is lost, and a different tone when the drone is centered on the line.
ExtensionExperiment with the Kp values and deadband. What happens when they are large? When they are zero?
ExtensionTape a short crossing line at the end of a course. When the line is crossed, land the drone.
ExtensionScan five rows instead of three. What is the result?
ExtensionIf the line is lost, have the drone hover and rotate slowly to search for it before landing.
ExtensionBuild a fork in the road. Which path should the drone take?
MathThis mission uses trigonometry (arctangent) to turn rise and run into a heading angle. Have students calculate the slope and angle of lines on graph paper and check them with a protractor.
MathThe mission introduces hexadecimal numbers. Practice converting numbers between number systems, even number systems other than binary and hexadecimal.
Life ScienceThis mission teaches a drone to "see." Compare the camera to the human eye. Discuss why the green channel gets an extra bit, since human eyes are most sensitive to green.
EngineeringProportional control is used to correct the drone's position. Discuss other feedback systems students use every day, such as cruise control, thermostats or a person balancing a broom on their hand.
EngineeringHave students act out proportional control: one student guides a blindfolded partner along a taped line with corrections that get bigger as the error grows.
Social StudiesMachine vision is used in self-driving cars, pipeline and power line inspection, farming and security cameras. Have students research one application and discuss its benefits and concerns, such as privacy, safety and jobs.
Visual ArtsHave a lesson on negatives, greyscale and high-contrast black-and-white art.
Physical ScienceDiscuss light absorption and reflection, and why black tape stands out on white paper.
Lang ArtsWrite a paper on a career that uses computer science, like a computer vision engineer, robotics technician, drone pilot or autonomous vehicle tester.
🔤

Vocabulary

▾
Frame - A bitmap, or grid of tiny color squares called pixels.
Hexadecimal (hex) - A compact way to write out bit patterns. Hex is base 16. Each digit counts 0-9 and then keeps going with letters a-f (10 being a, through 15 being f).
XOR - The ^ operator. This bitwise operator flips every bit, which flips every pixel in a bitmap.
Greyscale - A single value from dark to light.
RGB565 - Each 16-bit color pixel uses this configuration: 5 bits red, 6 bits green, 5 bits blue.
Thresholding - Setting a brightness cutoff. Above the threshold is set to one color, and below the threshold is set to an opposite color.
Format specifier - A string formatting tool that determines the number of digits to display after a decimal (floating) point.
Kp Value - The proportional gain in a PID controller. It determines how aggressively a control system reacts to the current error between a desired target and the actual measured process variable.
🐍

New Python Code

▾
out_bitmap = displayio.Bitmap(160, 120, 65536)Blank bitmap the same size as a camera frame. Width=160, height=120, colors=65536 (16-bit).
if camera.frame_available:Makes sure a fresh (new) frame is ready.
for i in range(frame.width):
    for j in range(frame.height):
        pixel = frame[i, j]
Use two nested loops to access every pixel.
out_bitmap[i, j] = pixel ^ 0xFFFFInvert each pixel and save it in the out_bitmap image.
pixel = ((pixel<<8) & 0xFF00 | (pixel>>8))Swap the pixel's two bytes to the correct order.
r = (pixel >> 11) & 0x1F
g = (pixel >> 5) & 0x3F
b = pixel & 0x1F
Use bit shifts and masks to pull out each color. Red and blue are 5 bits (0x1F). Green gets 6 bits (0x3F).
r8 = (r << 3) | (r >> 2)
g8 = (g << 2) | (g >> 4)
b8 = (b << 3) | (b >> 2)
Scale the color values to from 0-255.
grey8 = int((r8 + g8 + b8) / 3)Get one integer as a brightness value.
out_r = grey8 >> 3
out_g = grey8 >> 2
out_b = grey8 >> 3
grey565 = (out_r << 11) | (out_g << 5) | out_b
grey565 = ((grey565<<8) & 0xFF00) | (grey565>>8)
out_bitmap[i, j] = grey565
Pack the grey value back into a displayable pixel. This includes swapping the bytes again on the way out.
out_bitmap.fill(0x0000)Fill the image with black pixels.
continueJump back to the beginning of the loop, skipping the rest of the code in the loop body.
:.1f
heading: {heading_angle:.1f} deg
pos_error: {pos_error:.0f} px
Format specifier. These examples will display with one number past the decimal, and as an integer.
📐

Standards

▾

CSTA Standards - Middle School

MS-ALG-PS-01 MS-ALG-PS-03 MS-PRO-PD-12 MS-PRO-PD-13 MS-PRO-VD-16 MS-PRO-RD-17 MS-PRO-TR-19 MS-DAT-DC-21 MS-SYS-HW-31 MS-SOC-CE-44 MS-SOC-CE-45 MS-SOC-CE-46

CSTA Standards - High School

HS-ALG-PS-01 HS-ALG-PS-02 HS-ALG-PS-03 HS-PRO-PD-12 HS-PRO-PD-13 HS-PRO-VD-16 HS-PRO-RD-17 HS-PRO-TR-19 HS-PRO-TR-20 HS-DAT-DC-24 HS-SYS-HW-30 HS-SOC-CE-45 HS-SOC-CD-46

CSTA Standards - Physical Computing

S1-PHY-IO-02 S1-PHY-DD-03 S1-PHY-PP-07 S2-PHY-IO-02
📝
Preparing for the Lesson
  • Make a practice line for each station: a white sheet of paper with a line made with ¾-inch black electrical tape. The paper can sit on a desk for Objectives 1 through 6.
  • Set up a light floor area or posterboard with a taped line for the Objective 7 flight, and test the line before class.
  • Reserve space with good lighting for the flight - the camera needs to see the black line clearly.
  • Charge all CodeAIR drones fully and have spare batteries ready.
  • Be familiar with the three programs (LinePatrol_Vision, LinePatrol_Scan, LinePatrol_Fly) and the assignment and review questions before class.

🧑‍🏫
Teacher Notes
  • The drone doesn't fly until the last objective. For Objectives 4 through 6, you can use a white sheet of paper with a black line taped to it, and the paper can sit on a desk.
  • You can download an image from the console, and then copy/paste it into the assignment document.
  • Objective 1: Watch the indenting! The pipe command is outside any loop. Students can take multiple images without restarting the code.
  • Objective 2: Remember to delete the line of code that inverts the image.
  • Objective 3: Use a piece of paper and tape a black line on it. That way the paper can sit on the desk.
  • Objective 4: Run the code several times with different threshold values. You will not see an image, just white dots where a line is detected. You can also try the drone at different distances from the line.
  • Objective 7: Some of the code in the first function is the same code from Obj. 6. You can copy/paste from one program to the next. There are differences, though, so step through CodeTrek carefully!
🗺️

Lesson Outline

🗣️Warm-up / Hook

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

  • Ask: "What are the three axes a drone moves along, and what does each movement look like?"
  • Ask: "When you look at a photo, how do you know where a road or a line is? What would a computer need to do the same thing?"
Teaching tip: Frame the mission as teaching the drone to "see." A camera frame is just a grid of numbers, and the whole mission is about turning those numbers into a decision about where to fly.
📖Introduce the Mission

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

  • Introduce the camera frame as a 160x120 bitmap, and walk through how each pixel packs red, green and blue into 16 bits (RGB565).
  • Introduce hexadecimal and the bitwise operators. Each hex digit represents 4 bits, and XOR can flip every bit in a pixel.
  • Preview the pipeline: color image to greyscale, greyscale to black and white with a threshold, then scan a few rows to find the line center.
  • Preview the steering idea: centers become a heading angle and a position error, and proportional control makes bigger corrections for bigger errors.
  • Set expectations: three programs across seven objectives, with quizzes after Objective 3 and Objective 6. The drone only flies in the last objective.
Teaching tip: Hex and bit shifts can feel abstract. Keep the focus on what each step does to the picture, flip it, squeeze it to grey, then cut it to black and white, rather than on memorizing the bit math.
💻Coding Time

Students build three programs that progress from reading pixels to flying the line. As they work through the objectives, they should take notes and answer questions in their assignment doc.

  1. LinePatrol_Vision (Objectives 1-3, quiz after Objective 3) - read every pixel with nested loops, display a negative and a greyscale image, then use a threshold to make the image black and white.
  2. LinePatrol_Scan (Objectives 4-6, quiz after Objective 6) - scan only a few rows of the frame, find the center of the line in each row, then compute the heading angle and position error and display them with format specifiers.
  3. LinePatrol_Fly (Objective 7) - feed the error to the flight controller with proportional control, follow the line, and land when the line ends.
Teaching tip: Have students tape a black line on a sheet of white paper before they start. Objectives 1 through 6 can all be tested with the paper sitting on a desk.
Teaching tip: In Objectives 3 and 4, have students try several threshold values and compare the results. Finding a threshold that works (and one that does not) is part of the assignment.
🧑‍🤝‍🧑Class Debrief

Bring the class together to connect the pieces of the pipeline.

  • Ask: "Why do we reduce a color image to greyscale and then to black and white before looking for a line?"
  • Ask: "Why scan only a few rows instead of every pixel in the frame?"
  • Ask: "What two pieces of information does a line-following program need, and how does the drone use them?"
  • Ask: "What happens to the drone's correction as the error gets bigger? Where have you seen that idea before?"
Teaching tip: Connect back to the Social Studies extension - self-driving cars, farm and pipeline inspection drones and security cameras all use machine vision like this.
✏️Wrap-up & Review

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

Use the Mission 12 Review Questions through a preferred method - class discussion or an LMS quiz.

Teaching tip: Mission 13 moves from brightness to color. Make sure the idea of turning pixels into an error that steers the drone is solid before moving on.