Advertisement
brendan-stanford

auto-bot_final

Apr 5th, 2020
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #Import libraries
  2. from gpiozero import Robot, InputDevice, OutputDevice, DigitalInputDevice, DigitalOutputDevice
  3. from gpiozero.tools import scaled, negated
  4. from time import sleep, time
  5. from signal import pause
  6. import atexit
  7. import random
  8.  
  9. #Define variables
  10. robo = Robot(left=(8,7), right=(10,9))
  11. trig = OutputDevice(17)
  12. echo = InputDevice(18)
  13. duration = 60
  14. end_time = time() + duration
  15. running = True
  16. left_obstacle_sensor = DigitalInputDevice(27)
  17. right_obstacle_sensor = DigitalInputDevice(4)
  18. drive_speed = 0.6
  19.  
  20. #Wait 2 seconds before starting
  21. sleep(2)
  22.  
  23. #Trigger/Echo pulse time function
  24. def get_pulse_time():
  25. trig.on()
  26. sleep(0.00001)
  27. trig.off()
  28.  
  29. while echo.is_active == False:
  30. pulse_start = time()
  31.  
  32. while echo.is_active == True:
  33. pulse_end = time()
  34.  
  35. return pulse_end - pulse_start
  36.  
  37. #Distance calculation function based on pulse time as input
  38. def calculate_distance(duration):
  39. speed = 343
  40. distance = speed * duration / 2
  41. return distance
  42.  
  43. #Main loop executes until run time
  44. while running:
  45.  
  46. #Calculate pulse time/distance
  47. duration = get_pulse_time()
  48. distance = calculate_distance(duration)
  49. turn_time = random.uniform(0.1, 0.9)
  50. left_right = random.randint(0, 1)
  51.  
  52. #Drive condition: either forward if no obstacles, or left
  53. if distance <= 0.35 and distance != 0:
  54. robo.backward(drive_speed)
  55. sleep(0.5)
  56. if left_right == 0:
  57. robo.left(drive_speed)
  58. else:
  59. robo.right(drive_speed)
  60. sleep(turn_time)
  61. else:
  62. #Scale motors to the opposite reading coming from the infrared sensor on the opposing side (i.e. left sensor for right motor and vice versa); should act as backup obstacle detection if ultrasonic fails
  63. robo.left_motor.source = scaled(right_obstacle_sensor, -1 * drive_speed, drive_speed)
  64. robo.right_motor.source = scaled(left_obstacle_sensor, -1 * drive_speed, drive_speed)
  65.  
  66. #Running condition: False if over end_time
  67. if time() > end_time:
  68. running = False
  69. robo.stop()
  70.  
  71. #print distance to console
  72. sleep(0.06)
  73. print(distance)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement