while GPIO.input(ECHO) == 0:
pass
start = time.time()
while GPIO.input(ECHO) == 1:
pass
stop = time.time()
return (stop - start) * 34000 / 2
Main loop
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# Get current frame from camera
img = frame.array
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find contours in the image
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Check if any obstacles are detected
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 500:
stop()
time.sleep(0.5)
backward()
time.sleep(1)
left()
time.sleep(1)
forward()
# Check distance to nearest obstacle
dist = distance()
if dist < 30:
stop()
time.sleep(0.5)
backward()
time.sleep(1)
left()
time.sleep(1)
forward()
# Clear the stream in preparation for the next frame
rawCapture.truncate(0)
markdown