结合DAYU200的开发,这次实现摇小车。
实现原理:小河狸开发板开机后连接到连上wifi,并县开启TCP_server服务器。DAYU200连接到开发板上,发送前进、后退、停止,左右转向与回位的信号,小车开发板接收到后向两个舵机发送信号。具体代码如下:
import gewu
import network
import socket
sta_if = network.WLAN(network.STA_IF)
listenSocket = None
port = 3861
def do_connect():
try:
if not sta_if.active():
print("set sta active")
sta_if.active(True)
if not sta_if.isconnected():
print("connecting to network...")
sta_if.connect("SSID", "PWD")
retry_times = 30
while not sta_if.isconnected() and retry_times > 0:
print(" wait a moment i will try %s items,please" % retry_times)
time.sleep(2)
retry_times -= 1
print("network config:", sta_if.ifconfig())
ip = sta_if.ifconfig()[0]
print("IP:", ip)
gewu.display.text(ip,0,32,6)
gewu.display.show()
listenSocket = socket.socket()
print(listenSocket)
listenSocket.bind((ip, port))
print("bind OK")
listenSocket.listen(1)
listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("tecp waiting...")
while True:
print("accepting......")
conn, addr = listenSocket.accept()
print(addr, "connected")
while True:
data = conn.recv(1024)
if len(data) == 0:
print("close socket")
conn.close()
break
data = data.decode()
print(data)
if data == "CARGO":
gewu.servo_p4.set_speed(30)
if data == "CARBACK":
gewu.servo_p4.set_speed(-30)
elif data == "CARSTOP":
gewu.servo_p4.set_speed(0)
elif data == "CARRIGHT":
gewu.servo_p3.set_angle(110)
elif data == "CARLEFT":
gewu.servo_p3.set_angle(70)
elif data == "CARZERO":
gewu.servo_p3.set_angle(90)
data=''
yield
yield
except Exception as e:
gewu.display.text(str(e), 0, 0, 6)
gewu.display.show()
print(str(e))
func_connect_wifi = do_connect()
def repeat():
next(func_connect_wifi)
pass
gewu.servo_p3.set_angle(90)
while True:
repeat()
gewu.sleep_ms(1)
遥控界面如下:
【总结】由于积木没有TCP_server的模块,我这里采用microPython写的程序。目前只实现基本功能,后面有空修改协议,实现触摸动态速度等功能。
摇控车
|