Building a Self-Driving Car
Human ImpactsAlgorithms and ProgrammingArtificial IntelligenceDigital LiteracyComputing SystemsImpact of ComputingEngineering DesignNetworks and the Internet

Building a Self-Driving Car

Grades 6–12
9 hr 33 min
40 steps
Groups of 5
CSTANGSSNC SCOSAlabama Computer Science Standards+5

Standards Alignment

CSTA

  • 3A-CS-01: Explain how abstractions hide the underlying implementation details of computing systems embedded in everyday objects.
  • 3A-CS-03: Develop guidelines that convey systematic troubleshooting strategies that others can use to identify and fix errors.
  • 3A-CS-02: Compare levels of abstraction and interactions between application software, system software, and hardware layers.
  • 3A-NI-04: Evaluate the scalability and reliability of networks, by describing the relationship between routers, switches, servers, topology, and addressing.
  • 3A-DA-09: Translate between different bit representations of real-world phenomena, such as characters, numbers, and images.
  • 3A-DA-11: Create interactive data visualizations using software tools to help others better understand real-world phenomena.
  • 3A-AP-13: Create prototypes that use algorithms to solve computational problems by leveraging prior student knowledge and personal interests.
  • 3A-AP-14: Use lists to simplify solutions, generalizing computational problems instead of repeatedly using simple variables.
  • 3A-AP-15: Justify the selection of specific control structures when tradeoffs involve implementation, readability, and program performance, and explain the benefits and drawbacks of choices made.
  • 3A-AP-16: Design and iteratively develop computational artifacts for practical intent, personal expression, or to address a societal issue by using events to initiate instructions.
  • 3A-AP-17: Decompose problems into smaller components through systematic analysis, using constructs such as procedures, modules, and/or objects.
  • 3A-AP-20: Evaluate licenses that limit or restrict use of computational artifacts when using resources such as libraries.

Related NC CTE courses

  • Drafting Engineering (DREN)
  • PLTW Engineering (PLWE)
  • SREB Aerospace Engineering (AEEN)
  • SREB Clean Energy Technology (CENT)
  • SREB Energy and Power (ENPO)
  • SREB Innovations in Science and Technology (INST)
  • Technology Engineering and Design (TEND)

Showing 12 of 196 standards.

Lesson Steps

1

Welcome to Self-Driving Cars!

5 min

Welcome to the world of autonomous vehicles! Did you know that the first fully autonomous vehicle is widely considered to be the "Stanford Cart?”

The Stanford Cart was initially developed as part of the "Industrial Artificial Intelligence" lab's research project at Stanford University in the 1960s. It gained significant attention and recognition when it participated in the inaugural Defense Advanced Research Projects Agency (DARPA) Grand Challenge in 2004.The Stanford Cart, renamed "Stanley" for the competition, successfully completed a 131-mile desert course and won the first-place prize of $2 million. This event marked a major milestone in the advancement of autonomous vehicle technology.

Want to watch this amazing moment in history?  DARPA Grand Challenge of 2005


Currently, self-driving cars are being tested on public roads in various locations around the world. These vehicles use a combination of sensors, such as cameras, RADAR, and LIDAR, along with advanced software and algorithms to navigate and make decisions on the road. While fully autonomous vehicles that can operate in any driving condition are still being developed, there are already cars on the market with advanced driver-assistance systems (ADAS) that offer features like adaptive cruise control, lane-keeping assist, and automatic emergency braking. These technologies are paving the way for future fully autonomous vehicles.

Want to see for yourself? There's an incredible Waymo 360° Experience: A Fully Autonomous Driving Journey that you can watch. This virtual experience takes you on a ride in a self-driving car, providing a unique perspective on how the technology works and what it feels like to be in an autonomous vehicle. It's an opportunity to witness firsthand the advancements in self-driving car technology and how it's shaping the future of transportation.


The potential impact of self-driving cars is significant, including: 

  • Improving road safety

  • Reducing traffic congestion

  • Increasing accessibility for people who are unable to drive

  • Transforming transportation systems, leading to more efficient and sustainable mobility.

However, there are still challenges to overcome, such as refining the technology, ensuring safety, addressing ethical considerations, and navigating regulatory frameworks. 


What do you think? 

  • How would you feel about riding in a self-driving car? What factors would make you trust or distrust the technology?

  • How do you think self-driving cars will change the way we live and travel? What are the potential benefits and drawbacks?

 

You will be able to answer these questions and more as you progress through this Classbox. We will delve into the fascinating world of self-driving cars and explore the technology, design, and societal impact of autonomous vehicles. Get ready to embark on a journey where you will build your own self-driving car, learn coding and algorithm design, explore AI object detection, and discover the ethical and sustainability considerations of this emerging field.

 

Our Robot Dog, F1D0 is very excited to be on this journey with you! 

Teaching tips

Welcome to the Coding the Future: Adventures in Self-Driving Cars!

Over time, we will be adding more content to our website that you can explore. Updates will also be made to add-ons, which will help you build on the skills you've already learned while making your Robot Car. This means that as we add more content, this one car will actually become more valuable over time. You will get an email when a new project for your car is ready.

Here, you'll learn how to build, program, and test your Robot Car. You should have gotten the hands-on learning Betabox in the mail. It has everything you need to learn. Please send us an email at hello@betaboxlearning.com if you haven't gotten one.


Unit Description: 

Learners will embark on a new and exciting journey into the world of self-driving cars! In this unit, they will learn to build their own self-driving car, program it to navigate through obstacle courses, and train it to recognize objects using computer vision. They will get hands-on experience with coding, algorithms, and cutting-edge technologies as they explore the future of transportation.

In this unit, learners will meet the following goals:

  • Construct a self-driving robot car that meets the specified design criteria.
  • Design and implement algorithms that enable a robot car to move and navigate through an obstacle course.

  • Design and implement computer vision algorithms that enable a robot car to recognize visual stimuli.


Step Description:

In this step, learners will be introduced to the incredible history of self-driving cars, starting with the groundbreaking, "Stanford Cart". They will watch an amazing video that showcases the historic moment and gain insights into the advancements of autonomous vehicle technology. They will discover how self-driving cars are being tested on real roads and experience a virtual ride in a self-driving car through the Waymo 360 Experience. Lastly, they will reflect on the potential impact of self-driving cars, including improved road safety, reduced traffic congestion, and increased accessibility.

2

About My Robot Car Kit

5 min
 

Let’s open your Betabox Car kit! You’ll see that you’ll have everything you need to build an awesome Robot Car.

 

We’ve teamed up with SunFounder to deliver this Robot Car experience.

Accompanying the SunFounder materials, your kit also includes a microSD card and card reader for uploading the Raspberry Pi OS, a Raspberry Pi single board computer, batteries, and battery charger.

 

 

Upon your project completion, you’ll have manufactured a car with quite a few capabilities. You’ll be able to control it via a network connection right from your computer! We will build the car together and unleash our creativity by developing uses for self-driving car technologies.

Teaching tips

This step will show learners all the materials in their Robot Car Classbox.

 

EDUCATOR CLASSBOX

Your Educator Classbox contains:

  • 5 x workbenches each containing…
  • Robot car and camera parts
  • Various screws, nuts, tools
  • 18650 rechargeable battery pairs
  • Battery chargers
  • MicroSD cards
  • Raspberry Pi single board computers
  • 1 x router
  • Materials to set up an obstacle course!

ROUTER SETUP

If using a router for this project, we recommend setting up the router WiFi name and password without special characters (such as *, ? ! _ etc...) as it can create potential issues with the SSH stages. Make sure to write down the name and password for the WIFI, as you will need to share it with students!

 

PREPAREDNESS

We recommend charging the batteries as a first step to make sure they have enough power for the car in later steps. At the end of each day, place batteries back on the charger for the next session. Have ethernet cables nearby during the networking stages in case students need to connect their cars directly to the router.

 

WHITELISTING URLS

Finally, you will be accessing our online project with your students. Whitelist these domains by your IT department:

  • raspberry pi imager

 

SOFTWARE

You will be downloading the following software and using the following applications. Please verify that your student devices have software downloading permissions enabled before you begin. You may choose to pre-download them before you begin your lesson or to do it together as a class. NOTE: If you have an older version of Windows, you may need additional software as indicated by (if needed).

Windows

Mac

Chromebook


Step Description:

This step will show learners all the materials in their Robot Car Classbox.

3

About the Hardware

5 min

Your Robot Car contains more than just the mechanical components we reviewed. The real magic happens in the hardware. Hardware refers to the physical components that make up a robot, such as the sensors and other devices that allow the robot to sense and interact with its environment.

 

Let’s learn a bit about what each bit of hardware looks like and what it does.

 

Raspberry Pi 3B/3B+/4B

This is the main computing component, acting like the “brain” of the system. It is its own little computer!

 

 

Robot HAT

A Robot HAT is a circuit board that can be attached to a Raspberry Pi computer to add extra functionality for building a robot.
 

 

The Robot HAT has several components on it, including:

  • An MCU (microcontroller unit) which is a small computer that can be programmed to perform tasks and control other devices. The MCU on the Robot HAT is used to extend the PWM output and ADC input capabilities of the Raspberry Pi. (PWM output allows the Raspberry Pi to control the speed and direction of motors, while ADC input allows it to measure analog signals, such as those produced by sensors.)

  • A motor driver chip which is used to control the motors on the robot.

  • Bluetooth module which allows the Raspberry Pi to communicate with other devices using Bluetooth.

  • An I2S audio module which allows the Raspberry Pi to play audio.

  • A mono speaker which is a single speaker that can be used to play sound.

The Robot HAT also has connections (called GPIOs) that allow it to be connected to the Raspberry Pi and access the Raspberry Pi's input/output pins.

 

Ultrasonic Sensor

An ultrasonic sensor is a device that uses sound waves to measure distance or detect the presence of objects.

Grayscale Module

This device can be used to detect and follow a line on a surface. It works by using three channels, or sensors, that measure the intensity of light reflecting off the surface.

 


 

Teaching tips

Step Description:

In this step, learners will explore the hardware that makes up their Robot Car. The hardware components are the physical parts that bring their robot to life and allow it to sense and interact with its environment. They will take a closer look at each piece of hardware and understand their roles.

4

What's What?

20 min

Additional Equipment for Mac Users

If you are using a Mac computer, you will need a USB-C to USB-A adapter

 

It will be helpful to know what all your Betabox components are called so that you have a shared language to communicate and collaborate. Many industries have different names for the same things, called jargon, that are specific to their fields.  Think about it like work nicknames for your materials. You may want to open this page in a new tab to reference as you work through the assembly process.

 

Let’s get started! Unpack the components in your kit and take a moment to learn what each piece is called.

 

The following video shows us unpacking the Robot Car kit! 

 

 

Components List

 

A1 - Upper Plate

A2 - Pan-and tilt Plate

A3 - Camera Mount Plate

A4 - Front Half Plate

A5 and A6 - Steering Connnector Plates

A7 - Steering Linkage Plate

A8 - Ultrasonic Module Plate

 

Now, check out the servo accessories baggie. You should have three sets of these.

 

 

The mechanical fastener baggies will contain a variety of screws, nuts, washers, and standoffs in different shapes and sizes. Take a moment to look and organize them.

 

Mechanical Fasteners

 

 

Lots of stuff!

Check out the wire pack and familiarize yourself with them. You may have extra wires in your kit.

 

 

Other Components

 

 

The yellow motors are going to be able to drive your car forwards and backwards and the servo is used for steering left and right!

You will have a set of wheels, a camera, and a ribbon in your pack.

 

 

 

You’re also provided with a set of tools. The wrenches will be used to secure the nuts.

 

 

In addition to these car components, your Betabox Kit also includes the following:

 

Now that we’ve got that out of the way, click Next Section to discover more advanced components in your Betabox.

Teaching tips

Step Description:

In this step, learners will explore and take a closer look at more of the components that make up their Robot Car.

Additional Equipment for Mac Users

If you are using a Mac computer, you will need a USB-C to USB-A adapter

5

Imaging the Raspberry Pi

30 min

Now it is time to switch gears from the assembly of our cars to the setup of the software. This experience may be done alone, but may be more powerful with a partner. 

 

❗️If Using a Classroom Router

If you are a student working on this project in a classroom, ask your teacher for your router’s WiFi name and password as well as confirming your car’s hostname label (look for a sticky note or piece of tape as indicated by your teacher).

 


The following video shows the steps described below: 

 

The first thing we will need to do is set up our operating system on our SD Card. Find your SD card and your SD card reader. Plug the SD card into the small slot of your reader (make sure to push it in all the way). Then, plug the reader into a USB port of your computer.


 

INSTRUCTIONS FOR MAC 🍎 OR WINDOWS 💻 (Chromebook instructions coming soon)

  1. Download the Raspberry OS Imager software. Select Download for Windows or Mac.
  2. Download the robotcar-python.img.gz file.
  3. Insert your microSD card into the card reader and insert it into the USB slot of your computer.❗️Your Mac may not have a USB port. You might need a USB-C to USB-A adapter to fit a microSD card. 
  4. Open the Raspberry Pi Imager program and allow it to make changes to your computer.  
  5. For the Operating System, Click CHOOSE OS and select Use custom.
  6. Select robotcar-python.img.gz from your downloads.
  7. For the Storage, Click CHOOSE STORAGE and select your storage device (this will be your microSD card in the reader and will show something like the image below.) 
  8. Open Advanced Options by typing CTRL+Shift+X or select the gear button at the bottom right. 
  9. Under Image customization options, select for this session only.
  10. Check the box for Set hostname.
  11. Type the hostname as robotcar (all lowercase).  If you choose to set your own hostname, remember to write this down and do not lose it. ❗️ If you are in a classroom, ask your teacher for your car's hostname (check for a label on the car). Yours may be robotcar1 or robotcar2 for example.
  12. Check the box for Enable SSH.
  13. Check the box Use password authentication.
  14. Check the box Set Username and Password 

    ⌨️Type the username as pi (all lowercase). If you choose to set your own username, remember to write this down and do not lose it. 

    ⌨️Type the password as raspberry (all lower case). If you choose your own password, make it as simple as possible and write it down so you don't lose it. 

  15. Check the box for Configure wifi.

  16. For SSID: type in your Wifi network name (punctuation, spaces, and capitalization must match). ❗️ If you are in a classroom, ask your teacher for the router's wifi name.

  17. For Password: type in your Wifi password (punctuation, spaces, and capitalization must match).❗️If you are in a classroom, ask your teacher for the router's wifi password.

  18. In the Wifi Country dropdown, select US.

  19. Check the box for Play sound when finished.

  20. Check the box for Eject media when finished. 

  21. Before you move on, write down the hostname, username, and password that you used to write your SD card and keep it in a place you will not forget or lose it❗️

  22. Click SAVE and you will be taken back to this page. 

  23. Click WRITE to etch the Raspberry Pi OS to your microSD card.

  24. When finished, remove the device from your computer and insert the microSD card into the slot of the Raspberry Pi board.

  25. While you wait on the Imager to finish creating the SD card, we can move on to actually building the car!

When your SD card is done being written, you can eject it from your computer and put it aside. You will need to insert this SD card into your car when you are finished building it. 

 

🌟Congratulations! You are done with this section!🌟 

 

Our Robot Dog, F1D0 is very excited to be on this journey with you! 


 

Troubleshooting 🤷

 

🚩 Nothing shows up when I click Storage.

  1. Make sure you have pushed the microSD card all the way into the card reader and that you have inserted the reader into the USB port of your device. Also check to see if you put your microSD card in the correct slot (the smaller one) of the card reader. Sometimes it is labeled as TF card.
  2. If the last step doesn't work, try Another USB Port or Change the Adapter or Card Reader.

 

🚩 My SD Card is broken (using a Mac).

To check and repair a disk, you need to run First Aid: 

  1. In the Disk Utility app on your Mac, choose View > Show All Devices.
  2. In the sidebar, select a volume, then click the First Aid button .
  3. When the First Aid process is complete, click Done.

  4. For good measure, click Erase in the sidebar as well.
  5. When you are done, try re-imaging the SD card. 
  6. If this still doesn't work, contact us for a new SD card. 

 

🚩 My SD Card is broken (using Windows).

Use CHKDSK to repair SD card corruption: 

  1. Press Windows + X.
  2. Select Windows PowerShell (Admin).
  3. Enter the following command (make sure to replace X with the letter assigned to your SD card) and press Enter: chkdsk X: /R 
  4. Wait for CHKDSK to finish. The process may take several hours, depending on the size and speed of your SD card.
  5. If this still doesn't work, contact us for a new SD card. 

Teaching tips

Step Description:

To set up the operating system on the Raspberry Pi, learners will use the Raspberry Pi Imager software. They will simply download and install the software, select the desired operating system, choose the SD card as the destination, and start the imaging process. Once completed, they can insert the SD card into their Raspberry Pi and proceed with further configuration.

6

Battery Holder Assembly

15 min

Gathering Your Materials

Let’s start building this thing! Take it one step at a time and if you get stuck, give yourself a break, ask for help, or check back in with these guides.

 

The first step is to create the Battery Holder Assembly. You will need the parts shown below to complete this step.

 

 

Watch the following video for guidance on completing this step! 

 


Assembling the Battery Holder!

Insert the ribbon into the structural plate as shown below.

 

To screw in your battery pack, use the two M3x4 countersunk screws. Countersunk screws have a slanted head and are flat on the top. If you don’t use countersunk screws for this then the batteries won’t be able to fit in the holder.

Pay attention to the location of the wire sticking out of the battery pack and make sure it lines up with the picture below.

When inserting the batteries, make sure to pull the ribbon underneath each battery. This step makes it much easier to remove the batteries when needed.

 

Pass the battery holder wire through the hole as shown below.

Teaching tips

SECTION II: Constructing your Robot Car

In this section, learners will focus on building the Robot Car, establishing a connection to it via SSH, and calibrating its functionalities. Through hands-on activities, they will assemble the mechanical components, learn about hardware and sensors, and gain valuable experience in constructing their autonomous vehicle. Along the way, they’ll develop important problem-solving, teamwork, and technical skills in programming and robotics. 

Step Description:

Now learners  will build their self-driving robot car by following the step-by-step instructions. They will assemble the battery holder, motors, camera module, and sensors with precision and creativity, and then they will wire the boards together.

Classroom Setup:
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress.

7

Motor Assembly

15 min

Gather the Materials

The next step is to create the Rear Wheel Assembly. You will need the components shown below to complete this step.

 

Watch the following video for guidance on completing this step! 

 

 

Create the Rear Wheel Assembly

To begin, use four M2.5x20+6 standoffs and four M2.5x6 screws.

 

Attach the standoffs to the chassis plate as shown.

 

Grab the yellow motors and chassis. Use four M3x25 screws, four spring washers, and four M3 nuts to assemble the two motors as shown below. When installing the motors onto the chassis, make sure that the read and black wires are facing inside.

 

Place the wires through the hole as shown below.

Teaching tips

CLASSROOM SETUP
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress. 

8

Attaching the PCBs

20 min

Gathering Your Materials

The next step is to attach the Printed Circuit Boards (PCBs) that make the car function. Here is what we will need:

 

Watch the following video for guidance on completing this step! 

 

 

Attach the PCBs

First, grab the Raspberry Pi single board out of its box and place it onto the four M2.5x20+6 standoffs you previously installed on the board. You’ll see holes on the corners of the Pi board that correspond with the holes on the chassis plate. The USB and ethernet ports should be faced toward the back of the chassis plate, close to the motor wires.

 

Next, insert the FFC cable into the ribbon cable slot on the Pi as shown. Gently pull up the black tab, insert the FFC cable, and push to close.

 

Face the other end of the FFC Cable toward the front of the chassis plate. We will attach it in a future step.

 

Next, screw four M2.5x11 standoffs on top of the first four standoffs you used to seat the Pi onto the chassis plate. These upper four standoffs will secure the Pi and will become the base for the Robot HAT board.

 

The Robot HAT board is the white board. Place it on top of the four standoffs you just added and place the Robot HAT Case on top of it.

 

Finally, use four M2.5x14 screws to attach the Case to the HAT.

Teaching tips

CLASSROOM SETUP
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress. 

9

Attaching the Servo Arm and Ultrasonic Module

15 min

Gathering Your Materials

You will now attach one Servo Arm and the Ultrasonic Module. Find the following materials in your kit:

 

Watch the following video for guidance on completing this step! 

 

 

Attach a Servo Arm

First, grab the servo arm and four M1.5x4 self-tapping screws.

 

Place the servo arm on the bottom of the chassis and add the four screws as shown below.

 

Attach the Ultrasonic Module

Next, get the A8 plate, Ultrasonic Module, and two R3090 Rivets. Insert the Ultrasonic Module and place the A8 plate directly behind it. Insert the two rivets as shown in the diagram below.

 

Once the rivets are in place, push them to lock them into place.

 

Finally, insert two M3x6 screws with two M3x26 standoffs into the screw holes as shown below.

 

Teaching tips

CLASSROOM SETUP
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress. 

10

Camera Module Assembly

15 min

Gathering Your Materials

The next step is to build the Camera Module Assembly. See the image below for the necessary materials.

 

Build the Camera Module Assembly

First, insert the other end of the FFC cable into the Camera Module as shown. Gently pull up the black tab, insert the FFC cable, and push to close.

 

Next, use four M2x4 screws to attach the Camera Module to the A3 plate as shown below.

 

Finally, place the Servo Arm on the outside of the A3 plate and use four M1.5x4 self-tapping screws to secure it in place.

 

Teaching tips

CLASSROOM SETUP
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress. 

11

Servo Mount Assembly

10 min

Gather Your Materials

You will now assemble the Servo Mount. Use the image below to help you gather the necessary components.

 

Assemble the Servo Mount

Insert the Pan Servo to the A2 Plate as shown below. Use two M2x4 screws to secure the servo.

 

Insert the Tilt Servo to the A2 Plate as shown below. Use two M2x4 screws to secure the servo.

 

Teaching tips

CLASSROOM SETUP
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress. 

12

Turning on your Car

5 min

At this point, you are going to turn your car on for the first time. You will need to plug in your batteries (remember to tuck the blue ribbon underneath each battery) and turn on your car. 

To turn on your car, you will need to connect the power cable coming from the battery holder to the power slot in the Robot HAT. 

 

Now, it’s time to insert the microSD card into the slot of the Raspberry Pi board on your Robot Car.

Don’t worry that your car is not completely assembled yet. 

 

 

Next, flip the black switch on top of the car to turn it on: 

 

 

Finally, be patient and listen for a soft 'click' noise when the Robot Car is ready to connect. This process will take longer the first time you turn on your car. 

 

Keep your car on for the following step. 

13

Servo Calibration

10 min

You will need to connect to your car for the following steps while you calibrate your servos to the Raspberry Pi. Save this step for future reference!

 

Watch the following video for guidance on completing this step! 

 

 

 

Instructions for Windows and Mac

(Chromebook coming soon)
 
  1. Turn on the car. 

  2. Make sure your computer is on the same WiFi as your Robot Car.

  3. Open a Google Chrome Browser and type this into the URL: http://hostname:8080

    • Use the hostname you configured in a previous step: Imaging the Raspberry Pi

    • If you are using a Mac, type in http://hostname.local:8080

    • For example, your hostname may look like robotcar.local (or robotcar1.local if using a classroom router). 

  4. You should see a page like this upon connecting for the first time: 

  5. If you do not see the TERMINAL showing up in the status bar, hit CTRL and ~ on your keyboard.

  6. Once you are networked in and see your username@hostname in blue, type in the following commands and press enter after each command.

    • cd picar-x

    • cd calibration

    • sudo python3 servo_zeroing.py

 

Look below for an example of how it should look on your TERMINAL. 

 

❗️Keep the car on until all three servos are attached in the following steps❗️

 


Troubleshooting 🤷

 

🚩 If the previous steps worked, you can skip this step. If the previous steps did not work, we will use a workaround using the command prompt or windows terminal in your computer. To do this easily, click the Search icon and then type “terminal” or “windows terminal.” 

  • You should see an icon that looks like either of these 
  • To connect to your car, use the format ssh username@hostname (for windows) or ssh username@hostname.local (for mac) and use the username and hostname you configured in a previous step: Imaging the Raspberry Pi.
  1. Turn on the car. 
  2. Make sure your computer is on the same WiFi as your robot car.

  3. Open Command Prompt or Windows Terminal.

  4. Type ssh username@hostname and press Enter. ❗️If you are using a Mac, type in ssh username@hostname.local

  5. If this is your first time connecting on the terminal, you will be asked ‘ Are you sure you want to continue connecting (yes/no/[fingerprint])?’ Type yes then enter. 

  6. Type the password when prompted and press Enter. ❗️ Note: you won’t see the password typing out.

  7. Once you are networked in and see your username@hostname in green, type in the following commands and press enter after each command:

    • cd picar-x

    • cd calibration

    • sudo python3 servo_zeroing.py

  8. Press Control + C to exit the program. 

14

Add the Servo Assembly to the Camera Assembly

10 min

Gather Your Materials

You will now add the Servo Assembly to the Camera Assembly. Here are the materials you will need:

 

Attach the Servo Mount Assembly to the Camera Assembly

First, tuck the FFC cable into the gap between the two servos as shown below.

 

Next, make sure to plug the camera servo into the D11 pins on your Robot Hat and use the Servo Screw (included in the Rocker Arm bags) to attach the Servo Assembly to the Camera Assembly as shown below. This will ensure that your camera is as close to the correct starting position as possible.

 

 

 

 

Teaching tips

CLASSROOM SETUP
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress. 

15

Finishing the Camera Mount Assembly

10 min

Gather Your Materials

 

Your next step will be to attach the Servo and Camera Assembly to the Chassis. See the image below to help you determine which materials to use.

 

 

Attach the Assembly to the Chassis

 

Before you start attaching the assembly to the chassis, make sure to plug the Camera Assembly Servo into the D11 pins.

 

Place the Big Ring Washer in between the Chassis and the Camera Assembly Servo.

 

Hold the assembly in place with one hand and turn the Chassis over and tighten the Servo Screw.

 

 

 

Teaching tips

CLASSROOM SETUP
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress. Once they are ready to begin assembling, navigate to the following manufacturing pages.

16

Add the Steering Servo and Steering Bar

15 min

Gather Your Materials

 

You are now ready to install the Steering Servo and the Steering Bar. You will need the components shown below:

 

 

Add the Steering Servo and Steering Bar

 

To begin this step, we will first add the Steering Servo. Turn the car so that the Camera Module is facing away from you. Now add the servo so that the wire of the servo is towards the left.

Attach the servo by using two M2x4 screws.

 

 

 

Next, find the 1-Arm Rocker Arm and a M1.5x4 screw to prepare for the steering bar assembly process.

 

Now, sandwich the Steering Bar (A7 Plate) between the Rocker Arm and the screw. Make sure you stick the screw through the very first hole in the Rocker Arm (you’ll be threading the plastic of the Rocker Arm while doing this.).

 

Ensure that the screw is a little bit loose so that the assembly can rock back and forth. You can do this by backing the screw out a ¼ turn once you’ve inserted it.

 

 

After plugging the Steering Servo into the D11 pins you can add the Steering Bar Assembly to the bottom of the Steering Servo using a Servo Screw (located in the Rocker Arm bag) as shown below.

 

 

 

 

Teaching tips

CLASSROOM SETUP
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress. Once they are ready to begin assembling, navigate to the following manufacturing pages.

17

Grayscale Module Assembly

10 min

Gather Your Materials

 

The next step is to create the Grayscale Module Assembly. See the image below for the required components.

 

 

Build the Grayscale Module Assembly

 

First, you will need to attach the A4 Structural Plate to the two standoffs that you previously added. Use two M3x6 Screws as shown below.

 

 

To complete this step, you will use two M3x6 Screws to attach the Grayscale Module as shown below.

 

 

 

Teaching tips

CLASSROOM SETUP
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress. Once they are ready to begin assembling, navigate to the following manufacturing pages.

18

Front and Rear Wheel Assembly

20 min

Gather Your Materials

 

You will now add the Rear Wheels and create the Front Wheel Assembly. Find the items shown below to begin.

 

 

Add the Rear Wheels

 

To complete the Rear Wheel Assembly, stick the rear wheels onto the motors as shown below. Note that the rear wheels look different from the front wheels. Go back to the materials list page to spot the difference.

Rotate them a bit to ensure they spin.

 

 

Build the Front Wheel Assembly

 

First, attach the A5 Structural Plate using three R3065 Rivets as shown below. Note that the A5 and A6 Structural Plates are slightly different. Ensure you have the correct one by looking at the images below.

Remember to gently press on the top of the rivets when you have them in the correct position to lock them into place.

 

 

You will now attach the A6 Structural Plate using three R3065 Rivets on the other side of the car.

 

 

Next, insert an R4120 Rivet through one of the front wheels. Do not lock the rivet just yet!

 

Stack two Hexagonal Washers and one Round Washer on the rivet. Make sure to add the two Hexagonal Washers before adding the Round Washer to ensure the wheel will fit.

 

Once that wheel assembly has been completed, make another one identical to it.

 

 

You will then attach one of the wheel assemblies you just created to the A5 Structural Plate and the other to the A6 Structural Assembly as shown below.

 

After placing the two wheel assemblies in the correct places, you should now gently press the head of each rivet to lock them into place.

 

 

 

Teaching tips

CLASSROOM SETUP
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress. Once they are ready to begin assembling, navigate to the following manufacturing pages.

19

Wiring the Car

10 min

Gather Your Materials

You will now wire your car to complete the final step of assembly. Find the items shown below to begin.

 

 

Watch the following video for guidance on completing this step! 

 


Wire the Car

 

Now that you have your car assembled, it’s time to wire your boards to each other.

 

Take a moment to review the diagram below to understand how the system connects together.

 

 

Triple check to ensure that everything is in the correct place!

 

 

✨ Congratulations! You've now completed the assembly portion of your car! You will now move to the software and testing section! ✨

 

Teaching tips

CLASSROOM SETUP
Students will work in groups having one car kit in the center of their table. Each group will have at least one computer on their table for viewing project modules. These sections do not involve software or programming. Have storage containers on hand for saving assembly progress. Once they are ready to begin assembling, navigate to the following manufacturing pages.

20

Connecting to the Robot Car via SSH

10 min

We're going to learn about networking, specifically using SSH (Secure Shell) to connect to the Raspberry Pi remotely. Remember how we imaged the SD card? That process enabled us to set up the operating system on the Raspberry Pi, allowing us to establish a connection between it and our devices.

⭐ Networking enables communication between a computer and an electronic device by establishing a connection that allows data and commands to be exchanged. Through networking, the computer can send instructions to the Robot Car, such as to move forward, turn left, or stop. It also allows the Robot Car to send back sensor data or other relevant information, enabling the computer to monitor and control the car remotely.

With SSH, we can remotely access the command line interface of the Raspberry Pi from our computers so they don’t have to be physically connected to the computer. It's like having a virtual connection to the car, where we can send commands and control its actions. 

By setting up the operating system, we've prepared the Raspberry Pi for remote communication. It's an essential step that enables us to establish a secure connection and control the robot car from a distance. 

 


Watch the following video for guidance on completing this step! 

 

⭐ For this step, make sure your SD card is inserted into your Robot Car and you have fully charged batteries. We recommend you keep the car on for the following steps, otherwise you will have to reconnect to your car at each step. ⭐

 

Connecting to your Car - Instructions for Windows, Mac, and Chromebook

  1. Turn on the car. 

  2. Make sure your computer is on the same WiFi as your Robot Car.

  3. Open a Google Chrome Browser and type this into the URL: http://hostname:8080 

  4. If you are using a Mac, type in http://hostname.local:8080

❗️For example, your hostname may look like robotcar.local (or robotcar1.local if using a classroom router).

 

Once on the browser, open up the terminal.

