OpenHarmony开源社区
直播中

华仔stm32

3年用户 2978经验值
擅长:嵌入式技术
私信 关注
[经验]

【小河狸创客格物开发板试用体验】瑶控小车

结合DAYU200的开发,这次实现摇小车。
实现原理:小河狸开发板开机后连接到连上wifi,并县开启TCP_server服务器。DAYU200连接到开发板上,发送前进、后退、停止,左右转向与回位的信号,小车开发板接收到后向两个舵机发送信号。具体代码如下:

import gewu
import network
import socket
sta_if = network.WLAN(network.STA_IF)
listenSocket = None
port = 3861

#连接wifi
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]  # get ip addr
        print("IP:", ip)
#显示IP地址,方便摇控器连接
        gewu.display.text(ip,0,32,6)
        gewu.display.show()
        listenSocket = socket.socket()  # create socket
        print(listenSocket)
#绑定端口
        listenSocket.bind((ip, port))  # bind ip and 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)
                #gewu.display.fill(0)
                #gewu.display.text(data,0,8,6)
                #gewu.display.show()
                #ret = conn.send(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)

遥控界面如下:
image.png
【总结】由于积木没有TCP_server的模块,我这里采用microPython写的程序。目前只实现基本功能,后面有空修改协议,实现触摸动态速度等功能。

摇控车

更多回帖

发帖
×
20
完善资料,
赚取积分