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.