SunFounder PiCar-X Kit
(continued from previous page)
if __name__ == "__main__":
main()
How it works?
• Importing the Picarx Module and Initializing Constants:
This section of the code imports the Picarx class from the picarx module, which is essential for con-
trolling the Picarx robot. Constants like POWER, SafeDistance, and DangerDistance are defined,
which will be used later in the script to control the robot’s movement based on distance measurements.
from picarx import Picarx
import time
POWER = 50
SafeDistance = 40 # > 40 safe
DangerDistance = 20 # > 20 && < 40 turn around,
# < 20 backward
• Main Function Definition and Ultrasonic Sensor Reading:
The main function is where the Picarx robot is controlled. An instance of Picarx is created, which
activates the robot’s functionalities. The code enters an infinite loop, constantly reading the distance
from the ultrasonic sensor. This distance is used to determine the robot’s movement.
def main():
try:
px = Picarx()
while True:
distance = round(px.ultrasonic.read(), 2)
# [Rest of the logic]
• Movement Logic Based on Distance:
The robot’s movement is controlled based on the distance read from the ultrasonic sensor. If
the distance is greater than SafeDistance, the robot moves forward. If the distance is between
DangerDistance and SafeDistance, it slightly turns and moves forward. If the distance is less
than DangerDistance, the robot reverses while turning in the opposite direction.
if distance >= SafeDistance:
px.set_dir_servo_angle(0)
px.forward(POWER)
elif distance >= DangerDistance:
px.set_dir_servo_angle(30)
px.forward(POWER)
time.sleep(0.1)
else:
px.set_dir_servo_angle(-30)
px.backward(POWER)
time.sleep(0.5)
• Safety and Cleanup with the ‘finally’ Block:
4.6. 4. Obstacle Avoidance 59