Advertisement
timber101

With reversing buzzer

Feb 5th, 2021
1,062
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. from gpiozero import InputDevice, OutputDevice, Robot, Buzzer
  2. from time import sleep, time
  3. import random
  4.  
  5. sleep(2)
  6.  
  7. fwdsp = 0.75
  8. bcksp = 0.65
  9.  
  10. bz=Buzzer(16) # using GPIO16 next to a GRD
  11. bz.off()  # make sure its off, because it is anoying if on!
  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.         bz.on()  # Buzzer on
  56.         sleep(0.2)
  57.         bz.off() # Buzzer off
  58.         trn = random.choice(["L","R"])
  59.         if trn == "L":
  60.             boris.left(randtime())
  61.         else:
  62.             boris.right(randtime())
  63.         sleep(0.5)
  64.     else:
  65.         boris.forward(fwdsp)
  66.  
  67.     if time() >= end_time:
  68.         running = False
  69.         boris.stop()
  70.     sleep (0.06)
  71.     print("%.4f" % distance )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement