Solution
Hints
- Four things happen in order once an obstacle gets close: stop, reverse, turn, then drive forward again -- one small function per step keeps the loop readable.
- A sensor reading that looks perfect on a desk can lie once it's mounted at an angle -- keep it level and pointed straight ahead.
- "About 90 degrees" with no encoder really means timing: how many milliseconds you leave the wheels spinning in opposite directions.
Steps
- Confirm your Cytron board's motor pins and your sensor's pins (or bus) from its pinout guide.
- Write drive(left, right) so a -100-to-100 speed value becomes the right PWM signal on each motor pin.
- Write get_distance_cm() to return the sensor's live reading in centimeters.
- Loop forever: drive forward while the reading is above STOP_CM; otherwise reverse, turn, then check the distance again.
- Start from the chapter's numbers (20 cm, 100 ms) and retune every constant while test-driving in the real room.
from machine import Pin, PWM
from time import sleep_ms
LEFT_FWD, LEFT_REV = PWM(Pin(11)), PWM(Pin(10))
RIGHT_FWD, RIGHT_REV = PWM(Pin(8)), PWM(Pin(9))
FULL = 65025
STOP_CM, POLL_MS, REV_MS, TURN_MS = 20, 100, 400, 350
def pwm(speed):
return int(abs(speed) / 100 * FULL)
def drive(left, right):
LEFT_FWD.duty_u16(pwm(left) if left > 0 else 0)
LEFT_REV.duty_u16(pwm(left) if left < 0 else 0)
RIGHT_FWD.duty_u16(pwm(right) if right > 0 else 0)
RIGHT_REV.duty_u16(pwm(right) if right < 0 else 0)
def get_distance_cm():
pass # read your sensor here
while True:
if get_distance_cm() > STOP_CM:
drive(70, 70)
else:
drive(-60, -60)
sleep_ms(REV_MS)
drive(60, -60)
sleep_ms(TURN_MS)
sleep_ms(POLL_MS)
See also: Chapter 18's Collision Avoidance Robot section and Control Loop diagram.