通过超声波模块与小车结合,实现小车超声波避障。确保小车接线已安装,且安装正确。
通过超声波来获取小车与障碍物的距离。当检测到小车与障碍物的距离小于我们的设置的距离时,小车左旋避开障碍物。
运行代码如下所示:
from LOBOROBOT import LOBOROBOT # 载入机器人库
import RPi.GPIO as GPIO
import timeBtnPin = 19
Gpin = 5
Rpin = 6TRIG = 20
ECHO = 21clbrobot = LOBOROBOT() # 实例化机器人对象def keysacn():val = GPIO.input(BtnPin)while GPIO.input(BtnPin) == False:val = GPIO.input(BtnPin)while GPIO.input(BtnPin) == True:time.sleep(0.01)val = GPIO.input(BtnPin)if val == True:GPIO.output(Rpin,1)while GPIO.input(BtnPin) == False:GPIO.output(Rpin,0)else:GPIO.output(Rpin,0)def setup():GPIO.setwarnings(False)GPIO.setmode(GPIO.BCM)GPIO.setup(TRIG, GPIO.OUT)GPIO.setup(ECHO, GPIO.IN)GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to outputGPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to outputGPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V)def distance():GPIO.output(TRIG, 0)time.sleep(0.000002)GPIO.output(TRIG, 1)time.sleep(0.00001)GPIO.output(TRIG, 0)while GPIO.input(ECHO) == 0:a = 0time1 = time.time()while GPIO.input(ECHO) == 1:a = 1time2 = time.time()during = time2 - time1 time.sleep(0.2)return round(during * 340 / 2 * 100)def loop():while True:dis = distance()if (dis < 40) == True:while (dis < 40) == True:clbrobot.t_down(50,0.5)clbrobot.turnRight(50,0.1)dis = distance()else:clbrobot.t_up(50,0)print(dis, 'cm')print('')def destroy():clbrobot.t_stop(.1)GPIO.cleanup()if __name__ == "__main__":setup()clbrobot.t_stop(.1)keysacn()try:loop()except KeyboardInterrupt:destroy()
我们把小车放在地上,运行程序,小车会一直前进。当遇到前方有障碍物时且小于设置的距离时,小车会左旋避开障碍物。