Advertisement
brendan-stanford

auto-bot

Mar 25th, 2020
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. #Import libraries
  2. from gpiozero import Robot, InputDevice, OutputDevice
  3. from time import sleep, time
  4. import random
  5.  
  6. #Define variables
  7. robo = Robot(left=(8,7), right=(10,9))
  8. trig = OutputDevice(17)
  9. echo = InputDevice(18)
  10. duration = 10
  11. end_time = time() + duration
  12. running = True
  13.  
  14. #Wait 2 seconds before starting
  15. sleep(2)
  16.  
  17. #Trigger/Echo pulse time function
  18. def get_pulse_time():
  19. trig.on()
  20. sleep(0.00001)
  21. trig.off()
  22.  
  23. while echo.is_active == False:
  24. pulse_start = time()
  25.  
  26. while echo.is_active == True:
  27. pulse_end = time()
  28.  
  29. return pulse_end - pulse_start
  30.  
  31. #Distance calculation function based on pulse time as input
  32. def calculate_distance(duration):
  33. speed = 343
  34. distance = speed * duration / 2
  35. return distance
  36.  
  37. #Main loop executes until run time
  38. while running:
  39.  
  40. #Calculate pulse time/distance
  41. duration = get_pulse_time()
  42. distance = calculate_distance(duration)
  43.  
  44. #randomly generate variable time for turning and 0 or 1 for left or right turns
  45. turn_time = random.uniform(0.1, 0.9)
  46. left_right = random.randint(0, 1)
  47.  
  48. #Drive condition: either forward if no obstacles, or left/right depending on whether 1 or 0
  49. if distance <= 0.35 and distance != 0:
  50. robo.backward(0.3)
  51. sleep(0.2)
  52. if left_right == 0:
  53. robo.left(0.6)
  54. else:
  55. robo.right(0.6)
  56. sleep(turn_time)
  57. else:
  58. robo.forward(0.3)
  59.  
  60. #Running condition: False if over end_time
  61. if time() > end_time:
  62. running = False
  63. robo.stop()
  64.  
  65. #print distance to console
  66. sleep(0.06)
  67. print(distance)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement