Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Import libraries
- from gpiozero import Robot, InputDevice, OutputDevice, DigitalInputDevice, DigitalOutputDevice
- from gpiozero.tools import scaled, negated
- from time import sleep, time
- from signal import pause
- import atexit
- import random
- #Define variables
- robo = Robot(left=(8,7), right=(10,9))
- trig = OutputDevice(17)
- echo = InputDevice(18)
- duration = 60
- end_time = time() + duration
- running = True
- left_obstacle_sensor = DigitalInputDevice(27)
- right_obstacle_sensor = DigitalInputDevice(4)
- drive_speed = 0.6
- #Wait 2 seconds before starting
- sleep(2)
- #Trigger/Echo pulse time function
- def get_pulse_time():
- trig.on()
- sleep(0.00001)
- trig.off()
- while echo.is_active == False:
- pulse_start = time()
- while echo.is_active == True:
- pulse_end = time()
- return pulse_end - pulse_start
- #Distance calculation function based on pulse time as input
- def calculate_distance(duration):
- speed = 343
- distance = speed * duration / 2
- return distance
- #Main loop executes until run time
- while running:
- #Calculate pulse time/distance
- duration = get_pulse_time()
- distance = calculate_distance(duration)
- turn_time = random.uniform(0.1, 0.9)
- left_right = random.randint(0, 1)
- #Drive condition: either forward if no obstacles, or left
- if distance <= 0.35 and distance != 0:
- robo.backward(drive_speed)
- sleep(0.5)
- if left_right == 0:
- robo.left(drive_speed)
- else:
- robo.right(drive_speed)
- sleep(turn_time)
- else:
- #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
- robo.left_motor.source = scaled(right_obstacle_sensor, -1 * drive_speed, drive_speed)
- robo.right_motor.source = scaled(left_obstacle_sensor, -1 * drive_speed, drive_speed)
- #Running condition: False if over end_time
- if time() > end_time:
- running = False
- robo.stop()
- #print distance to console
- sleep(0.06)
- print(distance)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement