# -*- coding: utf-8 -*-
"""Run the car and stop if distance to obstacle is < 40cm."""
-from _thread import start_new_thread
from machine import Pin, PWM
from utime import sleep_us, ticks_us
TRIG = Pin(5, Pin.OUT)
ECHO = Pin(4, Pin.IN)
-SPEED = PWM(Pin(12), freq=1000)
+SPEED = PWM(Pin(14), freq=1000)
+BACK = PWM(Pin(15), freq=1000)
-dist = 4
+dist = 40
def get_dist():
- """Read data from ultrasonic sensor."""
+ """Read data from ultrasonic sensor and drive car if no obstacle."""
global dist
+ BACK.duty(0)
nc = ticks_us()
while True:
+ # read sensor data
TRIG.off()
sleep_us(2)
TRIG.on()
pass
t2 = ticks_us()
dist = (t2 - t1) / 58.0
- nc += 20000
- sleep_us(nc - ticks_us())
- return
-
-def set_speed():
- """Set PWM to control car speed."""
- nc = ticks_us()
- while True:
- if dist < 20:
+ # drive if obstacle-free
+ if dist > 10:
SPEED.duty(1023)
else:
SPEED.duty(0)
- nc += 200000
+ nc += 20000
sleep_us(nc - ticks_us())
return
if __name__ == "__main__":
- start_new_thread(get_dist, ())
- start_new_thread(set_speed, ())
- while True:
- pass
+ get_dist()