If you do not see the terminal showing up in the status bar, hit Ctrl + ` on your keyboard, or use the View > Terminal menu command.

 

Now, type hostname-I in the terminal and press Enter. Doing this will reveal the IP address of your device. More on this later!

 


Connecting to your car via SSH on Terminal

If the previous steps worked, you can skip this step. If the previous steps did not work, we will use a workaround using the command prompt or windows terminal in your computer. To do this easily, click the Search icon and then type “terminal” or “windows terminal.” 

To connect to your car, use the format ssh username@hostname.local and use the username and hostname you configured in a previous step: Imaging the Raspberry Pi.

For example, yours may look like ssh pi@robotcar.local (or ssh pi@robotcar1.local if using a classroom router).

 

Windows (version 10 or higher) and Mac

  1. Turn on the car.

  2. Make sure your computer is on the same WiFi as your robot car.

  3. Open Command Prompt or Windows Terminal.

  4. Type ssh username@hostname and press Enter. ❗If you are using a Mac, type in ssh username@hostname.local

  5. Type the password when prompted and press Enter. ❗Note: you won’t see it typing out


 

Troubleshooting 🤷

Go here for a full list of troubleshooting issues 

I can’t connect:

  • Are you using SSH with the username@hostname.local format? Make sure your username and hostname have the same spelling and capitalization as you configured it in the Imaging the Raspberry Pi step.
  • At home example: pi@raspberrypi.local
  • Classroom w/ router example: pi@robotcar1.local

 

I still can’t connect: 

  • Turn your car off and allow a few seconds before you turn it back on. 

 

I am getting this error message: 

 

 

  • Solution: Delete corrupt SSH files. 
  • MacOS: Open Finder and click on Go → Go To Folder → open folder /Users/your_name/.ssh → delete all files in that folder (including: known_hosts) → try reconnecting. 
  • Windows: Windows Key + R → C:\\Users\\Student/.ssh → delete all files in this folder (including: known_hosts) → try reconnecting. 

 

I still don’t see it: 

  • Try re-imaging your SD card with the steps from before 

 

The term ‘ssh’ is not recognized: 

 

Still nothing: 

  • Your teacher is your primary point of contact for technical assistance and support. If you're facing any challenges or have questions about the lab activities, start by reaching out to them. 

 

Teaching tips

Step Description:

In this lesson, learners will be introduced to the concept of networking and they will understand how it connects to the previous step of imaging the Raspberry Pi with the operating system. The learners learn about SSH and how it enables remote control of the Raspberry Pi.

The beginning of this step begins with connecting the Robot Car with the web browser on http://hostname.local:8080. If this isn't working, reach out to the Betabox team. Still, you can work around this using the command prompt or windows terminal on a desktop, as detailed later in this step. 


 

21

Understanding an IP Address

10 min

You may be wondering why we asked you to find the IP address for your car. An IP address, which stands for Internet Protocol address, is like a unique identifier for devices connected to a network. It helps in identifying and locating devices on the network, much like how a street address helps us find a specific house. It's made up of a series of numbers, separated by periods or colons, depending on whether it's an IPv4 or IPv6 address. For example, it might look something like 192.168.0.1

 

IP addresses also have practical applications in everyday life. For instance, when you order food for delivery, the delivery driver relies on their GPS device, which uses IP addresses to navigate to your location. Additionally, IP addresses are used in online gaming, video streaming, and countless other activities that require devices to connect and exchange data.

 

Does this mean anyone can know your location at any given time just by knowing your IP address?

 

While IP addresses can provide some general information about the geographic region associated with an address, they do not pinpoint your precise physical location. IP addresses can give an approximate location based on factors like the internet service provider (ISP) you're using and the IP address range assigned to that ISP. However, this information is often limited to the city or region and does not reveal your exact address or coordinates. 

 

❗Remember, maintaining your privacy and security online is crucial, and being mindful of the information you share and the steps you take to protect your digital footprint can help you stay safe.

 


Take some time to answer these questions in your own words. You can type the answers or write them in a notebook to be reviewed by your teacher. 

  1. How does networking enable communication between a computer and a robot car?

  2. What is the significance of establishing an SSH connection in controlling the robot car?

  3. What is an IP address? Describe how they are important for data exchange.

Teaching tips

 

Answer Key for teacher: 

Question 1: How does networking enable communication between a computer and a robot car?

  • Explained that networking allows devices to connect and communicate over a network.
  • Mentioned that a computer can send commands or instructions to the robot car through the network.

Question 2: What is the significance of establishing an SSH connection in controlling the robot car?

  • Described SSH as a secure and encrypted way to access a remote device over a network.
  • Explained that an SSH connection provides remote access to the robot car's interface.
  • Highlighted the significance of controlling the robot car's behavior without physical access to it.

Question 3: What is an IP address?

  • Defined an IP address as a unique numerical label assigned to devices on a network.
  • Explained that it serves as an identifier for devices like computers, smartphones, and robot cars.
  • Mentioned that IP addresses are used to locate and communicate with devices on a network.
  • Described how IP addresses are crucial for data exchange and establishing connections between devices.
22

Navigating VS Code

20 min

In this step, we'll dive into coding using Visual Studio Code (VS Code). You'll learn to navigate directories efficiently and utilize the Python extension to write and run code seamlessly within the VS Code environment. Additionally, we'll explore how to run Python code on your Robot Car with a simple click. This step equips you with essential skills for coding and directory navigation, setting the foundation for your coding journey.

VS Code, short for Visual Studio Code, is a computer program that helps you write and edit code for different programming languages. It's like a special text editor that is designed to make coding easier and more efficient. 

You might be wondering why we prefer using this software instead of using your computer’s terminal.

 

When it comes to changing code, using a terminal-based text editor can be a bit tricky and not as easy to use as dedicated code editors like VS Code. Terminal-based text editors are more basic and don't have fancy features that make coding easier. They are useful for making small changes to code quickly or when you don't have an advanced visual interface to work with. However, if you want a more comfortable and advanced coding experience, it's better to use a dedicated code editor like VS Code, which has lots of helpful features and a nice interface to make coding easier for you.

 

With this interface, we can control a robot car by providing a set of instructions or algorithms that govern the car's actions and behavior. By programming the car, we can define how it should respond to different inputs, such as sensor data or user commands, and make decisions on how to navigate through obstacles and follow a predefined path.


To navigate through the code directories, once you’re already connected to your car:

 

  • Find the Explorer icon at the top left of the taskbar (it looks like two files on top of each other) and open the PI folder.

 

  • Navigate to the directories you need to run the code. We will start with the directory under the name: workspace

 

  • You will be using the workspace directory a lot. When you open or create your own file within this directory, usually you can run the code directly to the Raspberry Pi using a Python extension, which you might already be familiar with. 

 

This extension allows you to write, edit, and run Python code directly within the VS Code environment. The "play button" is a feature provided by this extension that allows you to run your Python code with a single click, and it can be especially convenient for tasks like deploying code to your Robot Car. Instead of manually navigating to directories in the terminal, you can initiate the execution of your code directly from the VS Code interface, which can be a time-saving and user-friendly way to work on your projects.

 

However, sometimes this player does not work, and learners should get used to navigating to the directories in the terminal using the linux commands. Navigating through directories using commands like cd, seeing the libraries like ls, and running scripts using sudo python3, ensures a deeper understanding of how the system works and can be very helpful when troubleshooting issues.


Vocabulary 📓

 

Picar-X:

Imagine you're in a big library, and each bookshelf is like a different section of knowledge. Well, 'picar-x' is like a bookshelf in the library of coding. But instead of holding books, it's packed with all kinds of codes and tools made by the computer programmers at SunFounder, who also designed your Robot Car! So, when you see 'picar-x' or other directories, such as ‘vilib,’ just remember it's like a treasure trove where you can find a library of pre-made algorithms. You can add to these libraries and tinker with them to make them your own.

 

Directory:

A directory in Raspberry Pi is like a folder on your computer. It's a place where you can keep files, like your documents, pictures, or even special coding files. It helps you keep things organized. For example, think of a directory as a folder named "Projects" where you keep all your different project folders.

 

Library:

A library in Raspberry Pi is a collection of pre-made code that you can use to make your projects easier. It's like having a set of tools ready to use without having to build them from scratch. Libraries have pieces of code that do specific tasks, such as controlling hardware like motors or sensors. When you use a library, you're using code that someone else has already written to save you time and effort.

 

Python:

Python is a popular programming language known for its simplicity and readability. A programming language is a formalized set of instructions that a computer can understand and execute. It acts as a bridge between human-readable code and the machine's binary language.

 

Linux:

Linux is an Operating System (OS). It is a software that acts as an intermediary between computer hardware and user applications. It provides a set of essential services and functionalities that enable users to interact with and utilize a computer system efficiently. The main functions of an operating system include managing hardware resources (such as memory, CPU, and storage), providing a user interface, facilitating communication between software components, and ensuring security and stability.

 

One big reason people love Linux is that it's open source. This means anyone can look at its code, tinker with it, and make it better. Imagine building your own custom game level – that's the kind of flexibility Linux offers! Linux is also famous for being stable, reliable, and secure.

 

Teaching tips

Teaching Visual Studio Code (VS Code) effectively to your students can enhance their coding and development skills. Here are some teaching tips for introducing and using VS Code in the classroom.

  • Take your students on a tour of the VS Code user interface. Point out the key elements such as the sidebar, the editor area, the status bar, and the command palette. Ensure they are familiar with the basic layout.
  • Introduce the integrated terminal in VS Code, which allows students to run command-line operations without leaving the editor. Show them how to open, use, and customize the terminal.
  • Teach students best practices for organizing their projects within VS Code, including using folders, workspaces, and project-specific settings.
  • Encourage students to personalize their VS Code environment by customizing themes, settings, and keyboard shortcuts to suit their preferences.

Vocabulary: There are vocabulary terms at the bottom of this page. It may be useful for students to create flashcards or write these definitions (paraphrased) in a notebook. 

23

Navigating the Terminal with Linux Commands

5 min

Linux commands are text-based instructions used to interact with the Linux operating system and perform various tasks. These commands are typically entered into a terminal or shell, and they allow users to control and manipulate the system. 

 

Back before computers had a desktop, graphical programs used the command line to communicate with the user. Command lines are a mainstay in modern day computers and while most users don’t have a use for them, programmers find them invaluable. The command line allows you to edit files, run code, change settings, start and install programs, and almost anything else you could do with a desktop. In Windows, the command line is called the command prompt, or cmd. On Mac and Linux run computers, it is called the shell. When you ‘SSH‘ or remote-connect into a Raspberry Pi, you are accessing the shell with a Secure SHell connection.

 

Common Linux Commands

  • cd ↔️ change directories (go to another folder)

  • cd / ↔️ go to root (base) directory

  • cd ~ ↔️ go to home (the very start) directory

  • cd ../ ↔️ go up 1 directory (towards home)

  • cd ../.. ↔️ go up 2 directories (towards home)

  • pwd ↔️ print working directory (shows where you currently are)

  • ls ↔️ list (shows list of files/folders in current directory)

  • sudo python3 …py  ↔️ used to run a Python script

  • UP ARROW ↔️ quickly cycle through lines of code you’ve already typed

  • TAB ↔️ autocompletes files and folders

 

Watch the following video to guide you through navigating the terminal with linux commands: 

Teaching tips

Introducing students to Linux commands can be a valuable skill, and it's important to make it engaging and accessible. Set up a hands-on, interactive environment where students can practice these commands.

If possible, you could have students create their own cheat sheet of these commands so they can refer to them throughout the coding projects. 

24

Calibrating the Robot Car’s Servo Angles

20 min

Get ready to fine-tune your robot car for optimal performance! In this step, we will learn how to calibrate the servo angles of the Robot Car to ensure precise control. By running the calibration code, you can adjust the front wheel, pan, tilt, and motor directions to achieve the best alignment. Don't worry if you think your assembly is already perfect - you can skip this step if needed.

 

Some servo angles may be slightly tilted due to possible deviations during your Robot Car installation or limitations of the servos themselves, so you can calibrate them.

 

 

Follow the steps below detailing each step: 

 

  1. SSH-connect into your Robot Car using the previous steps: 

  • Turn on the car. 
  • Make sure your computer is on the same WiFi as your Robot Car.
  • Open a Google Chrome Browser and type this into the URL: http://hostname:8080 
  • ❗️If you are using a Mac, type in http://hostname.local:8080
  • ❗️For example, your hostname may look like robotcar.local (or robotcar1.local if using a classroom router).

 

  1. In the terminal, type and Enter: sh calibration.sh

  • ❗️If you do not see the TERMINAL showing up in the status bar, hit Ctrl + ` on your keyboard. 

 

  1. If that did not work, navigate to the following folders: 

  • picar-x

  • calibration 

  • Run calibration.py

 

  1. After running the code, you will see the following interface displayed in the terminal: 

  2. The R key is used to test whether the servo that controls the direction of the front wheel can work normally and is not damaged. 

  3. Press the number key 1 to select the front wheel servo, and then press the W/S key to let the front wheel look as forward as possible without skewing left and right. 

  4. Press the number key 2 to select the Pan servo, then press the W/S key to make the pan/tilt platform look straight ahead and not tilt left or right. 

  5. Press the number key 3 to select the tilt servo, then press the W/S key to make the pan/tilt platform look straight ahead and not tilt up and down. 

  6. Since the wiring of the motors may be reversed during installation, you can press E to test whether the car can move forward normally. If not, use the number keys 4 and 5 to select the left and right motors, then press the Q key to calibrate the rotation direction. 

  7. When the calibration is completed, press the Spacebar to save the calibration parameters. There will be a prompt to enter y to confirm, and then press esc to exit the program to complete the calibration. 

 

You may repeat this step as many times as you need if your car is not moving straight or the servos have misaligned. In the next section, you will be able to put your driving to the test! For now, you can turn your car off and recharge your batteries.

Teaching tips

Step Description: In this step, learners will learn how to calibrate the servo angles of the Robot Car to ensure precise control.

You may repeat this step as many times as you need if your car is not moving straight or the servos have misaligned. In the next section, you will be able to put your driving to the test! For now, you can turn your car off and recharge your batteries.

25

Recap Assessment

15 min

Before you move on to the next section, we want to make sure you have a strong grasp of the concepts covered so far. This recap assessment is designed to review your understanding and ensure you're ready for the upcoming content. Don't worry if you don't get everything right – the purpose of this assessment is to identify areas that might need a little more focus before moving forward.

 

Question 1: Which of the following Linux commands is used to navigate to a specific directory? 

a) ls 

b) cd 

c) dir 

d) mv

 

Question 2: What action should you take if the Python player extension in VS Code doesn't work? 

a) Ignore it, the extension is not necessary for coding. 

b) Restart your computer to fix the issue. 

c) Use terminal commands to navigate to the directory and run the code. 

d) Reinstall VS Code to resolve the problem.

 

Question 3: If your robot car is not moving straight, what should you do?

a) Replace the servos with new ones. 

b) Ignore the issue, as it won't affect the car's performance. 

c) Use the provided calibration code to adjust the servos' positions.

d) Increase the speed of the car to compensate for the misalignment.

 

Question 4: Which command is used to run a Python script in the terminal? 

a) start script.py 

b) python run script.py 

c) run script.py 

d) sudo python3 script.py

 

Question 5: You have tried to connect to your car via http://hostname.local:8080/ but it doesn't work. You have already tried turning your car off and back on, as well as recharging your batteries. What should you do next? 

Check all that apply, there are multiple correct answers.

 Check that your car is connected to the same Wi-Fi network as your computer

 Try connecting from a longer distance to avoid interference

 Try reimaging your SD card

 Disassemble and reassemble the car 

 Try connecting via your computer’s terminal instead of VS Code 

 Check the troubleshooting guide

 

Question 6: Think of your robot car's code as a library with different sections for various types of books (algorithms), and the "picar-x" directory as a specific shelf in this library. If your robot car's operating system is like the management of the library, which analogy best describes the role of the VS Code interface?

A) The librarian who helps you find books. 

B) The shelves where books are organized. 

C) The library card used to check out books. 

D) The books themselves.

 

Question 7: How does an IP address aid in identifying devices on a network? 

a) By displaying a map of connected devices 

b) By assigning a unique emoji to each device 

c) By providing a unique identifier for each device 

d) By displaying the device's manufacturer information

 

Question 8-9. 

Part 1: Imagine you want to take the Robot Car home, but your home has a different Wi-Fi network than the one you used at your school. What should you do to ensure your robot car can connect to your home network?

A) Change the Wi-Fi settings of your robot car by opening its configuration file. 

B) Connect your robot car to your home network using a physical cable. 

C) Reset your robot car's IP address to match your home network's address range. 

D) Reimage your robot car's SD card with the home network's Wi-Fi credentials.

 

Part 2: True or False? If you re-image your SD card to match your home's Wi-Fi network, any files you saved on the original card will be deleted.

a) True

b) False

 

Hint: You should create a backup of your files by saving them on your computer or an external storage device.

 

