nodemcu 制作的WiFi小车程序

nodemcu 制作的WiFi小车程序

##硬件连接
D1 —> 直流电机驱动A
D2 —> 直流电机驱动B
D7 —> 转向舵机

##测试效果

  • 转向精度有些低,不知是nodemcu的pwm的问题
  • 转向响应有些慢,这个不清楚是app还是nodemcu反应慢了还是网络的延迟

function setwifi()
    wifi.setmode(wifi.SOFTAP)
    mac = wifi.ap.getmac()
    local cfg = {}
    cfg.ssid = "car_"..mac
    cfg.pwd = "0123456789"
    wifi.ap.config(cfg)        
end

function setpwm()
    pwm.setup(1,50,0)
    pwm.setup(2,50,0)
    pwm.setup(4,50,0)
    pwm.setup(6,50,0)
    pwm.setup(7,50,0)
    pwm.start(1)
    pwm.start(2)
    pwm.start(4)
    pwm.start(6)
    pwm.start(7)
    
    
end

function motorpwm(index, value)
    if value then
       -- print (index,value)
        pwm.setduty(index,value)
    end 
end

function setTcpServer()
    sv = net.createServer(net.TCP)
    sv:listen(8000,
    function(c)
      c:on("receive", function (c,pl)
        --print(pl)
        local t = sjson.decode(pl)
        --for a,b in pairs(t) do
          --print(a,b)
        --end
                                     
        motorpwm(1,t["p1"])   
        motorpwm(2,t["p2"])        
        motorpwm(4,t["p3"])
        motorpwm(6,t["p4"])
        motorpwm(7,t["p5"])

        c:send("data received")
      end)
      c:send("hello car controler\n")
    end
    )
end

flag = 0;
wifi.eventmon.register(wifi.eventmon.AP_STACONNECTED, function(T)
  print("\n\tAP - STATION CONNECTED".."\n\tMAC: "..T.MAC.."\n\tAID: "..T.AID)
  if(flag == 0) then
    setTcpServer()
    flag = 1;
  end
end)
setpwm()
setwifi()


你可能感兴趣的:(nodemcu)