EasyManua.ls Logo

SunFounder PiCar-X Kit - Page 66

Default Icon
181 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
SunFounder PiCar-X Kit
(continued from previous page)
if gm_state == 'forward':
px.set_dir_servo_angle(0)
px.forward(px_power)
elif gm_state == 'left':
px.set_dir_servo_angle(offset)
px.forward(px_power)
elif gm_state == 'right':
px.set_dir_servo_angle(-offset)
px.forward(px_power)
else:
outHandle()
finally:
px.stop()
print("stop and exit")
sleep(0.1)
How it works?
This Python script controls a Picarx robot car using grayscale sensors for navigation. Heres a breakdown of its main
components:
Import and Initialization:
The script imports the Picarx class for controlling the robot car and the sleep function from the time
module for adding delays.
An instance of Picarx is created, and theres a commented line showing an alternative initialization
with specific grayscale sensor pins.
from picarx import Picarx
from time import sleep
px = Picarx()
Configuration and Global Variables:
current_state, px_power, offset, and last_state are global variables used to track and control
the cars movement. px_power sets the motor power, and offset is used for adjusting the steering
angle.
current_state = None
px_power = 10
offset = 20
last_state = "stop"
outHandle Function:
This function is called when the car needs to handle an ‘out of line scenario.
It adjusts the car’s direction based on last_state and checks the grayscale sensor values to determine
the new state.
def outHandle():
global last_state, current_state
if last_state == 'left':
(continues on next page)
62 Chapter 4. Play with Python

Table of Contents

Related product manuals