树莓派开发相关知识十 -小车服务器
1、功能引脚定义
实际测试,请根据接线情况调整对应控制引脚。
#4个电机驱动输出通道
CarIN=[6,13,19,26]
#生成小车对象
car=CarMove.L298N(CarIN)#4个红外输入通道
RedIN=[25,24,23,18]
#初始化为输入
GPIO.setup(RedIN,GPIO.IN)
#自动运行标志,用来停止自动模式
exitFlag=1
stopmu=1#3个超声波测距
DIO=[16,20,21]
#超声波是否启用标志
carstate=1
#舵机角度设定
angle=90#数码管
dio=17
clk=27
LCD.init(dio,clk)
#初始化数码管
LCD.send_auto(dio,clk,0,1)#蜂鸣器引脚
pin_beep=12
#灯
LED=[22,5]
#初始化蜂鸣器和灯
distance.init(pin_beep,LED)
#超声波锁
2、小车运行命令处理
def carrun(data,speed=0):global carglobal DIOglobal angledistance.stop_beep()distance.stop_led()if speed!=0:car.speed=speedcar.stopall()if data=='f':distance.start_led('f')angle=90car.forward()elif data=='b':distance.start_led('b')angle=-1car.backward()elif data=='l':angle=135distance.start_beep()car.leftward()elif data=='r':angle=45distance.start_beep()car.rightward()elif data=='up':car.speedup()elif data=='down':car.speeddown()else:print 'cmd error!'
3、小车避障
#小车避障
def carvoid():global anglewhile not carstate:if angle==-1:num=0else:num=distance.get_distance(DIO,angle)if num<20 and num !=-1:car.stopall()time.sleep(0.01)time.sleep(0.01)print num#数码管显示LCD.send_auto(dio,clk,int(num),0)
4、智能模式
#智能模式
def carmu():while not stopmu:num=distance.get_distance(DIO,90)if num<20 and num!=-1:car.stopall()num1=distance.get_distance(DIO,45)num2=distance.get_distance(DIO,135)if num<10:carrun('b',15)time.sleep(0.5)if num1>num2:carrun('r',23)time.sleep(0.5)else:carrun('l',23)time.sleep(0.5)else:carrun('f',15)time.sleep(0.5)car.stopall()
5、红外寻迹
#小车红外寻迹(自动)
def auto_start():global RedINnum=0while not exitFlag:if GPIO.input(RedIN[0])==GPIO.HIGH:num=0carrun('r',23)time.sleep(0.2)elif GPIO.input(RedIN[3])==GPIO.HIGH:num=0carrun('l',23)time.sleep(0.2)elif GPIO.input(RedIN[1])==GPIO.HIGH or GPIO.input(RedIN[2])==GPIO.HIGH:num=0carrun('f',15)time.sleep(0.25)else:if num>10:car.stopall()else:carrun('b',16)time.sleep(0.25)num +=1
6、整体调用响应
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind(('192.168.191.3',10000))
s.listen(5)try:while True:print '等待连接...'clientSock,clientaddr=s.accept()print '新连接:',clientaddrwhile True:data=clientSock.recv(1024)if not data:breakelse:print '命令:',dataif data=='a':exitFlag=0car_a=threading.Thread(target=auto_start)car_a.start()if carstate==1:t2=threading.Thread(target=carvoid)t2.start()carstate=0else:print 'exits'elif data=='s':#停止自动或手动car.stopall()distance.stop_beep()exitFlag=1carstate=1stopmu=1elif data=='mu':print 'mu'stopmu=0car_m=threading.Thread(target=carmu)car_m.start()else:t=threading.Thread(target=carrun,args=(data,))t.start()if carstate==1:t2=threading.Thread(target=carvoid)t2.start()carstate=0else:print 'exits'except KeyboardInterrupt:LCD.send_auto(dio,clk,-1,0)GPIO.cleanup()s.close()
7、其他调用前面编写的模块
LCD 对应数据码管模块
树莓派开发相关知识七 -串口数码管C语言版本-CSDN博客
distance对应超声波测距
树莓派开发相关知识四 传感器-测距C语言版本-CSDN博客
CarMove对应L298N
树莓派开发相关知识三PWM控制转速-CSDN博客
import socket
import CarMove
import RPi.GPIO as GPIO
import time
import threading
import distance
import LCD