Question 10: How does the Raspberry Pi contribute to building algorithms for your Robot Car?

A) It provides power to the Robot Car's motors and sensors.

B) It is a specialized algorithm-building software.

C) It is a compact computer that executes the algorithms and controls the Robot Car's actions.

D) It connects to the internet to download pre-made algorithms for the Robot Car.

 

✨Congratulations! You are done with this section and should be proud of yourself!✨

Teaching tips

This is a recap assessment designed to review learners’ understanding and ensure they are ready for Section 3, where they begin to create algorithms. Learners can only move to the next section if they receive 80% or above. Otherwise, have them retake the assessment. Answers and explanations are provided at the end for learners to review.

 

**Answer with Explanations: Allow learners to move to the next section if they receive 80% or above. Otherwise, have them retake the assessment. 

 

Question 1: b) cd

Explanation: The `cd` command in Linux is used to change the current working directory and navigate to a specific directory.

 

Question 2: c) Use terminal commands to navigate to the directory and run the code.

Explanation: If the Python player extension in VS Code doesn't work, you can navigate to the directory containing your code using terminal commands (e.g., `cd` command) and run the code using the appropriate Python command.

 

Question 3: c) Use the provided alignment tools to adjust the servos' positions.

Explanation: If the robot car is not moving straight, it might be due to misaligned servos. You should use the provided calibration code (sudo python3 calibration.py) to adjust the positions of the servos for proper alignment.

 

Question 4: d) sudo python3 script.py

Explanation: The `sudo python3 script.py` command is used to run a Python script in the terminal. 

 

Question 5: 

 Check that your car is connected to the same Wi-Fi network as your computer

 Try connecting via your computer’s terminal instead of VS Code

 Check the troubleshooting guide

 Re-image the SD card

Explanation: These actions are recommended to troubleshoot the issue of not being able to connect to the robot car. Checking the Wi-Fi connection, trying the terminal connection, and consulting the troubleshooting guide can help identify and solve the problem. You should use re-imaging as one of your last options. 

 

Question 6: A) The librarian who helps you find books.

Explanation: The VS Code interface acts as a tool that helps you navigate through your robot car's code (library) and find specific sections (algorithms) to work with, similar to how a librarian helps you find books in a library.

 

Question 7: c) By providing a unique identifier for each device**

Explanation: An IP address serves as a unique identifier for devices on a network, allowing them to be identified and located.

 

Question 8: D) Reimage your robot car's SD card with the home network's Wi-Fi credentials.

Explanation: To connect your robot car to a different Wi-Fi network, you should reimage the SD card with the appropriate Wi-Fi credentials so that the car can access the new network.

 

Question 9: a) True

Explanation: This statement is true. Re-imaging an SD card will erase all data, including files saved on the card. It's important to create a backup of your files before re-imaging.

 

Question 10: C) It is a compact computer that executes the algorithms and controls the Robot Car's actions.

Explanation: The Raspberry Pi serves as the brain of the robot car, executing the algorithms you design and controlling the car's actions based on your programming. It processes the algorithms and commands you create to make the car function as desired.

 

26

Driving the Car!

20 min

🏎️ 💨 Get your engines ready!

 

Watch the following video for guidance on completing this step! 

 

For this step, you will be driving the car manually so you can let your imagination run wild with the materials below.    

 

Feel free to explore other materials you think would add excitement and challenge to your course. Get creative with your designs and think about ways to make the course engaging and fun!

 

Take some time now to create your obstacle course. Next, you will connect to the cars to start driving. ❗Make sure you have charged your car’s batteries before proceeding to the next step.

 

Materials for your obstacle course:

 

  Traffic cones 

  Set up a challenging slalom course or create narrow passages to navigate through.

  Speed limit signs

  Designate speed zones and challenge yourself to navigate the course within the speed limits. 

 

  To create your own sign, stick the wooden dowel rod on top of the wooden craft wheel to make a stand. Then, use one of the cardstock Speed Limit signs and use tape to adhere it to the top of the dowel rod. 

  Stop signs

  Create intersections where you have to come to a complete stop and carefully proceed. 

 

 To create your own sign, stick the wooden dowel rod on top of the wooden craft wheel to make a stand. Then, use one of the cardstock Stop signs and use tape to adhere it to the top of the dowel rod. 

  Building Blocks 

  Use building blocks to make your obstacle course come to life! 

  Black tape

  Use black tape to create a line follower track. You will not need this until later.


 

It’s time to get your car moving. Use the following instructions to connect to your car. 

Remember to use the hostname and password that you gave your robot car in the step where you imaged the Raspberry Pi sd card. 

Once you’ve SSH’d into your car, take some time to drive it around your obstacle course. Have fun!

 

