EasyManua.ls Logo

SunFounder picar-x - Page 60

Default Icon
153 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
If there is no obstacle in the direction after turning left or the obstacle distance is greater than 25cm, it will continue to
move forward.
Code
Note: You can Modify/Reset/Copy/Run/Stop the code below. But before that, you need to go to source code path
like picar-x/example. After modifying the code, you can run it directly to see the effect.
from picarx import Picarx
def main():
try:
px = Picarx()
# px = Picarx(ultrasonic_pins=['D2','D3']) # tring, echo
px.forward(30)
while True:
distance = px.ultrasonic.read()
print("distance: ",distance)
if distance > 0 and distance < 300:
if distance < 25:
px.set_dir_servo_angle(-35)
else:
px.set_dir_servo_angle(0)
finally:
px.forward(0)
if __name__ == "__main__":
main()
How it works?
The ultrasonic module is also imported in the picarx module, and we can use some of its encapsulated functions to
detect distance.
from picarx import Picarx
Because the ultrasonic module is imported into the picarx module, we can directly use px.ultrasonic.read()
to get the distance.
px = Picarx()
px.forward(30)
while True:
distance = px.ultrasonic.read()
The following code snippet reads the distance value reported by the ultrasonic module, and if the distance is below
25cm (10 inches) it will set the steering servo from (straight) to -35° (turn left).
while True:
distance = px.ultrasonic.read()
print("distance: ",distance)
if distance > 0 and distance < 300:
if distance < 25:
px.set_dir_servo_angle(-35)
else:
px.set_dir_servo_angle(0)
56 Chapter 4. Play with Python

Related product manuals