赞
踩
树莓派作为服务端,代码如下:
#coding=utf-8 import socket import time import sys import thread import os import RPi.GPIO as GPIO HOST_IP = "172.28.11.3" HOST_PORT = 7654 GPIO.setwarnings(False) #Echo G21(input) #trig G20 GPIO.setmode(GPIO.BCM) GPIO.setup(22,GPIO.OUT) GPIO.setup(27,GPIO.OUT) GPIO.setup(25,GPIO.OUT) GPIO.setup(24,GPIO.OUT) GPIO.setup(18,GPIO.OUT) GPIO.setup(23,GPIO.OUT) GPIO.setup(20,GPIO.OUT) GPIO.setup(21,GPIO.IN) pwma=GPIO.PWM(18,100) pwmb=GPIO.PWM(23,100) pwma.start(100) pwmb.start(100) print("Starting socket: TCP...") socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("TCP server listen @ %s:%d!" %(HOST_IP, HOST_PORT) ) host_addr = (HOST_IP, HOST_PORT) socket_tcp.bind(host_addr) socket_tcp.listen(1) def checkdist(): while True: GPIO.output(20,True) time.sleep(0.000015) GPIO.output(20,False) while not GPIO.input(21): pass t1=time.time() while GPIO.input(21): pass t2=time.time() socket_con.send("distance:"+str((t2-t1)*340/2)+'m') #print(1) time.sleep(0.3) def camera(): os.system('cd ~/mjpg-streamer/mjpg-streamer-experimental && ./mjpg_streamer -i "./input_uvc.so" -o "./output_http.so -w ./www"') thread.start_new_thread(camera,()) while True: pwma.ChangeDutyCycle(50) GPIO.output(22,0) GPIO.output(27,0) pwmb.ChangeDutyCycle(50) GPIO.output(25,0) GPIO.output(24,0) print ('waiting for connection...') socket_con, (client_ip, client_port) = socket_tcp.accept() print("Connection accepted from %s." %client_ip) thread.start_new_thread(checkdist,()) # socket_con.send("Welcome to RPi TCP server!") while True: data=socket_con.recv(1024) #if data: #print(data) #socket_con.send(data) if data=='a': #socket_con.send(data) #forward pwma.ChangeDutyCycle(50) GPIO.output(22,True) GPIO.output(27,False) pwmb.ChangeDutyCycle(50) GPIO.output(25,True) GPIO.output(24,False) elif data=='b': #back pwma.ChangeDutyCycle(50) GPIO.output(22,0) GPIO.output(27,1) pwmb.ChangeDutyCycle(50) GPIO.output(25,0) GPIO.output(24,1) elif data=='d': #left pwma.ChangeDutyCycle(50) GPIO.output(22,1) GPIO.output(27,0) pwmb.ChangeDutyCycle(50) GPIO.output(25,0) GPIO.output(24,1) elif data=='c': #right pwma.ChangeDutyCycle(50) GPIO.output(22,0) GPIO.output(27,1) pwmb.ChangeDutyCycle(50) GPIO.output(25,1) GPIO.output(24,0) else: pwma.ChangeDutyCycle(50) GPIO.output(22,0) GPIO.output(27,0) pwmb.ChangeDutyCycle(50) GPIO.output(25,0) GPIO.output(24,0) socket_tcp.close()
其中HOST_IP为树莓派的ip,也就是socket服务端的ip,HOST_PORT可以自行设置,但是服务端和客户端必须保持一致。其中开启了2个线程,一个是用于开启mjpg-streamer的命令,一个是用于超声波的采集,传输到安卓端(客户端)。为了视频传输,树莓派必须安装mjpg-streamer。
作为客户端连接树莓派,surfaceview读取mjp-streamer视频流,按键控制小车移动,并显示超声波数据。附件为app工程。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。