树莓派避障小车(python)

本文章为树莓派后台小车代码,前台代码可以自由选取
小车代码为:

import  RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)

m1_fwd = 12
m1_rev = 11
m2_fwd = 13
m2_rev = 15
red_left = 07
red_right = 16
trip = 38
echo = 37
def init():
    GPIO.setup(m1_fwd,GPIO.OUT)
    GPIO.setup(m1_rev,GPIO.OUT)
    GPIO.setup(m2_fwd,GPIO.OUT)
    GPIO.setup(m2_rev,GPIO.OUT)
def stop():
    GPIO.output(m1_fwd,False)
    GPIO.output(m1_rev,False)
    GPIO.output(m2_fwd,False)
    GPIO.output(m2_rev,False)
    GPIO.cleanup()
def fwd():
    GPIO.output(m1_fwd,GPIO.HIGH)
    GPIO.output(m1_rev,GPIO.LOW)
    GPIO.output(m2_fwd,GPIO.HIGH)
    GPIO.output(m2_rev,GPIO.LOW)
    GPIO.cleanup()
def rev():
    GPIO.output(m1_fwd,GPIO.LOW)
    GPIO.output(m1_rev,GPIO.HIGH)
    GPIO.output(m2_fwd,GPIO.LOW)
    GPIO.output(m2_rev,GPIO.HIGH)
    GPIO.cleanup()
def right():
    GPIO.output(m1_fwd,GPIO.HIGH)
    GPIO.output(m1_rev,GPIO.LOW)
    GPIO.output(m2_fwd,False)
    GPIO.output(m2_rev,False)
    GPIO.cleanup()
def left():
    GPIO.output(m1_fwd,False)
    GPIO.output(m1_rev,False)
    GPIO.output(m2_fwd,GPIO.HIGH)
    GPIO.output(m2_rev,GPIO.LOW)
    GPIO.cleanup()
def get_distance():
    GPIO.setup(trip,GPIO.OUT)
    GPIO.setup(echo,GPIO.IN)
    GPIO.output(trip,GPIO.HIGH)
    time.sleep(0.000015)
    GPIO.output(trip,GPIO.LOW)
    while not GPIO.input(echo):
        pass
    t1 = time.time()
    while GPIO.input(echo):
            pass
    t2 = time.time()
    return (t2-t1)*34300/2
def turnaround():
    GPIO.setup(red_left,GPIO.IN)
    GPIO.setup(red_right,GPIO.IN)
    while GPIO.input(red_left) and GPIO.input(red_right)==0:
        rev()
        if GPIO.input(red_left)==1:
            left(1)
        else:
            right(1)
    GPIO.cleanup()


while True:
    distance = get_distance()
    time.sleep(0.5)
    if distance > 20:
        fwd()
    elif distance == 20:
        stop()
    else:
        stop()
        turnaround()

你可能感兴趣的:(Raspberry,智能小车)