下面是一个简单的基于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引脚),你可以根据实际硬件连接修改引脚号
网友回复
图片ai拒绝帮用户ps修改带公章类的拍照图片如何解决?
视频大模型和最强文本大模型通过代码生成视频哪个性价比更高?
seedream5.5为啥无法将图白色背景修改成透明?
seedance2如何通过2张不同角度平视图来识别场景进行人物定位?
有没有免费的浏览器中离线运行的语音识别ai模型?
微信小程序个人版不交钱认证就不让你用二维码,报错"errcode":85411?
美丽国为啥要限制ai发展?
seedance2如何参考白模视频使用真实场景和人物生成新视频?
如何设定小孩看电视的时候每隔10分钟弹出一个题目,答对才能继续,答错继续下一题?
直播数字人根据公屏互动评论实时做出不用动作技术是什么?


