-
1setup sensors and led
from machine import Pin,PWM
import time
trig = 15
echo = 13
led = 4echo = Pin(echo, Pin.IN)
led = Pin(led, Pin.OUT)
trig = Pin(trig, Pin.OUT)
servo = PWM(Pin(2), freq=50, duty=77)
trig.off()
time.sleep_ms(2)
trig.on()
time.sleep_ms(10)
trig.off()def get_distance(unit="cm"):
trig.on()
time.sleep_ms(10)
trig.off()
while echo.value() == 0:
pass
start = time.ticks_us()
while echo.value() == 1:
pass
stop = time.ticks_us()
d = (stop - start)/58
distance = round(d,2)
if unit == "mm":
factor = 10
elif unit == "cm":
factor = 1
elif unit == "m":
factor = 0.1
return distance*factor
def limit(value):
x=int(get_distance())
if x < float(value):
led.on()
print('limit is reached')
else:
led.off()
print('distance is {} cm'.format(x))
print('limit is {} cm'.format(value))
while True:
limit(1000)
time.sleep_ms(1)
if x < 5 :
servo.duty(30)
time.sleep_ms(1)
servo.duty(122) -
2setup motor servo
from machine import Pin, PWM
from time import sleep
servo = PWM(Pin(2), freq=50, duty=77)
servo.duty(30)
sleep(.5)
servo.duty(122)
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.