Connecting to Camera Feed Instructions:

  1. Turn on the car.

  2. Make sure your computer is on the same WiFi as your Robot Car.

  3. Open a Google Chrome Browser and type this into the URL: http://hostname:8080 using your hostname or IP Address. ❗️If you are using a Mac, type in http://hostname.local:8080

  4. In the terminal (Ctrl + `), type and Enter: sh run.sh  ❗️Once this program starts launching, go to step 7.

  5. If that did not work, navigate to the sidebar and open the folders:

    • picar-x

    • example

    • video_control

  6. In the top right corner of the Editor, click on the play button ▶️ to run the file. This play button is a Python extension which runs and debugs your file directly to the Raspberry Pi. 
  7. When this program starts running, you will see the following code: 
  8. Open Google Chrome. This program tells you to navigate to http://0.0.0.0:5000/ You can replace the 0.0.0.0 with your IP address or your hostname ❗️For example, http://192.168.1.45:5000/ or http://robotcar:5000
  9. Once you open up this page, you will see a live video feed from your car’s camera, like this! 

 

Go ahead and practice driving around! Use the WASD keys to move, O/P will slow down and speed up the car, and the arrow keys will move the camera.

To start color detection, choose a color flip the toggle switch at the top. To start face detection, flip the toggle switch at the top.

❗️To stop the program, press Ctrl+C on your terminal.

 


Review 🗒️

  1. How did your robot car navigate through the obstacle course? Did it encounter any difficulties or unexpected behaviors?

  2. What are some potential areas for improvement in enhancing the maneuverability or smartness of this robot car? Provide at least two suggestions and briefly explain why they would contribute to improved performance.

 


Troubleshooting 🤷

 

Go here for a full list of troubleshooting issues

Teaching tips

Step Description:

Now that their car is built, learners will test their car’s capabilities by navigating through an obstacle course! Learners will first construct their courses and connect to their car to drive manually. They will start by completing the steps to enable manual driving through an obstacle course and navigating through VS Code to interact with the Raspberry Pi. 

Feel free to add materials to your obstacle course and let students use their creativity. For example, you can add pipe cleaners and other craft supplies. 

As an option, have students submit a video recording or submit the review questions. 

 

27

The Ultrasonic Sensor

5 min

Have you ever wondered how robots can navigate their surroundings without bumping into things or crashing into other cars? One way they achieve this is by using sensors. Sensors are like the robot's eyes and ears, allowing it to gather information about its environment. One such sensor is the ultrasonic sensor.

An ultrasonic sensor is a device that uses sound waves to measure distances. It works by sending out high-frequency sound waves and then listening for the echoes when those sound waves bounce back after hitting an object. By measuring the time it takes for the sound waves to return, the sensor can calculate the distance between the robot and the object.

 

Figure 1. A visual representation of multiple ultrasonic sensors on a car. These sensors emit high-frequency sound waves, which bounce off objects and return as echoes. By analyzing the echoes, the car can determine the distance to obstacles and navigate effectively.

 

Figure 2. Tesla Model Y uses 12 ultrasonic sensors for its autopilot system. Image credit: Michael Simari, Car and Driver.

 

Several animals have natural abilities for obstacle avoidance similar to the concepts we're discussing. Here are a few examples:

  • Bats: Bats use echolocation, which is similar to the ultrasonic sensor we're using. They emit high-frequency sound waves and listen to the echoes to navigate and locate objects in their surroundings.
  • Dolphins: Dolphins also use echolocation to navigate and locate objects underwater. They emit clicking sounds and listen for the echoes to understand the location and distance of objects.
  • Birds: Birds have excellent vision and can perceive obstacles in their flight path. They adjust their flight patterns and maneuver around obstacles to avoid collisions. Oilbirds and Swiftlets can even emit clicks and use the echoes to help them navigate in total darkness.
  • Insects: Insects like bees and flies have compound eyes that allow them to detect objects and avoid obstacles while flying. They can quickly react and change their flight direction to avoid collisions.

These animals have evolved specialized sensory systems and behaviors to navigate their environments effectively and avoid obstacles. By studying and emulating their abilities, we can design robotic systems that mimic these natural mechanisms for obstacle avoidance.

 

It’s not just animals that can do this! A small number of people—mostly those blind from birth—have figured out how to create mental representations of their surroundings by making clicking sounds.

Ben Underwood was a boy who lost his eyesight at a young age due to cancer. But he didn't let that stop him. Ben learned to use echolocation by making clicking sounds and listening to the echoes to understand his surroundings. With practice, he could do things like ride a bike and play sports all by using echolocation. Ben's incredible story shows us that even when faced with challenges, we can find amazing ways to adapt and succeed.

Click on the video to watch how Ben Underwood used this amazing skill. 

 


Obstacle avoidance is crucial for the safe and efficient movement of robots. Just like we need to watch out for obstacles to avoid collisions, robots also need to detect and avoid objects in their path.

By using an ultrasonic sensor, our robot can "see" its surroundings and determine if there are any obstacles nearby. It can then adjust its movement to avoid those obstacles, making it much less likely to collide with objects and preventing potential damage.

 

Figure 1. Ultrasonic Module Distance Measuring Sonar Sensor Module. The HC-SR04 ultrasonic distance sensor is a module that allows non-contact measurement of distances ranging from 2 cm to 400 cm. It consists of an ultrasonic transmitter, a receiver, and a control circuit. The sensor module uses the time it takes for the ultrasound signal to travel to calculate the distance. By measuring the duration of the high-level signal, it can determine the distance based on the speed of sound.

 

Figure 2. Placement of Ultrasonic Sensor on fully completed Robot Car

 

Figure 3. A visual demonstration of the ultrasonic sensor using sonar for obstacle avoidance.

 


In the next step, you will activate and program the ultrasonic sensor on the Robot Car for obstacle avoidance 👉

Teaching tips

Section Description:

In this section, learners will embark on a journey of algorithm design to overcome challenges with the Robot Car. They will start by completing the steps to enable manual driving through an obstacle course and navigating through VS Code to interact with the Raspberry Pi. Additionally, they will explore Ultrasonic Sensors and Line Follower code to understand their roles in autonomous vehicles, honing their coding skills and problem-solving abilities along the way.

 

For the following lessons, you will follow this format: 

First, we will establish a clear understanding of self-driving car functionalities, such as obstacle avoidance, line tracking, and computer vision for object detection. By recognizing these parallels, we will comprehend how these features contribute to the overall performance of self-driving cars. 

Next, we will explore the code already installed in our SD cards, like the "line_tracking.py" code. Through a provided template and detailed code explanation, we will gain insight into the functions and how to control our robot car. We will then put our robot cars to the test by running them through an obstacle course, reflecting on their performance, and brainstorming ways to improve their capabilities. 

To further enhance our robot cars, we will introduce additional code that builds upon the original features. We will delve into the explanations of this new code, understanding its purpose and how it enhances the performance of our robot cars. 

Throughout the unit, we will emphasize critical thinking by engaging with pseudocode and contemplating future steps. While not requiring a background in computer science, we will encourage learners to think analytically and strategically to optimize their robot cars' functionality. 

Finally, we will conclude with a reflection, allowing learners to contemplate their journey and the skills they have developed. They will have the opportunity to share their insights, evaluate the effectiveness of the features implemented, and consider future improvements. 

By the end of this unit, learners will have explored various functionalities of self-driving cars, enhanced their robot cars' performance through code implementation, and gained valuable insights into the world of autonomous vehicles. Get ready to take your robot car on an exciting journey filled with obstacle avoidance, line following, computer vision, and much more!

 


Step Description:

In this step, students will learn about the ultrasonic sensor, which reads the distance and adjusts the car's movement autonomously based on the readings. Variables like time, direction, counters, and thresholds are used to handle different situations. In the next step, learners will activate and program the ultrasonic sensor on their robot car for obstacle avoidance. 

28

Using Obstacle Avoidance

30 min

To implement obstacle avoidance, we will write a program that uses the data from the ultrasonic sensor to guide our robot. The program will continuously read the distance measurements from the sensor and make decisions based on those measurements.

If the distance is below a certain threshold, indicating an object is too close, the program will instruct the robot to change its direction or stop to avoid the obstacle. This way, the robot can navigate around objects and continue moving forward safely.

 

⭐Let’s get started!⭐

 

In this challenge, we will show you how to read a simple program that will allow the car to use the ultrasonic sensor to avoid obstacles autonomously.

 

To find this, you will enter the workspace directory and find obstacle_avoidance.py

 

On your original obstacle avoidance file, use a number sign (#) to create comments and explain what each function does. You can also change parts of it, like the speed and distance threshold, so that it works better for your course. To stop the program, press Ctrl+C on your terminal.

 


The provided code is a basic template to start writing an obstacle avoidance program for the Robot Car. The template gives an outline of the necessary steps, and you will need to fill in the specific details to complete the program.

 

#write your import statements here

​

def main():

   try:

       #initialize your picar object and start it moving forward

 

       while True:

           #read the ultrasonic sensor data here and print it

 

           #write your driving logic here

​

   except KeyboardInterrupt:

       px.stop()

   finally:

       px.stop()

​

if __name__ == "__main__":

   main()

 

Let's go through each piece step by step. As you read each block of code, write it into your own documentation.

 

The following video runs through the code: 

❗❗ Note: We have since changed the location of the obstacle_avoidance.py file to the workspace folder and there may be some differences between this video and the template. 


 

 

Import Statements: The first part is for importing any necessary libraries or modules. You should list the import statements at the beginning of your code, depending on the sensors and functionalities you plan to use. For example, you might import the Picarx class from the SunFounder PiCar-X library and other modules like time for time-related operations.

#write your import statements here

from picarx import Picarx

import time

 

In this code, we are using a library called "picarx" to control the robot car. We import the necessary classes and functions from the library using the "from picarx import Picarx" statement.

🌟A class is like a blueprint or template that describes how an object should be created. It defines what properties an object can have and what actions it can perform. It's like having a general plan for creating things.

🌟A function, on the other hand, is like a small block of code that does a specific task. It's like a mini-program that takes some input, does some work, and gives you an output. Functions are used to perform specific operations or calculations.

To put it simply, a class is used to create objects with certain characteristics, while a function is used to perform specific tasks or operations. Classes are like the overall plan, and functions are like the individual steps you take to accomplish something.

 


main() Function: The main function is the entry point of our program. It is where you will write the main logic for your obstacle avoidance system.

def main():

   try:

       #initialize your picar object and set its speed here

       px = Picarx()

       px.forward(20)

 

Inside the main function, we create an instance of the Picarx class called "px" and set its speed to 30. We then call the "forward" method of the "px" object to start the car moving forward.

❗Pay careful attention to how code indentation is utilized to establish clear block structures. The def main(): function definition is indented, creating a new block. Everything indented directly under this block is part of the main() function's scope. If your code is not indented properly, hit the tab or backspace button to make sure it is inline with the line above it.

 


Continuous Loop: The while True: loop is responsible for running the obstacle avoidance logic repeatedly. It will continuously read the ultrasonic sensor data and perform obstacle avoidance actions.

  while True:

           #read the ultrasonic sensor data here and print it

           distance = px.ultrasonic.read()

           print("distance: ", distance)

 

Inside the while loop, we continuously read the distance from an ultrasonic sensor using the "ultrasonic.read()" method of the "px" object. We print the distance on the screen using the "print" function.

❗Pay careful attention to how code indentation is utilized to establish clear block structures. The while True: loop is indented yet again. This is like putting a box around the code inside the loop to show that it's all related to the loop. Doing this helps you understand that the loop and what's inside it are different from the rest of the code. If your code is not indented properly, hit the tab or backspace button to make sure it is inline with the line above it.

 


Driving Logic: The “write your driving logic here” comment is where you will implement the actual obstacle avoidance algorithm. Based on the distance readings from the ultrasonic sensor, you will decide how the car should steer or move to avoid obstacles. You can use conditionals (if-else statements) to control the car's actions based on the distance readings.

 #write your driving logic here

           if distance > 0 and distance < 300: 

           # Check if the distance is within a valid range

 

               if distance < 20: 

               # If the distance is less than 20, there is an obstacle nearby

                   px.set_dir_servo_angle(-45) 

                   # Adjust the servo angle to steer the car away from the obstacle

               else:

                   px.set_dir_servo_angle(0) 

                   # Keep the servo angle straight when no obstacle is detected

 

We use an if statement to check if the distance is within a valid range (between 0 and 300). If it is, we further check if the distance is less than 20. If it is, it means there is an obstacle nearby, and we adjust the servo angle of the car to steer it away from the obstacle using the "set_dir_servo_angle" method of the "px" object. Otherwise, if there is no obstacle, we keep the servo angle straight.

 

🌟When the "dir_servo_angle" is set to a negative value, it instructs the servo motor to turn or steer to the left. Conversely, when the "dir_servo_angle" is set to a positive value, it will turn to the right. Typically, the range is specified in degrees, and it can vary from -35 degrees to +35 degrees for this robot car.

 


Exception Handling: The try-except block is used for exception handling. It ensures that the car stops gracefully in case of any unexpected errors. The px.stop() function inside the except block is used to stop the car when an exception occurs.

   except KeyboardInterrupt:

       px.stop()

 

❗ Pay careful attention to how code indentation is utilized to establish clear block structures. Indenting the except block helps to distinguish it as a separate part of the code, specifically meant for handling errors.

 


Starting the Program: Finally, the if __name__ == "__main__": block is used to check if the script is run as the main program. It ensures that the main() function is called when the script is executed directly.

if __name__ == "__main__":

   main()

 

The "__name__" variable is a special variable that Python sets to "__name__" when the script is being executed directly (not imported as a module). The code under the "if __name__ == "__main__”:" block ensures that the "main" function is called when the script is run directly. Sometimes, we use a "finally" block to ensure that the car stops when the program ends, regardless of any exceptions that may occur. We call the "stop" method of the "px" object to stop the car.

 


When all is said and done, your code should look like this:

 

By filling in the missing pieces and implementing the driving logic using the ultrasonic sensor data, you will have a basic obstacle avoidance program for your robot car. You can further customize and enhance the code based on your specific requirements and sensors used. Always remember to test your code in a safe environment and make adjustments as needed for optimal performance. Happy coding!

 

from picarx import Picarx 

 

def main():

    try:

        px = Picarx() 

        px.forward(20)  

        while True:

            distance = px.ultrasonic.read()

            print("distance: ", distance)

            if distance > 0 and distance < 300: 

                if distance < 20:  

                    px.set_dir_servo_angle(-30) 

                else:

                    px.set_dir_servo_angle(0) 

    except KeyboardInterrupt:

        px.stop()

 

if __name__ == "__main__":

    main()

To stop the program, press Ctrl + C on your terminal.

 


 

The Code Explained 💡

Overall, this code controls the movement of a car based on the distance readings from an ultrasonic sensor, allowing the car to avoid obstacles and move forward.

Finally, you probably noticed that different lines of code are placed in different indentations. These are are important for the following reasons:

  • Readability: Indentation makes code easier to read and understand by visually organizing the structure and flow of the program.
  • Code organization: Indentation clarifies the hierarchy of code blocks, such as loops and conditionals, helping to identify their scope and nesting.
  • Logical execution: Indentation ensures that code is executed in the intended order, especially in conditional statements and loops.

 

Teaching tips

Step Description:

In this step, learners will activate and program the ultrasonic sensor on their robot car for obstacle avoidance. The ultrasonic sensor reads the distance and adjusts the car's movement autonomously based on the readings. Variables like time, direction, counters, and thresholds are used to handle different situations.

29

Improving Obstacle Avoidance

25 min

In the next challenge, we will show you how to add some functionality to the original code in a new file. Take a moment to break down the new code into smaller sections or blocks and read each section carefully, adding comments where it helps. Try to summarize in your own words what each section does.

 

🌟 A good way to do this is to write pseudocode. Pseudocode is a way to outline the steps of a program using plain language and simple code-like structures, like:

  1. Start the car at 10% speed while driving forward
  2. If the car is facing an obstacle 50cm away, the car will turn left at 35 degrees
  3. If the car is not facing an obstacle, the car will keep straight

 


The following video runs through the code: 

 

It may help to add a new file in the workspace directory and copy-paste the code below 👇, then add comments by using #

❗ To add a new file, click on the page + icon and give it a name, like obstacle_avoidance_2.py

 

 

from picarx import Picarx

import time

 

def main():

    try:

        px = Picarx()    

        px.forward(20) 

        while True:

            distance = px.ultrasonic.read()  

            print("distance: ", distance)  

            if distance > 0 and distance < 300:  

                if distance < 50: 

                    px.set_dir_servo_angle(-35) 

                else:

                    px.set_dir_servo_angle(0)  

                if distance < 10:  

                    px.stop()

                    time.sleep(0.5)

                    px.backward(20)

                    time.sleep(1)

                    px.set_dir_servo_angle(35)

                    px.forward(20)

            elif distance > 300:  

                    px.stop()

                    time.sleep(0.5)

                    px.set_dir_servo_angle(35)

                    px.backward(20)

                    time.sleep(1)

                    px.set_dir_servo_angle(0)

                    px.forward(20)

 

    finally:

        px.stop()  # Stop the car

 

if __name__ == "__main__":

    main()

To stop the program, press Ctrl + C on your terminal.

 


The Code Explained 💡

 

In the first code snippet, the `time` module is imported at the beginning of the code using the line `import time`. This module allows us to work with time-related functions and operations.

 

Within the code, there are several instances where the `time.sleep()` function is used. This function is used to pause the execution of the program for a specified duration, allowing us to control the timing of certain actions.

 

✅ For example, when the distance is less than 10 in the first code snippet, the following actions occur:

1. The car stops using `px.stop()`.

2. The program waits for 0.5 seconds using `time.sleep(0.5)`.

3. The car moves backward using `px.backward(20)`.

4. The program waits for 1 second using `time.sleep(1)`.

5. The servo angle is set to 35 degrees (steering to the right) using `px.set_dir_servo_angle(35)`.

6. The car moves forward again using `px.forward(20)`.

 

✅ Similarly, when the distance is greater than 300, the following actions occur:

1. The car stops using `px.stop()`.

2. The program waits for 0.5 seconds using `time.sleep(0.5)`.

3. The servo angle is set to 35 degrees (to the right) using `px.set_dir_servo_angle(35)`.

4. The car moves backward using `px.backward(20)`.

5. The program waits for 1 second using `time.sleep(1)`.

6. The servo angle is set to 0 degrees (centered position) using `px.set_dir_servo_angle(0)`.

7. The car moves forward again using `px.forward(20)`.

 

By utilizing the `time.sleep()` function, we introduce delays in the execution of the code, allowing for controlled pauses between actions. This can be useful in scenarios where precise timing or synchronization is required.

 


Did this change work for you?

Try to implement different features to make your Robot Car navigate the obstacle course. For instance, you might want to add a u-turn feature.

30

Pseudocode + Improved Code

10 min

🤔 For your final obstacle avoidance challenge, we will show you how to add more variables to improve the functionality. 

 

Read and save the following document: How to Create Pseudocode or a Flowchart for your New Program. This quick reference will show you an example of a flowchart, which helps visualize how you might implement a new algorithm:

 

In pseudocode: 

  • The flowchart starts with "Start."

  • The program measures the distance using an ultrasonic sensor.

  • The distance is shown on the screen.

  • The program checks if the distance is safe (greater than a certain value).

  • If the distance is safe, the program moves the car forward.

  • If the distance is not safe but still not dangerous (between safe and dangerous values), the program moves the car forward and slightly turns it to the right to avoid an obstacle.

  • If the distance is dangerous (too close to an obstacle), the program moves the car backward and slightly turns it to the left to avoid an obstacle.

  • The program then repeats the process of measuring the distance and adjusting the car's movement to avoid obstacles.

  • When the program is stopped or ended, it reaches the "Stop Car - End" part of the flowchart.

 


Create your own flowchart, this time incorporating the modifications you want to make to your own code and the logic (if, elif, else) you might need. You can draw your own or use a drawing feature available, like the one used here.

 

Now, we will show you how we adapted this into a Python script using logic.

 

You can find this upgraded file under the workspace folder, then open obstacle_avoidance_upgrade.py

 

from picarx import Picarx

import time

 

SafeDistance = 40   # > 40 safe

DangerDistance = 20 # > 20 & < 30 move slightly, 

                    # < 20 backward

 

def main():

    try:

        px = Picarx()

       

        while True:

            distance = round(px.ultrasonic.read(), 2)

            print("distance: ",distance)

            if distance >= SafeDistance:

                px.set_dir_servo_angle(0)

                px.forward(20)

            elif distance >= DangerDistance:

                px.set_dir_servo_angle(30)

                px.forward(20)

                time.sleep(0.1)

            else:

                px.set_dir_servo_angle(-30)

                px.backward(20)

                time.sleep(0.5)

 

    except:

        px.forward(20)

 

    finally:

        px.stop()

 

if __name__ == "__main__":

    main()

 

To stop the program, press Ctrl + C on your terminal.

 


The Code Explained 💡

 

In this code, we have introduced new functions and variables that serve specific purposes. Let's focus on understanding them:

  • SafeDistance: This variable represents the safe distance from obstacles. If the ultrasonic sensor reading is greater than or equal to this value, it indicates that the car is at a safe distance from any potential obstacles. The car will move forward in this situation.
  • DangerDistance: This variable represents a distance threshold indicating that the car is approaching a potentially dangerous situation. If the ultrasonic sensor reading falls between DangerDistance and SafeDistance, the car will turn around slightly while still moving forward. This serves as a cautious maneuver to avoid potential collisions.

By adding these two variables, the code gains flexibility and adaptability to different scenarios. These distances can be adjusted based on the specific environment or requirements. For instance, if the robot car operates in a confined space, it might need to start turning around at a closer distance to avoid collisions. These variables allow fine-tuning of the car's behavior and improve its obstacle avoidance capabilities.

The code uses an if-elif-else statement to determine the car's behavior based on the distance reading:

  • If the distance is greater than or equal to SafeDistance (40), the car moves forward at the specified power level.
  • If the distance is between DangerDistance (20) and SafeDistance (40), the car turns around slightly (steering angle set to 40) while moving forward.
  • If the distance is less than DangerDistance (20), the car moves backward while steering away from the obstacle (steering angle set to -40).

 


Review 🧠

Write a short paragraph (typically 3-5 sentences) or bullet point list and use your own words to answer these questions. You may turn this into your teacher for review.

  1. How does an ultrasonic sensor measure distance?
  2. Explain the role of the "SafeDistance" and "DangerDistance" variables in the obstacle avoidance code.
  3. How do these 3 sets of codes differ in terms of their approach to obstacle avoidance and the overall effectiveness in navigating your obstacle course?
  4. How did you modify your code to achieve better results for your obstacle course? Be specific.

Teaching tips

Step Description:

You can make this step as challenging as you want. There is a code for improved functionality that students can copy-paste. There is also a chance for students to create pseudocode, using this guide. 

 

Review Answer Key: 

  1. An ultrasonic sensor measures distance by sending out a sound wave and timing how long it takes for the wave to bounce back after hitting an object. The sensor calculates the distance based on the time taken for the wave to travel to the object and return.

  2. SafeDistance: This variable represents the distance at which the robot should consider it safe to continue moving forward without collision. DangerDistance: This variable defines the distance at which the robot should start taking corrective action to avoid an obstacle. It acts as a trigger for the obstacle avoidance behavior.

  3. The student's response should provide a brief comparison of how these aspects are addressed differently in each set of codes, highlighting their impact on obstacle avoidance and the effectiveness of navigating the obstacle course. Such responses may include: 

    1. Use of Thresholds

    2. Handling Stuck Situations 

    3. Complexity of Logic 

    4. Adaptability to Different Scenarios 

    5. Overall Effectiveness of Obstacle Avoidance 

    6. Consideration of Space/Distance in Navigation

  4. The response should provide a clear understanding of how the student identified areas for improvement, made necessary changes, and observed the impact of those changes on the car's navigation of the obstacle course.

31

Lane-Assist

20 min

We’ve learned about how self-driving cars are able to avoid crashing into obstacles. Now, let's dig deep into another aspect that is important for driverless cars on the road: Lane Assist or Lane Centering. Self-driving cars rely on a combination of cameras, radar, and LIDAR systems to maintain their position and stay within their lanes accurately.

 

Want to see what it’s like? Watch this video to experience Lane Centering Assist

 

To achieve lane centering and enable autonomous vehicles to navigate accurately, a combination of sensors is used. These sensors provide crucial information about the vehicle's surroundings and the position of the lanes. Let's take a look at the figure below for an overview of the sensors commonly used in autonomous vehicles:

 

 

It’s not just about sensors though! To achieve precise lane centering and smooth movements, autonomous vehicles rely on advanced control techniques. One such technique is Model Predictive Control (MPC).

 

This next video serves as a fantastic opportunity to witness MPC in action and gain a better understanding of how it enhances autonomous driving. You'll witness a car following a yellow path, which represents the desired trajectory. The green path showcases the car's actual movements as it utilizes MPC. Pay close attention to how the car adjusts its speed, brakes, and steering to stay on the intended path. It's fascinating to see how the car predicts and plans its movements, ensuring a seamless and comfortable ride while avoiding abrupt changes.

 

MPC is a really cool technology because it can make decisions based on what it thinks will happen in the future. It's like the car can see into the future and make choices that will lead to the best results. In the case of autonomous driving, MPC helps the car navigate its surroundings and follow the path it's supposed to take. In all, MPC is a smart way of controlling things, and it's a bit like artificial intelligence because it uses predictions and calculations to make decisions based on future states. It's an important technique in autonomous driving to make sure the car behaves just the way it should!

 


Your Robot Car does not work this way. Instead, it achieves lane following by utilizing a 3ch grayscale sensor that can detect and interpret lines on the ground.

 

 

Figure 1. The grayscale sensor module consists of 3 TCRT5000 transmitting sensors. These sensors are used for line following and edge detection. They work by emitting infrared light that is reflected back when it encounters an obstacle.

In general, the module's output readings are higher for white surfaces, lower for black surfaces, and even lower for cliffs or surfaces that do not reflect the infrared light well. The brightness of the surface affects the amount of reflection and the current generated, resulting in brighter LED indicators.

 

Figure 2. Placement of Grayscale Sensor on fully completed Robot Car

 

Figure 3. A visual demonstration of the Grayscale Sensor following a black piece of tape on a white surface.

 

To implement line following, we will write a program that uses a line follower sensor to guide our Robot Car. The program will continuously read the values from the sensor and make decisions based on those readings.

 

The line follower sensor consists of multiple infrared sensors that detect the contrast between a black line and a white surface. By analyzing the readings from the sensor, the program can determine if the car is on the line or off the line. The program will use a threshold value to determine if the sensor readings indicate that the car is on the line. If the readings fall below the threshold, it means the car has drifted off the line, and the program will instruct the car to adjust its direction accordingly.

Teaching tips

Step Description:

In this step, learners will program a robot car to follow a line using a 3-channel grayscale sensor as a "lane assist" system. The grayscale sensor will detect a line created with black tape on a white (high contrast) surface. They will utilize the grayscale readings to control the car's steering and keep it aligned with the line.

32

Using the Line-Follower

20 min

In this challenge, we will show you how to write a simple program that will allow the car to follow the line autonomously.

 

You can copy and paste the provided code onto your files in VS Code. In the following steps, we will guide you through the process of setting up the line follower sensor and programming the car to follow the line accurately. Let's get started!

 

🏁 Before you start coding for the line follower, here are some important tips:

 

🌟 Create Your Course: You will need to set up your own course using the black tape provided. Place the tape on a surface that is light in color. The contrast between the tape and the surface is crucial for the sensor to accurately read the line.

🌟 Tape Removal: Don't worry about leaving tape residue. The tape is designed to come off easily from any surface, so you can experiment and create different courses without any concerns.

🌟 Optimal Surface: For the best performance, it is recommended to use a hard and flat surface for your course. This will ensure smoother driving and better turns. However, if you don't have access to such a surface, you can create your own floor using white cardstock paper. This will provide a suitable contrast to the black tape.

🌟 Avoid sharp turns: You might have already noticed that the Robot Car’s wheels do not turn a complete 90 degrees, so it will not have the capability to make sharp turns. An effective line track will use wide curves and obtuse angles.

 

 

Remember, the goal is to build a line follower that can accurately follow the black tape on your course. By following these instructions, you will create an environment that allows the sensor to detect the line effectively, leading to better results in your coding project. Have fun creating your course and coding your line follower!

 


The following video runs through the code: 

❗❗ Note: We have since changed the location of the line_tracking.py file to the workspace folder and there may be some differences between this video and the template. 

 

To find the line follower code on VS Code, remote-ssh to your car and open the workspace directory (just like we did for obstacle avoidance.)

This time, open the line_tracking.py file.

The provided code is a basic template to start writing a line-following program for the Robot Car. The template gives an outline of the necessary steps, and you will need to fill in the specific details to complete the program.

#write your import statements here

 

if __name__ == '__main__':

# Create an instance of the Picarx object

 

# Set the speed of the car

 

   while True:

       # Get the grayscale data from the sensors and print it

 

       # Check the grayscale values to determine the line status

       # If the value of the first sensor is less than 900, indicating a black line detected on the right side

 

       # Set the servo angle to turn the car to the left

       # Move the car forward

 

       # If the value of the third sensor is less than 900, indicating a black line detected on the left side

 

       # Set the servo angle to turn the car to the right

       # Move the car forward

 

       # If the value of the second sensor is less than 900, indicating a black line detected in the center

 

       # Set the servo angle to go straight

       # Move the car forward

 

       # Pause for a short duration to control the frequency of grayscale data readings

Let's go through each piece step by step. As you read each block of code, write it into your own documentation. 

 


Import Statements: The first part is for importing any necessary libraries or modules. You should list the import statements at the beginning of your code, depending on the sensors and functionalities you plan to use. For example, you might import the Picarx class from the SunFounder PiCar-X library and other modules like time for time-related operations.

#write your import statements here

from picarx import Picarx

import time

In this code, we are using a library called "picarx" to control the Robot Car. We import the necessary classes and functions from the library using the "from picarx import Picarx" statement.

 

🌟A class is like a blueprint or template that describes how an object should be created. It defines what properties an object can have and what actions it can perform. It's like having a general plan for creating things.

🌟A function, on the other hand, is like a small block of code that does a specific task. It's like a mini-program that takes some input, does some work, and gives you an output. Functions are used to perform specific operations or calculations.

To put it simply, a class is used to create objects with certain characteristics, while a function is used to perform specific tasks or operations. Classes are like the overall plan, and functions are like the individual steps you take to accomplish something.

 


main() Function: The main function is the entry point of our program. It is where you will write the main logic for your line-tracker system.

if __name__ == '__main__':

 

    # Create an instance of the Picarx object

    px = Picarx()

  # Set the speed of the car

    px.speed = 10 

 

Inside the main function, we create an instance of the Picarx class called "px" and set its speed to 10. ❗ Pay careful attention to how code indentation is utilized to establish clear block structures.

 


Continuous Loop: The while True: creates an infinite loop that continuously performs the line-following behavior until the program is interrupted.

 while True:

 

        # Get the grayscale data from the sensors and print it

        gm_val_list = px.get_grayscale_data()

        print("gm_val_list:", gm_val_list)

  • gm_val_list = px.get_grayscale_data(): This retrieves the grayscale data from the sensors and stores it in the gm_val_list variable.
  • print("gm_val_list:", gm_val_list): This line prints the grayscale data for debugging or monitoring purposes.

 

❗Pay careful attention to how code indentation is utilized to establish clear block structures. The rest of the code will be inside this continuous loop.

 


Driving Logic: This code is designed to navigate the car using grayscale values from line sensors to detect and follow a black line on the ground. The car adjusts the servo angle and movement direction based on the position of the detected line relative to the car.

 

The logic is as follows:

 

Check Line Status: The code checks the grayscale values from line sensors to determine the position of the black line in relation to the car.

Right Line Detection: If the value of the first sensor (right side) is less than 900, it indicates a black line detected on the right side:

  • Set the servo angle to turn the car to the left (-35)
  • Move the car forward

Left Line Detection: If the value of the third sensor (left side) is less than 900, it indicates a black line detected on the left side:

  • Set the servo angle to turn the car to the right (35)
  • Move the car forward

Center Line Detection: If the value of the second sensor (center) is less than 900, indicating a black line detected in the center:

  • Set the servo angle to go straight (0)
  • Move the car forward

Control Frequency: After each reading, the code pauses for a short duration (0.1 seconds) to control the frequency of grayscale data readings, ensuring a smoother response.

 

        # Check the grayscale values to determine the line status

        # If the value of the first sensor is less than 900, indicating a black line detected on the right side

        if gm_val_list[0] < 900:

 

            # Set the servo angle to turn the car to the left

            # Move the car forward

            px.set_dir_servo_angle(-35) 

            px.forward()  

 

        # If the value of the third sensor is less than 900, indicating a black line detected on the left side

        elif gm_val_list[2] < 900:

 

            # Set the servo angle to turn the car to the right

            # Move the car forward

            px.set_dir_servo_angle(35)  

            px.forward()  

 

        # If the value of the second sensor is less than 900, indicating a black line detected in the center

        elif gm_val_list[1] < 900:

 

        # Set the servo angle to go straight

        # Move the car forward

            px.set_dir_servo_angle(0)  

            px.forward()  

 

   # Pause for a short duration to control the frequency of grayscale data readings

        time.sleep(0.1)

 

❗ Pay careful attention to how code indentation is utilized to establish clear block structures. 

 


When all is said and done, your code should look like the code below 👇

 

By filling in the missing pieces and implementing the driving logic using the grayscale sensor data, you will have a basic line follower program for your Robot Car.

 

Run this code a few times and write down notes about its functionality and effectiveness. What does it do right? What does it do wrong?

 

You can further customize and enhance the code based on your specific requirements of your track. Always remember to test your code in a safe environment and make adjustments as needed for optimal performance. Happy coding! 💻

from picarx import Picarx

import time

 

if __name__ == '__main__':

    px = Picarx()

    px.speed = 10  

 

    while True:

        gm_val_list = px.get_grayscale_data()

        print("gm_val_list:", gm_val_list)

 

        if gm_val_list[0] < 900:

            px.set_dir_servo_angle(-35)  

            px.forward()  

 

        elif gm_val_list[2] < 900:

            px.set_dir_servo_angle(35) 

            px.forward()  

 

        elif gm_val_list[1] < 900:

            px.set_dir_servo_angle(0)  

            px.forward()  

 

        time.sleep(0.1)

 

To stop the program, press Ctrl + C on your terminal.

 


The Code Explained 💡

 

The main loop for line-following behavior:

  • while True: This creates an infinite loop that continuously performs the line-following behavior until the program is interrupted.

 

  • Getting grayscale data and determining line status. The Grayscale_Module library is used to read grayscale data from the three sensors:
    • gm_val_list = px.get_grayscale_data(): This retrieves the grayscale data from the sensors and stores it in the gm_val_list variable.
    • print("gm_val_list:", gm_val_list): This line prints the grayscale data for debugging or monitoring purposes.
    • The following conditions check the grayscale values to determine the line status:
      • If the value of the first sensor (right side) is less than 900, it indicates a black line detected on the right side.
      • If the value of the third sensor (left side) is less than 900, it indicates a black line detected on the left side.
      • If the value of the second sensor (center) is less than 900, it indicates a black line detected in the center.

 

  • Taking actions based on the line status:
    • Depending on the line status determined by the grayscale values, the code sets the servo angle and moves the car accordingly to follow the line.
    • The servo angle is set using px.set_dir_servo_angle() with values of -25 (left), 25 (right), or 0 (straight).

 

  • Adding a delay:
    • time.sleep(0.1): This adds a short delay of 0.1 seconds to control the frequency of grayscale data readings and line-following actions.

 

Summary: The code continuously reads grayscale data, determines the line status based on the grayscale values, and adjusts the car's direction accordingly to follow the line.

33

Improving Line-Follower

20 min

For this next code, try to analyze the changes we made to the code in the last step and write it into pseudocode or a flowchart. Then, we will give you the same code but with comments to help you understand it.

 

You can find this file under the workspace folder, then open line_tracking_upgrade.py. ❗Hint: Pay attention to the “outHandle”

 

from picarx import Picarx

from time import sleep

 

px = Picarx()

 

px.set_grayscale_reference(1400)

 

last_state = None 

current_state = None 

px.speed = 10

offset = 20 

 

def outHandle():

    global last_state, current_state

 

    if last_state == 'left':

        px.set_dir_servo_angle(-30)  

        px.backward() 

 

    elif last_state == 'right':

        px.set_dir_servo_angle(30) 

        px.backward()  

 

    while True:

        gm_val_list = px.get_grayscale_data()  

        gm_state = px.get_line_status(gm_val_list) 

        print("outHandle gm_val_list: %s, %s" % (gm_val_list, gm_state))

        currentSta = gm_state

 

        if currentSta != last_state:

            break

 

    sleep(0.001) 

 

if __name__ == '__main__':

    try:

        while True:

            

            gm_val_list = px.get_grayscale_data()

            gm_state = px.get_line_status(gm_val_list)

            print("gm_val_list: %s, %s" % (gm_val_list, gm_state))

           

            if gm_state != "stop":

                last_state = gm_state

            if gm_state == 'forward':

                px.set_dir_servo_angle(0)

                px.forward()

 

            elif gm_state == 'left':

                px.set_dir_servo_angle(offset)

                px.forward()

            elif gm_state == 'right':

                px.set_dir_servo_angle(-offset)

                px.forward()

            else:

                outHandle()

    except:

        

        px.stop()

 


💡 Updated code with comments: 

from picarx import Picarx

from time import sleep

 

px = Picarx()

 

# Set the grayscale reference value to 1400

px.set_grayscale_reference(1400)

 

# Initialize variables

last_state = None #Variable to store the previous line-following state

current_state = None # Variable to store the current line-following state

px.speed = 10

offset = 20 #Offset value for steering the car (adjust as needed)

 

# Function to handle the "out" state

def outHandle():

    global last_state, current_state

 

    # Check if the previous state was "left"

    if last_state == 'left':

        px.set_dir_servo_angle(-30)  # Set the servo angle to -30 degrees for a left turn

 

        px.backward()  # Move the car backward

 

    # Check if the previous state was "right"

    elif last_state == 'right':

        px.set_dir_servo_angle(30)  # Set the servo angle to 30 degrees for a right turn

        px.backward()  # Move the car backward

 

    # Continuously check the grayscale data until the state changes

    while True:

        gm_val_list = px.get_grayscale_data()  # Get the grayscale data from the sensors

        gm_state = px.get_line_status(gm_val_list)  # Determine the line status based on the grayscale data

        print("outHandle gm_val_list: %s, %s" % (gm_val_list, gm_state))

        currentSta = gm_state

 

        # Break the loop if the line state changes

        if currentSta != last_state:

            break

 

    sleep(0.001)  #Introduce a smaller delay

 

# Entry point of the program

if __name__ == '__main__':

    try:

        # Run the main loop indefinitely

        while True:

            # Get grayscale data from the sensor

            gm_val_list = px.get_grayscale_data()

            

            # Get the current line status

            gm_state = px.get_line_status(gm_val_list)

            

            # Print grayscale data and line status

            print("gm_val_list: %s, %s" % (gm_val_list, gm_state))

 

            # Update last_state if the line state is not "stop"

            if gm_state != "stop":

                last_state = gm_state

 

            # Execute actions based on the line state

            if gm_state == 'forward':

                px.set_dir_servo_angle(0)

                px.forward()

            elif gm_state == 'left':

                px.set_dir_servo_angle(offset)

                px.forward()

            elif gm_state == 'right':

                px.set_dir_servo_angle(-offset)

                px.forward()

            else:

                outHandle()

    except:

        # Stop the car after exiting the loop

        px.stop()

 


🤔 Let's compare the two complete code snippets provided.

 

The original code (line_tracking.py) attempts to follow a black line using grayscale data, while the second one (line_tracking_upgrade.py) seems to have some improvements. What are the key differences you notice between them?

 

In the first code, the line-following logic is based on conditions for forward, left, and right movements. However, it lacks robust turning capability and doesn't handle scenarios when the line is lost. The second code, on the other hand, sets a grayscale reference, includes a function to handle line loss, and adjusts the servo angle for more precise turns.

 

What does setting a grayscale reference do?

 

The grayscale reference value is used as a point of comparison. The line sensor readings are compared to this reference value to determine whether they indicate the presence of the black line or the absence of the line (white background). By setting a reference value, you can adjust the sensitivity of the grayscale module to detect the black line accurately. In the first code snippet, the line px.set_grayscale_reference(1400) is not present.

 

What is the purpose of the outHandle() function in the code? How does it contribute to the line-following behavior?

 

The outHandle() function handles the situation when the car goes off the line. It adjusts the car's direction based on the previous state ('left' or 'right') and then continues checking the grayscale data until the line is detected again. This helps the car recover and reacquire the line when it goes off-track. The code also adjusts the servo angle based on the line status, providing more accurate turns and better line-following capability.

 

What modifications would you suggest to enhance the second code?

Teaching tips

You might be wondering where we go from here. Obviously there is better code, but as a teacher, you might want to challenge students before moving forward. We want to give students the tools to update their program by thinking about the best approach, and thus flowcharting and pseudocode come in handy. 

 

Flowcharting in code refers to visually representing the logical flow and structure of a program using symbols and diagrams. It helps programmers to visualize the sequence of steps, decision points, and actions in their code like input/outputs, conditionals, and more. In other words, flowcharting is like drawing a picture that shows the steps and decisions in a program. It helps programmers plan and understand how their code works, using different shapes and arrows to represent different parts of the program.

 

Overall, flowcharting in code is a valuable technique that promotes better planning, understanding, and communication in software development. It provides a high-level overview of the program's structure and flow, aiding in efficient coding and problem-solving. This document is a quick reference that helps visualize how you might implement a new algorithm.

 

These flowcharts are examples meant to help tackle the issue when the Robot Car loses the line. 

 

 

Optional Challenge Prompts: 

  1. What are some key distinctions between the line-following code you adapted for your Robot Car and what a fully functional self-driving car would need for lane assist? Compare their strengths, limitations, and performance in various driving scenarios.
  2. Investigate different lane detection approaches for self-driving cars, considering the complexity and diversity of sensors, understanding of the environment, localization and mapping, decision-making and planning, safety or legal considerations, or deep learning and artificial intelligence. 
  3. Use reliable online resources to dive deeper into this topic, such as Arxiv, Google Scholar, articles from the IEEE Xplore Digital Library, Towards Data Science, Medium, and more. 
34

Machine Learning

30 min

This next project will enter the field of Computer Vision 👀

 

You will understand the basics of machine learning to train their Robot Car to recognize images, such as a stop sign, with Google’s Teachable Machine.

 

This project covers the fundamentals of machine learning, a branch of artificial intelligence (AI) which uses data and algorithms to train a machine to imitate intelligent human behavior.

 

Below is a list of just a few ways humans use machine learning. Can you think of any more?

  • Facial recognition
  • Social media monitoring
  • Marketing and advertising
  • Self-driving cars Reading handwriting from phones
  • Virtual assistants (Siri, Alexa, etc)
  • Customer service chat bots
  • Planning out the fastest route to a destination
  • New song recommendations
  • Farmers checking out crops to diagnose problems
  • Clinical decision support and robotic assistance for medical procedures

 

 

Let’s test it out so you can see for yourself. Use this link to direct you to Google’s Machine Learning App and take notice of each step.

How accurate was the app and why?

What do you think would make the learning app better at classifying images?

You will be able to answer these questions by the end of this lesson series.

 


Let’s highlight the basic steps to machine learning.

 

  1. Collecting data – Machines learn from the data you give them. The quality of data you feed the machine will determine the accuracy. What could be a good source of data for training AI?

  2. Preparing the Data – You can do this by removing unwanted data, randomizing the data so the ordering does not affect the learning process, visualizing it so you better understand how the data is structured and being represented, and splitting the data between a training set and a testing set. The training set uses the samples your model learns from. The testing set is used to check the accuracy of your training model.

  3. Choosing a Model – This determines the output you get after running the training data. Scientists and engineers have developed various models suited for different tasks like speech recognition, image recognition, prediction, etc.
  4. Training the model – This is when you pass the prepared data to your machine learning model to find patterns and make predictions. With more training and more data, the model gets better at predicting.
  5. Evaluating the model – Test the performance of the model with entirely new, unseen data.
  6. Parameter Tuning – Parameters are the variables (changes) in the model that the programmer decides. Tuning the parameter’s values may increase the accuracy.
    • Epochs – The total number of times your data will be fed through the training model. Therefore, in 10 epochs, the dataset will be fed through the training model 10 times. Increasing the number of epochs can often lead to better performance.
    • Batch Size – The size of the set of samples that will be used in one step. For example, if you have 160 data samples in your dataset, and you have a batch size of 16, each epoch will be completed in 160/16=10 steps. You’ll rarely need to alter this hyperparameter.
    • Learning Rate – It dictates the speed at which your model updates the weights after iterating through a step. Even small changes in this parameter can have a huge impact on the model performance. The usual range lies between 0.001 and 0.0001.
  7. Making Predictions – Apply your model on new data to predict the likelihood of a particular outcome. How accurate would the machine learning app you used be on data from your own photos?

 


Now that you have a basic understanding of machine learning, let’s do the steps to train your car so that it can learn objects in your course.

 

You will be receiving these images to put on your course:

To create your own sign, stick the wooden dowel rod on top of the wooden craft wheel to make a stand. Then, use one of the cardstock signs and use tape to adhere it to the top of the dowel rod, like this:

 

 


You won’t need your car yet. This will show you how to use Google’s Teachable Machine to train your images and export it into a .tflite file so you can use it in your code. 

 

The following video details the written instructions below: 

 

Written Instructions

  1. Go to https://teachablemachine.withgoogle.com/train and select Image, then Standard.

  2. Rename your first class to the image you want to teach the car, such as a stop sign.

  3. Hold up your sign in front of the webcam and press the "Hold to Record" button, or upload an image you found online or saved on your computer.
  4. Take 20-30 samples from many different angles and proximities.
  5. Repeat steps 2-4 for additional images, making sure to add a new class for each one.
  6. Click "Train Model" and wait.
  7. Test the model under "Preview" and "webcam" or import a new image.

 

💡 Once the training is complete, the resulting image classification model is ready for use.


 

Teachable Machine provides a link or embed code that you can use to integrate the trained model into your applications or projects. To export your model, select the Tensorflow Lite tab and select Quantized, then download the model.

 

❗ Downloading the model will give you two files when you unzip the folder: one txt file and the other a tflite file.

 

 

The TXT file usually contains the class labels or categories used for image classification. Each line in the file corresponds to a class, and the class names are often human-readable labels that help identify the objects or entities the model is designed to recognize. For example, in an image classification model for recognizing animals, the TXT file may contain lines like "cat," "dog," "bird," etc. This file is essential for interpreting the model's output and mapping numeric class identifiers to meaningful class names.

 

The Tensorflow (TF) Lite file is the actual trained machine learning model in a compact, optimized format. When you deploy an image classification model using TensorFlow Lite, the file is loaded into the target device's memory, and the image data is passed through the model for inference. The model processes the input image and generates output probabilities or scores for each class specified in the TXT file. The class with the highest score is considered the model's prediction for the given input image.

 

In other words, imagine the model is like a brain that looks at pictures and tries to figure out what's in them. When you show it a picture, it thinks about what objects or things could be in that picture. It gives each possible object a score or a probability, which tells how likely it thinks that object is in the picture. The model looks at the picture, guesses what things are in it, and tells you what it thinks is the most likely thing in that picture based on the scores it calculates.

 


Find the Image Classification on VS Code, remote-ssh to your car and open the workspace folder.

 

Steps to SSH-Connect to Robot Car

  1. Turn on the car.

  2. Make sure your computer is on the same WiFi as your Robot Car.

  3. Open a Google Chrome Browser and type this into the URL: http://hostname:8080 using your hostname or IP Address.
    • ❗️If you are using a Mac, type in http://hostname.local:8080. For example, your hostname may look like robotcar.local (or robotcar1.local if using a classroom router).
  4. In the workspace directory, open the image classification file. 
  5. Next, drag and drop the files downloaded from your machine learning model into your workspace folder and rename them as needed. 
  6. Then, right-click or cmd-click and select 'Copy Path' 
  7. Paste this Path onto the Image Classification code in the lines where it reads ‘labels_path.’ Repeat the same step for the .tflite file and the model_path. The .txt file replaces the labels path and the .tflite file replaces the model path. 
  8. Once ready, run the code and put one of your images in front of your Robot Car’s camera. You will see something like this on your terminal: 

 

You must quit the program to restart with a new image. To stop the program, press Ctrl + C on your terminal.

 

When the computer returns this in the terminal, it means that the image classification model has analyzed an input image (or a frame from the camera feed in this case) and has made a prediction.

 

Let's break down the output:

  • 2: This is the class index or label index of the predicted class. In this case, the model has predicted class index 2. You might recall seeing this in the text file.
  • Right Turn: This is the label associated with class index 2. It represents the predicted class, which is "Right Turn" in this case.
  • 0.8994467: This is the confidence score or probability associated with the prediction. It indicates the model's confidence in its prediction. In this case, the model is quite confident with a probability of approximately 0.899 (or 89.9%) that the input image belongs to the class "Right Turn."

 

Overall, the meaning of the output is that the image classification model has identified the input image as a "Right Turn" with a high confidence score of 0.899 (or 89.9%).

 


You can find more machine learning models that have a lot more diverse set of object classes, such as this one: Mobilenet_V1_1.0_224_quant

 

Repeat the previous steps with this file and see what else your car can identify.

 


Review 🧠

  1. How does the experience of building and training a machine learning model enhance your understanding of artificial intelligence and its applications in various industries?

 

  1. Did this lesson spark your interest in pursuing a career related to machine learning, computer vision, or artificial intelligence? If so, what specific roles or industries are you now considering?

 

  1. How might you use Google’s teachable machine, or any other machine training model, to enrich your life? You can also try it with sounds and poses. 

            For example, if you like to watch birds, you could train a model to identify bird calls. 

 

  1. How does machine learning create bias, and what are some potential ways to address this issue? Hint: Think about the sources of bias in machine learning, such as biased training data and labeling, and consider how these biases can be unintentionally encoded into the model's behavior. Also, explore possible solutions and strategies to mitigate bias, such as diverse and representative data collection, fairness-aware algorithms, and ongoing monitoring of model performance for biases.

Teaching tips

Section Description:

In this section, learners will delve into the fascinating world of machine learning as they train their Robot Car to recognize objects using their own images. They will grasp the fundamentals of machine learning and explore its diverse applications. Learners will experiment with Google's Teachable Machine for image recognition and export their trained models. By integrating the machine learning models into the Robot Car's code, they will witness their Car's enhanced capabilities in image classification and object detection. 

35

Object Detection

18 min

Object recognition, a fundamental task in computer vision, involves identifying and classifying objects within images or videos. With the development of deep learning, significant progress has been made in this field, revolutionizing the way computers perceive and understand visual information. In this gentle introduction, we explore the basics of object recognition using deep learning, shedding light on the key concepts and techniques that enable computers to "see" and recognize objects in the digital world.

 

 

You might be wondering, what do AI and object detection have to do with the things we love?

 

Imagine you're watching a basketball game, and AI-powered cameras are intelligently tracking players' moves, analyzing their shooting techniques, and providing real-time insights to coaches and fans. It's like having a virtual coach right on the court! Or picture scrolling through Instagram, and the app automatically recognizes your friends' faces, suggesting you tag them in photos effortlessly. This is all thanks to the marvels of object detection.

 

From the thrill of the sports arena to the vibrant world of social media, object detection is revolutionizing our experiences, making them more interactive and personalized. Whether you're a sports fanatic, a selfie enthusiast, or simply curious about the tech that shapes our digital lives, this journey has something exciting in store for you.

 


What is Object Detection? 🤔

 

Have you ever wondered how computers can "see" and recognize objects in images or videos, just like we do? It's all thanks to a fascinating process called object detection, also known as object recognition. Imagine being able to identify and locate specific objects, like cars, animals, or faces, within pictures or video frames.

 

Object detection is a computer vision task that involves identifying and localizing multiple objects within an image or video frame. The goal is to not only recognize what objects are present but also precisely determine where they are located in the image. This goes beyond traditional image classification, which identifies a single object class in an image.

 

 

For instance, take a look at the image on the left in Figure 1. Thanks to an advanced AI system known as a Convolutional Neural Network (CNN), the computer can tell that it's a "beagle." But object detection goes beyond simple recognition. It can also pinpoint the exact location of each object. In Figure 1 on the right, you can see how both the person and the dog are identified and localized with bounding boxes and class labels.

 


 

The Rise of Deep Learning 📖

 

This incredible ability of computers to "see" is made possible by a revolutionary approach called deep learning. Unlike traditional algorithms, deep learning models, inspired by the human brain, learn directly from raw data.

 

The illustration below represents the hierarchy of artificial intelligence. At the core, AI represents the broader field of creating intelligent systems. Within AI, we find Machine Learning (ML), a subset focusing on algorithms that enable computers to learn from data. Inside ML, we encounter Deep Learning (DL), a specialized approach using deep neural networks for complex pattern recognition.

 

Want to dive deeper into the realm of object detection? Check out this link for more information: https://pyimagesearch.com/2018/05/14/a-gentle-guide-to-deep-learning-object-detection/

 


💡 Now it’s time to find the object detection on VS Code:

 

Steps to SSH-Connect to Robot Car

 

  1. Turn on the car.
  2. Make sure your computer is on the same WiFi as your Robot Car.
  3. Open a Google Chrome Browser and type this into the URL: http://hostname:8080 using your hostname or IP Address.
    • ❗️If you are using a Mac, type in http://hostname.local:8080. For example, your hostname may look like robotcar.local (or robotcar1.local if using a classroom router).
  4. Open the vilib folder, then examples.
  5. In the vilib directory, open the objects_detection.py file.
  6. Run the python file and you should see the following: 
  7. Next, you will see this in the terminal: 

    Running on: http://192.168.1.45:5000/

     * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

     

  8. Open a Google Chrome Browser and type this into the URL: http://hostname:5000 using your hostname or IP Address.

    • ❗️For example, your hostname may look like robotcar.local (or robotcar1.local if using a classroom router).If you are using a Mac, type in  http://hostname.local:5000

  9. Once you open up this page, you will see a live video feed from your car’s camera performing object detection! 

Have fun driving around and observing how computer vision works! 

 


Troubleshooting  🤷

 

If you are experiencing issues where your Robot Car is not running object detection, try this:

❗Before following these steps, save and back up your files to a folder in your computer or flash drive since you will lose them on the SD card.

 

1. In your terminal, type and enter: 

sudo rm -r picar-x

2. Then, type and enter: 

sudo rm -r vilib

 

Performing these actions will erase the two directories. Now, we will clone a new, updated copy from the code creator on github. 

 

3. Type and enter: 

git clone https://github.com/justinbetabox/picar-x.git

4. Do the same thing with the vilib folder:

git clone https://github.com/justinbetabox/vilib.git

5. Now, you will re-install the robot-hat directory. Just copy and paste this into your terminal and press Enter.

cd /home/pi/

git clone https://github.com/sunfounder/robot-hat.git

cd robot-hat

sudo python3 setup.py install

 

The following instructions can also be found here: https://docs.sunfounder.com/projects/picar-x/en/latest/python/python_start/install_all_modules.html?highlight=setup.py

 

Running setup.py will download some necessary components. Your download may have failed due to network issues. You may need to download again at this point. See the following interface, type Y and press Enter.

6. Then download and install the vilib module.

cd /home/pi/

git clone https://github.com/sunfounder/vilib.git

cd vilib

sudo python3 install.py

7. Then download and install the vilib module.

cd /home/pi/

git clone https://github.com/sunfounder/vilib.git

cd vilib

sudo python3 install.py

8. Download and install the picar-x module.

cd /home/pi/

git clone -b v2.0 https://github.com/sunfounder/picar-x.git

cd picar-x

sudo python3 setup.py install

This step will take a little while, so please be patient.

 

8. Finally, you need to run the script i2samp.sh to install the components required by the i2s amplifier, otherwise the picar-x will have no sound.

cd /home/pi/picar-x

sudo bash i2samp.sh

9. Type y and press enter to continue running the script.

10. Type y and press enter to run /dev/zero in the background.

 

11. Type y and press enter to restart the Picar-X.

❗ Note: If there is no sound after restarting, you may need to run the i2samp.sh script several times.

 

12. Go back to the workspace folder and run object_detection.py again. You should get something that looks like this after you put an object in front of the Robot Car’s camera:

 


Review 🧠

Take some time to answer these questions in your own words. 

 

  1. What is object detection, and why is it important in robotics and computer vision?

  2. How does object detection benefit autonomous systems like robot cars? 

  3. Can you suggest any improvements or modifications to enhance the object detection capabilities of your robot car?

  4. How might object detection be used in fields other than robotics, such as healthcare or security? Give an example of a real-world scenario where object detection can make a significant impact.

  5. Can you think of any ethical issues or considerations related to object detection technology?

  6. Are there any specific projects or applications you'd like to develop using object detection?

 


Congrats on being done with this section on Computer Vision! 

 

Teaching tips

Step Description:

In this step, we delve into the fascinating world of object detection powered by deep learning. Object detection involves identifying and precisely locating multiple objects within images or video frames. We explore the significance of artificial intelligence (AI) and its impact on various aspects of our lives, from sports analytics to social media. Deep learning, specifically Convolutional Neural Networks (CNNs), is introduced as the driving force behind computer vision, enabling computers to "see" and recognize objects. This foundation sets the stage for hands-on exploration and implementation of object detection in the practical exercises.

 

Optional Review - Answer Key 

  1. Object detection helps robots and computers see and find things in pictures or videos.Object detection allows robots to interact with their environment intelligently and make informed decisions.

  2. Object detection helps robot cars see, recognizing and avoiding objects in their path. This keeps them safe and helps them drive on their own by following traffic rules and avoiding crashing into things.

  3. Allow students to come up with their own suggestions, like: 

    • upgrading the camera sensor for higher resolution and better image quality

    • implementing advanced deep learning models for improved accuracy 

    • integrating additional sensors like LiDAR or radar

  4. Allow students to research and come up with their own suggestions, like: 

    • In healthcare, it can be used to identify and locate anomalies in medical images, such as detecting tumors in X-rays or MRI scans.

    • In security, object detection can be employed for video surveillance to recognize unauthorized access or suspicious activities. 

  5. Allow students to research and come up with their own suggestions, like: 

    • privacy concerns when used in surveillance

    • potential biases in the training data leading to discriminatory outcomes

    • and the responsible use of object detection in sensitive areas like healthcare or law enforcement

  6. Answers may vary. Students can express their interests in specific projects or applications they would like to explore using object detection. These could include developing a smart home security system, creating an autonomous delivery robot, or building an object recognition app for visually impaired individuals, among others.

36

Playing Music

10 min

In this exciting mini lesson, you will learn how to access and create music using Python on your robot car. First, let's get started by exploring the "robot_hat" directory, which holds the music.py file that will guide us through all the music-related fun!

 

Steps to SSH-Connect to Robot Car

  1. Turn on the car. 

  2. Make sure your computer is on the same WiFi as your Robot Car.

  3. Open a Google Chrome Browser and type this into the URL: http://hostname:8080 using your hostname or IP Address.

    • ❗️If you are using a Mac, type in  http://hostname.local:8080. For example, your hostname may look like robotcar.local (or robotcar1.local if using a classroom router).

  4. Navigate to the robot_hat directory, and inside that, open robot-hat.py.

  5. Open the "music.py" file, which is your ticket to the world of music and sounds.

     

Let's take a look at the music.py file to understand what it does and how it helps us create music and sound effects on our robot car. Make sure you don’t make any changes to this file.

 


The music.py file is like a treasure chest filled with all the tools we need to play music and sound effects. It's a special Python file that provides us with pre-built functions, just like how a music conductor directs an orchestra!

 

Here's a breakdown of some important parts of the "music.py" file:

 

  • Importing Libraries: At the beginning of the file, we see some lines of code that start with "import." These lines bring in special "libraries" or "modules" that provide additional features for our music. For example:

    import pygame

    import time

    import threading

    import pyaudio

    import numpy as np

    import os

These libraries have different purposes, like helping us play music, handle time, and even generate musical tones!

 

  • Defining the Music Class: The file defines a special class called "Music." Think of a class as a blueprint that helps us create objects with specific abilities. In this case, the "Music" class helps us create an object that can play music and sound effects. 
  • Properties and Constants: Inside the "Music" class, we see some properties and constants, like "MUSIC_BEAT" and "MUSIC_DIR." These properties hold important values that help us control aspects of our music, such as the tempo (speed) of the music and the directory where our music files are stored.
  • Helper Functions: The "Music" class also contains some helpful functions that make our music experience smooth and enjoyable. For example, we have functions like "note," "beat," and "tempo." These functions help us convert musical notes, set the beat duration, and adjust the tempo of our music.
  • Music and Sound Effect Functions: The file provides us with functions to play music and sound effects. For example:

def sound_effect_play(self, file_name):

    # Play a sound effect from the given file_name.

    # ...

 

You can even see all the tones that the speaker is able to make: 

To understand this a little better, we’ve created a reference document that maps out the note with its corresponding frequency (in Hertz).

  • Musical notes have names like A, B, C, D, etc.
  • Each note can be "higher" or "lower" than another note, and we measure this difference in "semitones."
  • A higher note has a higher frequency (it sounds higher-pitched).

 

The frequency of a musical note directly reflects its pitch. In music and sound, pitch is the perceived highness or lowness of a note. The increasing pitch and frequency correspond with these notes:

  • A higher-pitched note has a higher frequency in Hertz (Hz). For example, A4 has a frequency of 440 Hz and is perceived as a relatively high-pitched note.
  • Conversely, a lower-pitched note has a lower frequency in Hertz. For example, A3 has a frequency of 220 Hz and is perceived as a lower-pitched note than A4.

 


Now, let's navigate back to the picarx -> example folder. Open the sound_test.py file to see the template.

from robot_hat import Music #importing music module

 

player = Music() #create music object named player

 

song = '/home/pi/picar-x/sounds/car-double-horn.wav' #load in sound effect that is saved in robot-hat directory

 

player.sound_effect_play(song) #play sound effect



player.play_tone_for(player.note('C4'), player.beat(0.5)) #plays a tone that is declared by player.note and player.beat

 

Create a new file in the workspace directory. In a new file, use the template from the sound_test.py file to create notes with a ‘sleep’ component, so that there can be a pause in between notes. What do you think you need to do?

 


Here, we have imported time and time.sleep() for any number of seconds. 

 

from robot_hat import Music

import time

 

player = Music() #create music object named player

player.play_tone_for(m.note('C5'),m.beat(0.5)) # Replace 'Middle C' with the desired note and 0.5 with the desired beat duration

time.sleep(0.5) # pause for half a second (0.5 seconds) before proceeding to the next line of code.

 

 

With these functions, we can create all types of songs, like “Twinkle Twinkle Little Star”

 

from robot_hat import Music

import time

 

m = Music()  # Create a music object named m

 

# Twinkle, Twinkle, Little Star melody

m.play_tone_for(m.note('C4'), m.beat(1))

m.play_tone_for(m.note('C4'), m.beat(1))

time.sleep(0.25)

 

m.play_tone_for(m.note('G4'), m.beat(1))

m.play_tone_for(m.note('G4'), m.beat(1))

time.sleep(0.25)

 

m.play_tone_for(m.note('A4'), m.beat(1))

m.play_tone_for(m.note('A4'), m.beat(1))

time.sleep(0.25)

 

m.play_tone_for(m.note('G4'), m.beat(2))

 

m.play_tone_for(m.note('F4'), m.beat(1))

m.play_tone_for(m.note('F4'), m.beat(1))

time.sleep(0.25)

 

m.play_tone_for(m.note('E4'), m.beat(1))

m.play_tone_for(m.note('E4'), m.beat(1))

time.sleep(0.25)

 

m.play_tone_for(m.note('D4'), m.beat(1))

m.play_tone_for(m.note('D4'), m.beat(1))

time.sleep(0.25)

 

m.play_tone_for(m.note('C4'), m.beat(2))

 

m.play_tone_for(m.note('G4'), m.beat(1))

m.play_tone_for(m.note('G4'), m.beat(1))

time.sleep(0.25)

 

m.play_tone_for(m.note('F4'), m.beat(1))

m.play_tone_for(m.note('F4'), m.beat(1))

time.sleep(0.25)

 

m.play_tone_for(m.note('E4'), m.beat(1))

m.play_tone_for(m.note('E4'), m.beat(1))

time.sleep(0.25)


m.play_tone_for(m.note('D4'), m.beat(2))

 

 

Now it’s your turn! Play around with these functions so you can create your own melody! 🎵

 


Troubleshooting 🤷

 

If you are experiencing issues where your Robot Car is not playing the entire set of notes, try this:

 

In your terminal, you are going to manually enter into the correct directories and run the code from there.

 

1. Type the following and hit Enter. When you use the "cd" command followed by the name of a directory, it changes your current working directory to that specified directory.

cd robot-hat

2. Next, type and enter "ls" which stands for "list." It is a command used to display the contents of a directory (folder). When you run the "ls" command in a terminal or command prompt, it will show you a list of files and directories within the current working directory.

ls

3. Now, the following command "sudo python3 ....py" runs the Python script,, allowing it to perform actions that require administrative access on the system.

Sudo python3 [file name].py

Overall, your terminal should look like this: 

Teaching tips

Step Description:

In this step, you will learn how to incorporate music and sound effects into your Python script on the Raspberry Pi. You will create a music object and explore various functionalities to play sound effects and musical tones.

 

Optional Add-on: 

Create and submit a recording to your teacher/class of your car’s musical performance! 

As an additional challenge, you can create a Sound Library by collecting or creating unique sound effects. You can categorize the sounds based on themes (e.g., nature, animals, technology) and use these libraries in future projects.

37

Sound Effects

10 min

Using this next template, you will be able to play sound effects and add another dimension to your Robot Car’s sound capabilities. 


Create a new file in the workspace directory. 

# Import the required library

from robot_hat import Music

 

# Create a Music object

m = Music()

 

# Specify the filename of the sound effect you want to play (replace 'sound_effect.wav' with the actual filename)

m.sound_effect_play ('sound_effect.wav')

 

Before running the script, make sure to replace 'sound_effect.wav' with the actual filename of the sound effect you want to play from a WAV file.

 

You can find WAV files online, making sure you are finding them on reliable sites, like this one: https://www.wavsource.com/sfx/sfx.htm

 

When you download a WAV file, you can store it in a location accessible by your Python script on the Raspberry Pi by doing a drag and drop. The location of your WAV file should be within the main library of your Raspberry Pi's file system, not within a specific directory or folder related to your project. Storing it in the main library ensures that you can easily access the WAV file from anywhere on your Raspberry Pi.

 

Observe how the WAV files are stored at the bottom of the Raspberry Pi folders: 

After completing these steps, your WAV file will be accessible from anywhere on your Raspberry Pi, including your Python script. When you reference the WAV file in your script, you will use the name of the WAV file. Just make sure you are typing your file name exactly as you see it inside the ‘...’, as any typos will not allow it to work.

 

With these functions, we can create all types of sound effects:

from robot_hat import Music

 

m = Music()

 

m.sound_effect_play('beep-03.wav')

m.sound_effect_play('car_crash.wav')

m.sound_effect_play('Cartoon-02.wav')

m.sound_effect_play('chainsaw.wav')

m.sound_effect_play('bloop_x.wav')

Teaching tips

Optional Add-on

Create and submit a recording to your teacher/class of your car’s musical performance! 

As an additional challenge, you can create a Sound Library by collecting or creating unique sound effects. You can categorize the sounds based on themes (e.g., nature, animals, technology) and use these libraries in future projects.

38

Color Detection

20 min

In this captivating mini-lesson, you'll embark on a journey to explore the realm of color detection using Python on your Robot Car 🌈

 

You'll begin by delving into the "robot_hat" directory, where the music.py file awaits to guide you through this colorful adventure.

 

The provided Python code sets the stage for your exploration, initiating the Robot Car's camera and displaying its feed. As you venture into the world of color detection, you'll have the opportunity to choose from a spectrum of colors: red, orange, yellow, green, blue, or purple.

 

The car will move forward slowly, and its camera will scan for the selected color. When the camera detects the chosen color, the car will come to a halt, accompanied by a delightful sound, adding a playful element to your learning experience.

 

So, get ready to dive into the world of color detection and witness your Robot Car's ability to recognize and react to different colors. It's an engaging and interactive way to explore the wonders of computer vision on your journey with the Robot Car!

 

Steps to SSH-Connect to Robot Car

  1. Turn on the car. 

  2. Make sure your computer is on the same WiFi as your Robot Car.

  3. Open a Google Chrome Browser and type this into the URL: http://hostname:8080 using your hostname or IP Address.

    • ❗️If you are using a Mac, type in  http://hostname.local:8080. For example, your hostname may look like robotcar.local (or robotcar1.local if using a classroom router).

  4. Open the vilib folder, then examples. 

  5. In the vilib directory, open the color_detect.py file. 

 


Let's take a look at the color_detect.py file to understand what it does and how it allows the Robot Car to see colors and return them in the terminal. 

 

This Python script is designed to perform color detection using the "vilib" library and provides information about the detected color blocks in the camera feed. Let's break down its functionality step by step:

 

1. Import Statements:  

#!/usr/bin/env python3

from vilib import Vilib

from time import sleep

 

  • The line #!/usr/bin/env python3 specifies that this script should be executed using Python 3.
  • It imports necessary modules: Vilib from the "vilib" library and the sleep function from the "time" library.

 

2. Camera Initialization and Configuration: 

Vilib.camera_start(vflip=False, hflip=False)

Vilib.display(local=True, web=True)

Vilib.color_detect(color="green")

sleep(1)

 

  • Initializes the camera using Vilib.camera_start() with options to disable vertical (vflip) and horizontal (hflip) flipping.
  • Enables local and web display with Vilib.display().
  • Initiates color detection with a specified color, in this case, "green." ❗️You can replace the code to detect a different color by inputting red, green, blue, yellow, orange, or purple.
  • Sleeps for 1 second to allow time for the camera to start and initialize.

 

3. Color Detection and Reporting Loop:

while True:

Starts an infinite loop to continuously monitor and report color detection results.

 

4. Get the Number of Color Blocks:

n = Vilib.detect_obj_parameter['color_n']

Retrieves the number of color blocks detected using Vilib.detect_obj_parameter['color_n'].

 

5. Print Color Block Information:

print("%s color blocks are found" % n, end=',', flush=True)

Prints the number of color blocks found.

 

6. Conditional Reporting: 

if n != 0:

    w = Vilib.detect_obj_parameter['color_w']

    h = Vilib.detect_obj_parameter['color_h']

    print("the maximum color block pixel size is %s*%s" % (w, h))

else:

    print('')

  • If color blocks are detected (i.e., n is not zero), it prints the maximum pixel size of the detected color block.
  • If no color blocks are found, it prints a new line for formatting.

 

7. Sleep: 

sleep(0.5)

Sleeps for 0.5 seconds before the next iteration of the loop.


 

In summary, this script initializes the camera, detects a specified color, and continuously reports the number of color blocks found along with the maximum pixel size of the detected color block. It runs indefinitely until manually stopped and provides real-time feedback on color detection.

 


Run the python file and you should something that looks like the following: 

Starting network video streaming ...

 

Running on: http://192.168.1.45:5000/

 

 * Serving Flask app "vilib.vilib" (lazy loading)

 * Environment: development

 * Debug mode: off

 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

0 color blocks are found,

4 color blocks are found,the maximum color block pixel size is 0*0

6 color blocks are found,the maximum color block pixel size is 52*88

0 color blocks are found,

1 color blocks are found,the maximum color block pixel size is 32*32

3 color blocks are found,the maximum color block pixel size is 52*72

0 color blocks are found,

 

 

This output provides real-time feedback on the color detection process. It reports the number of color blocks found and, when color blocks are detected, it also provides information about the maximum pixel size of the largest detected color block. The script continues to run indefinitely, continuously monitoring the camera feed for color detection.

 

Note that you need to have good lighting in order for accurate color detection. Remember, you can replace the code to detect a different color by inputting red, green, blue, yellow, orange, or purple.

 

Using the URL http://hostname:5000 with your hostname or IP Address, you can see a live video feed from your car’s camera performing color detection and drive at the same time! 

 

Teaching tips

Step Description: 

In this step, you will discover how to integrate color detection into your Python script on the Raspberry Pi. You will create a color detection object and explore various functions to identify and work with different colors in images or videos.

39

Dancing Car

5 min

The following code will play a short tune while the Robot Car moves in different directions. You'll hear the music while seeing the car's movements, creating a fun combination of sound and motion 💃

 

This program runs until it reaches the last note or until interrupted (using Ctrl + C).

 

Save the following program to your workspace folder as Dancing Car and have fun! Feel free to change the sounds and movements! 

 

# write your import statements here

import threading

import time

from picarx import Picarx

from robot_hat import Music

import time

 

# initialize your music and picarx objects here

m = Music()

m.tempo(60)

px = Picarx()

 

def play_song():

    # write your song to be played here

    m.play_tone_for(m.note("C4"), m.beat(0.25))

    m.play_tone_for(m.note("D4"), m.beat(0.25))

    m.play_tone_for(m.note("E4"), m.beat(0.25))

    m.play_tone_for(m.note("F4"), m.beat(0.25))

    m.play_tone_for(m.note("G4"), m.beat(0.25))

    m.play_tone_for(m.note("A4"), m.beat(0.25))

    m.play_tone_for(m.note("B4"), m.beat(0.25))

    m.play_tone_for(m.note("C5"), m.beat(0.25))

 

if __name__ == "__main__":

    x = threading.Thread(target=play_song)

    x.start()

    # write your movements here

 

    px.set_dir_servo_angle(-30)

    time.sleep(1)

    px.set_dir_servo_angle(0)

    time.sleep(1)

    px.set_dir_servo_angle(30)

    time.sleep(1)

    px.set_dir_servo_angle(0)

    time.sleep(1)

    px.set_dir_servo_angle(-30)

    time.sleep(1)

    px.set_dir_servo_angle(0)

    time.sleep(1)

    px.set_dir_servo_angle(30)

    time.sleep(1)

    px.set_dir_servo_angle(0)

 

Remember that you can integrate wav files for sound effects and different musical notes using this reference doc. 

40

🎉 You Did It!

5 min

You Did It!

 

Nice work! You've completed the Self-Driving Car project! We've covered a ton about this project and congrats to you for finishing it 🎉

 

Reflect on Your Journey:

  • Take a moment to think about all the skills and knowledge you've gained throughout this project.
  • Consider the challenges you faced and how you overcame them. Remember, learning often involves overcoming obstacles.
  • Think about the moments of discovery and accomplishment when you made your self-driving car perform a task.

 

Your Next Steps:

  • Now that you've mastered this project, consider where you'd like to apply your newfound knowledge and skills.
  • Explore other exciting projects and challenges in the world of robotics and automation.
  • Share your journey and accomplishments with others who may be inspired by your work.

 

Stay Curious and Keep Learning:

  • Learning doesn't stop here! Continue to explore and expand your understanding of robotics, coding, and automation. Join online communities or teams to connect with fellow enthusiasts and professionals in the field. 
  • Consider further education or training in related subjects if you're passionate about pursuing a career in this area.

 

Thank You:

Special thanks to everyone who supported you during this project, whether it was your teacher, classmates, friends, or family. Learning is often a collaborative effort. Remember, every project you complete brings you one step closer to achieving your goals. So keep pushing the boundaries of what you can achieve, stay curious, and never stop learning.

 

Best of luck on your future projects and endeavors! 🚗💨

Materials

  • 2.0 Robot Car Kit — 5 per group
  • Assembled Robot Car — 5 per group
  • Car Obstacle Course — 1 per classroom
  • Networking Kit — 1 per classroom
  • Raspberry Pi 4b+ — 5 per group

Related Supply Kit

Self-Driving Car Pack

All the hands-on materials you need for this lesson, delivered to your classroom.

Ready to bring this lesson to your classroom?

Sign up to save this lesson, order supplies, and track student progress.