基于ESP8266灯控

本文介绍了使用ESP8266进行灯控的实现过程,包括硬件搭建、代码编写,以及通过QT创建TCP Server进行设备管理和控制。文章详细描述了如何利用NanoPI运行Ubuntu系统,实现远程监看和控制,集成百度语音识别API,以及使用阿里云物联网平台进行MQTT通信。还探讨了不同内网穿透工具的优缺点。
摘要由CSDN通过智能技术生成

 

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:clo
  • 9
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值