前言
此篇为番外篇,是 ESP8266 入门的其他功能教程,包括但不限于
- DHT11 驱动
- TCP 通信
- Thingsboard 平台的接入
- 阿里云物联网云平台接入
- 华为云平台接入
1. 小节目标
使用 Lua 驱动 DHT11 传感器,获取温湿度的值
2. 进入主题
官方文档:dht - NodeMCU Documentation
包括 dht 的固件:📎nodemcv_dht.zip
如果使用的是以下这一款硬件,就直接使用引脚4
2.1. 单独驱动温湿度传感器
dht11Pin = 4
tmr.create():alarm(3000,tmr.ALARM_AUTO ,function()
if conn_flag==1 then
status,
temp,
humi,
temp_dec,
humi_dec = dht.read(dht11Pin)
if status == dht.OK then --根据返回的状态
dht11data=string.format("DHT Temperature:%d.%03d;Humidity:%d.%03d\r\n")
-- 打印
print(dht11data)
-- 在这里直接发送到MQTT上
else
print("dht11 error")
-- 下面这一行是上报到物联网云平台的,如果不想上报直接打印即可
-- m:publish(pub_topic,"[dht11 error",0, 0, function(client) print("sent") end)
end
end
end)
2.2. 完整代码
station_cfg = {}
station_cfg.ssid = "wifi_ssid"
station_cfg.pwd = "wifi_pwd"
station_cfg.auto = false
station_cfg.save = false
-- MQTT配置
mqtt_cfg = {}
mqtt_cfg.host = "broker.emqx.io"
mqtt_cfg.port = 1883
mqtt_cfg.clientid = "alro12345940"
mqtt_cfg.keepalive = 120
mqtt_cfg.username = "AlvaRocha"
mqtt_cfg.password = "aio_KO<safety edit>sXwbgtWCboCal"
sub_topic="/topic/ctiot/dht11/topic/c"
pub_topic="/topic/ctiot/dht11/topic/m"
m=nil
iot_test = mqtt.Client(mqtt_cfg.clientid, mqtt_cfg.keepalive, mqtt_cfg.username, mqtt_cfg.password)
-- wifi配置
wifi.setmode(wifi.STATION)
wifi.sta.config(station_cfg)
-- gpio 配置
pin=3
gpio.mode(pin, gpio.OUTPUT)
conn_flag=0
function get_broker(mqtt_client)
mqtt_client:connect(mqtt_cfg.host, mqtt_cfg.port, false,
function(client)
client:subscribe(sub_topic, 0, function(client)
print("subscribe success ", sub_topic)
end)
m:publish(pub_topic, "success", 0, 0, function(client)
print("init success")
conn_flag=1
end)
end,
function(client, reason)
print('connection failed', reason)
end)
m=mqtt_client
end
iot_test:on("offline", function(client)
print("client offline")
conn_flag=0
get_broker(iot_test)
end)
iot_test:on("message", function(client, topic, data)
--print("MQTT msg received on '" .. topic .. "':")
if data ~= nil
then
print(data)
if data == "1"
then
gpio.write(pin, gpio.HIGH)
print("1111")
end
if data == "2"
then
gpio.write(pin,gpio.LOW)
print("222")
end
end
end)
function startup()
if file.open("init.lua") == nil then
--print("init.lua deleted or renamed")
else
--print("Running")
file.close("init.lua")
get_broker(iot_test)
end
end
wifi_connect_event = function(T)
print("Connection to AP(" .. T.SSID .. ") established!")
print("Waiting for IP address...")
if disconnect_ct ~= nil then
disconnect_ct = nil
end
end
wifi_got_ip_event = function(T)
tmr.create():alarm(3000, tmr.ALARM_SINGLE, startup)
end
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, wifi_connect_event)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wifi_got_ip_event)
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
wifi.sta.connect()
end)
wifi.sta.connect()
dht11Pin = 4
tmr.create():alarm(3000,tmr.ALARM_AUTO ,function()
if conn_flag==1 then
status,
temp,
humi,
temp_dec,
humi_dec = dht.read(dht11Pin)
if status == dht.OK then --根据返回的状态
m:publish(pub_topic, string.format("DHT Temperature:%d.%03d;Humidity:%d.%03d\r\n",
math.floor(temp),
temp_dec,
math.floor(humi),
humi_dec
),
0, 0, function(client) print("sent") end)
else
print("dht11 error")
m:publish(pub_topic,"[dht11 error",0, 0, function(client) print("sent") end)
end
end
end)
3. 完整的代码注释
为了方便各位读者学习,特地将代码加上注释,如下
-- Wi-Fi连接配置
station_cfg = {}
station_cfg.ssid = "wifi_ssid" -- 设置Wi-Fi的SSID
station_cfg.pwd = "wifi_pwd" -- 设置Wi-Fi的密码
station_cfg.auto = false -- 设置Wi-Fi不自动连接
station_cfg.save = false -- 设置不保存Wi-Fi连接信息
-- MQTT连接配置
mqtt_cfg = {}
mqtt_cfg.host = "broker.emqx.io" -- 设置MQTT服务器地址
mqtt_cfg.port = 1883 -- 设置MQTT服务器端口
mqtt_cfg.clientid = "alro12345940" -- 设置MQTT客户端ID
mqtt_cfg.keepalive = 120 -- 设置MQTT保持连接时间
mqtt_cfg.username = "AlvaRocha" -- 设置MQTT用户名
mqtt_cfg.password = "aio_KO<safety edit>sXwbgtWCboCal" -- 设置MQTT密码
sub_topic="/topic/ctiot/dht11/topic/c" -- 设置MQTT订阅主题
pub_topic="/topic/ctiot/dht11/topic/m" -- 设置MQTT发布主题
-- 初始化MQTT客户端
m=nil
iot_test = mqtt.Client(mqtt_cfg.clientid, mqtt_cfg.keepalive, mqtt_cfg.username, mqtt_cfg.password)
-- 设置Wi-Fi模式为Station模式并配置Wi-Fi连接参数
wifi.setmode(wifi.STATION)
wifi.sta.config(station_cfg)
-- 配置GPIO引脚
pin=3
gpio.mode(pin, gpio.OUTPUT)
conn_flag=0 -- 初始化连接标志为0
-- 连接到MQTT服务器并订阅主题的函数
function get_broker(mqtt_client)
mqtt_client:connect(mqtt_cfg.host, mqtt_cfg.port, false,
function(client)
client:subscribe(sub_topic, 0, function(client)
print("subscribe success ", sub_topic)
end)
-- 发布初始化成功消息
m:publish(pub_topic, "success", 0, 0, function(client)
print("init success")
conn_flag=1
end)
end,
function(client, reason)
print('connection failed', reason)
end)
m=mqtt_client
end
-- MQTT客户端离线时的回调函数
iot_test:on("offline", function(client)
print("client offline")
conn_flag=0
get_broker(iot_test)
end)
-- MQTT客户端接收到消息时的回调函数
iot_test:on("message", function(client, topic, data)
if data ~= nil then
print(data)
if data == "1" then
gpio.write(pin, gpio.HIGH)
print("1111")
end
if data == "2" then
gpio.write(pin,gpio.LOW)
print("222")
end
end
end)
-- 设备启动时执行的操作
function startup()
if file.open("init.lua") == nil then
--print("init.lua deleted or renamed")
else
--print("Running")
file.close("init.lua")
get_broker(iot_test)
end
end
-- Wi-Fi连接成功时的事件处理函数
wifi_connect_event = function(T)
print("Connection to AP(" .. T.SSID .. ") established!")
print("Waiting for IP address...")
if disconnect_ct ~= nil then
disconnect_ct = nil
end
end
-- 获取到IP地址时的事件处理函数
wifi_got_ip_event = function(T)
tmr.create():alarm(3000, tmr.ALARM_SINGLE, startup)
end
-- 注册Wi-Fi事件监听器
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, wifi_connect_event)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wifi_got_ip_event)
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
wifi.sta.connect()
end)
wifi.sta.connect()
-- DHT11传感器引脚配置
dht11Pin = 4
-- 定时执行DHT11传感器读取并向MQTT服务器发布数据
tmr.create():alarm(3000,tmr.ALARM_AUTO ,function()
if conn_flag==1 then
status, temp, humi, temp_dec, humi_dec = dht.read(dht11Pin)
if status == dht.OK then
m:publish(pub_topic, string.format("DHT Temperature:%d.%03d;Humidity:%d.%03d\r\n",
math.floor(temp),
temp_dec,
math.floor(humi),
humi_dec
),
0, 0, function(client) print("sent") end)
else
print("dht11 error")
m:publish(pub_topic,"[dht11 error",0, 0, function(client) print("sent") end)
end
end
end)
4. 结语
本小节完成了以下功能:
- 配置Wi-Fi连接参数,使设备能够连接到指定的Wi-Fi网络。
- 配置MQTT连接参数,使设备能够使用MQTT协议与远程服务器通信。
- 设置GPIO引脚的模式和状态,以便设备可以控制外部设备。
- 连接到MQTT服务器并订阅特定主题,以便实时接收来自服务器的消息。
- 当设备收到MQTT消息时,根据消息内容执行相应的操作,例如控制GPIO引脚的状态。
- 在设备启动时执行初始化操作,包括连接到Wi-Fi网络和MQTT服务器。
- 注册Wi-Fi事件监听器,以处理Wi-Fi连接状态变化事件。
- 通过DHT11传感器定时读取环境温湿度数据,并将数据发布到指定的MQTT主题上。
柴头物联网出品