下面是一个简单的基于NodeMCU(ESP8266)的Lua程序示例,通过一个网页按钮和一个机械按钮来控制LED的开关,同时在网页上显示LED的状态。
此程序使用NodeMCU提供的net和gpio模块,同时使用HTTP服务器来处理网页请求。
-- 设置LED引脚 local ledPin = 4 -- GPIO2 -- 初始化LED状态 local ledState = gpio.LOW -- 初始化网络配置 local wifiConfig = { ssid = "your-ssid", -- 你的WiFi名称 pwd = "your-password" -- 你的WiFi密码 } -- 初始化HTTP服务器 srv = net.createServer(net.TCP) srv:listen(80, function(conn) conn:on("receive", function(client, request) local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP") if method == nil then _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP") end local _GET = {} if vars ~= nil then for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do _GET[k] = v end end local response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n" if _GET.pin == "ON" then gpio.write(ledPin, gpio.HIGH) ledState = gpio.HIGH elseif _GET.pin == "OFF" then gpio.write(ledPin, gpio.LOW) ledState = gpio.LOW end response = response .. "<html><body>" response = response .. "<h1>ESP8266 LED Control</h1>" response = response .. "<p>LED State: " .. (ledState == gpio.HIGH and "ON" or "OFF") .. "</p>" response = response .. "<p><a href=\"?pin=ON\"><button style=\"background-color:green\">Turn ON</button></a></p>" response = response .. "<p><a href=\"?pin=OFF\"><button style=\"background-color:red\">Turn OFF</button></a></p>" response = response .. "</body></html>" client:send(response) client:close() collectgarbage() end) end) -- 设置LED引脚为输出 gpio.mode(ledPin, gpio.OUTPUT) -- 连接WiFi wifi.setmode(wifi.STATION) wifi.sta.config(wifiConfig) -- 等待WiFi连接成功 tmr.alarm(1, 1000, 1, function() if wifi.sta.getip() == nil then print("Connecting to WiFi...") else tmr.stop(1) print("Connected to WiFi. IP Address: " .. wifi.sta.getip()) end end)
这个Lua程序通过HTTP服务器监听端口80,当收到网页请求时,会根据请求参数控制LED的状态,并在网页上显示LED的当前状态。你可以使用NodeMCU Flasher等工具将该Lua程序烧录到ESP8266上。在程序中,LED的引脚使用GPIO2(对应NodeMCU的D4引脚),你可以根据实际硬件连接修改引脚号
网友回复