Advertisement
timber101

UDS with reverse and random L&R

Feb 4th, 2021
991
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None
  1. # autorunning
  2.  
  3. from gpiozero import InputDevice, OutputDevice, Robot
  4. from time import sleep, time
  5. import random
  6.  
  7. sleep(2)
  8.  
  9. fwdsp = 0.75
  10. bcksp = 0.25
  11.  
  12. trig = OutputDevice(4)
  13. echo = InputDevice(17)
  14. boris = Robot(right =(20,21),left =(19,26))
  15. duration = 10
  16. end_time = time() + duration
  17. running = True
  18.  
  19. sleep(2)
  20.  
  21. def randtime():
  22.     randtim = random.uniform(0.25, 0.75)
  23.     return randtim
  24.  
  25.  
  26. def get_pulse_time():
  27.     pulse_start, pulse_end = 0,0
  28.  
  29.     trig.on() # sends a burst
  30.     sleep(0.00001)
  31.     trig.off() # stops burst
  32.  
  33.     while echo.is_active == False:
  34.         pulse_start = time()
  35.     while echo.is_active == True:
  36.         pulse_end = time()
  37.  
  38.     return pulse_end - pulse_start
  39.  
  40. def calc_dist(duration):
  41.     speed = 343 # speed of sound in air m / second
  42.  
  43.     distance = speed * duration /2 # distance is there and back hence divide by 2
  44.     #calcs distance in metres
  45.  
  46.     return distance
  47.  
  48.  
  49. while running:
  50.     duration = get_pulse_time()
  51.     distance = calc_dist(duration)
  52.  
  53.     if distance < 0.2:
  54.         boris.backward(bcksp)
  55.         sleep(0.2)
  56.         trn = random.choice(["L","R"])
  57.         if trn == "L":
  58.             boris.left(randtime())
  59.         else:
  60.             boris.right(randtime())
  61.         sleep(0.5)
  62.     else:
  63.         boris.forward(fwdsp)
  64.  
  65.     if time() >= end_time:
  66.         running = False
  67.         boris.stop()
  68.     sleep (0.06)
  69.     print("%.4f" % distance )
Advertisement
RAW Paste Data Copied
Advertisement