基于ESP8266灯控

 

ESP8266灯控硬件:使用淘宝ESP-01模块,带一个ESP8266插槽和一个5V继电器,220V转5V用拆下的手机充电器

ESP8266代码,开放TCP Server(80)端口,同时作为TCP Client连接远端TCP Server,可读取和配置pin1、pin2,可读取adc

WIFI_NAME = "MERCURY_204"
WIFI_PASSWORD = "Password"
SERVER_IP = "192.168.1.200"
SERVER_PORT = 8081

led1 = 3
led2 = 4
gpio.mode(led1, gpio.OUTPUT)
gpio.mode(led2, gpio.OUTPUT)
wifi.setmode(wifi.STATION)
wifi.sta.config(WIFI_NAME, WIFI_PASSWORD)
wifi.sta.connect()
wifi.sta.autoconnect(1)

Watchdog = 0
local function receiveData(data)
    Watchdog = 0
    local _GET = {}
    for k, v in string.gmatch(data, "(%w+)=(%d*)") do
        _GET[k] = v
    end
    
    local buf = "ID="..node.chipid();
    if(_GET.PIN1 == "1")then
        gpio.write(led1, gpio.HIGH);
        print("led1 on")
    elseif(_GET.PIN1 == "0")then
        gpio.write(led1, gpio.LOW);
        print("led1 off")
    end
    if(_GET.PIN1 ~= nil)then
        buf = buf.." PIN1="..gpio.read(led1)
    end
    
    if(_GET.PIN2 == "1")then
        gpio.write(led2, gpio.HIGH);
        print("led2 on")
    elseif(_GET.PIN2 == "0")then
        gpio.write(led2, gpio.LOW);
        print("led2 off")
    end
    if(_GET.PIN2 ~= nil)then
        buf = buf.." PIN2="..gpio.read(led2)
    end
    
    if(_GET.ADC ~= nil)then
        buf = buf.." ADC="..adc.read(0)
    end
    return buf
end

ClientConnectedFlag = 0
i=0
tmr.alarm(1, 1000, 1, function()
    if wifi.sta.getip()== nil then
        print("IP unavaiable, Waiting...")
        i=i+1
        if(i>10) then
            print("restart nodeMCU")
            node.restart()
        end
    elseif ClientConnectedFlag == 0 then
        print("Connecting to Server...")
        Client = net.createConnection(net.TCP, 0)
        Client:connect(SERVER_PORT, SERVER_IP)

        Client:on("receive", function(Client, data)
            Client:send(receiveData(data));
            collectgarbage();
        end)
        Client:on("connection", function(sck, c)
            ClientConnectedFlag = 1
        end)
        Client:on("disconnection", function(sck, c)
            ClientConnectedFlag = 0
        end)
    elseif Watchdog >= 120 then
        Watchdog = 0
        ClientConnectedFlag = 0
        Client:close();
    else
        Watchdog = Watchdog + 1
    end
end)

srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive", function(client,data)
        client:send(receiveData(data));
        client:close();
        collectgarbage();
    end)
end)

 

PC上使用QT开放两个TCP Server(8080、8081),8081端口用于管理设备,8080端口用于与Android终端通讯

基于ESP8266灯控

 

打印Log

基于ESP8266灯控

Android终端作为TCP Client连接到PC的TCP 8080端口,通过Server获取和配置已连接的设备信息

基于ESP8266灯控

设备、PC、Android连接方式:

基于ESP8266灯控

 

方案改进:利用了之前买的nanopi开发版,手掌心大小,通过网线接入到局域网中,配置静态ip为192.168.1.200,将nanopi代替pc

nanopi上跑Ubuntu-Core with Qt-Embedded系统,在pc上建立ubuntux64虚拟机,安装好arm交叉编译器,在pc上完成程序移植,因为下载qt太慢,直接用c重新写了一遍,相比之下c代码对字符串的处理真是麻烦,全部当数组操作。调试ok后编译拷贝到nanopi上,赋予可执行权限,就可以通过nanopi控制esp8266了