Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Import libraries
- from gpiozero import Robot, InputDevice, OutputDevice
- from time import sleep, time
- import random
- #Define variables
- robo = Robot(left=(8,7), right=(10,9))
- trig = OutputDevice(17)
- echo = InputDevice(18)
- duration = 10
- end_time = time() + duration
- running = True
- #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)
- #randomly generate variable time for turning and 0 or 1 for left or right turns
- turn_time = random.uniform(0.1, 0.9)
- left_right = random.randint(0, 1)
- #Drive condition: either forward if no obstacles, or left/right depending on whether 1 or 0
- if distance <= 0.35 and distance != 0:
- robo.backward(0.3)
- sleep(0.2)
- if left_right == 0:
- robo.left(0.6)
- else:
- robo.right(0.6)
- sleep(turn_time)
- else:
- robo.forward(0.3)
- #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