连接并编写传感器节点代码
读取环境数据,并通过 MQTT 发布
连接并编写传感器节点代码 是 CoddyKit 上的免费 Arduino & IoT Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Arduino & IoT Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Arduino & IoT Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Build the Node
现在,你要将方案转化为硬件。你需要将 DHT22 连接到 ESP32,并编写代码来读取气候数据并将其发布。🔌
Wire Power and Ground
将 DHT22 的 VCC 连接到 ESP32 的 3.3V 引脚,并将 GND 连接到地(GND)。共地是让两个部件在信号上保持一致的基础。
Wire the Data Pin
Run the sensor's data line to a GPIO pin and add a pull-up resistor so the idle line stays clean and reads reliably.
Include Your Libraries
At the top of the sketch, pull in the tools you need: the DHT library for the sensor and PubSubClient for MQTT.
#include <DHT.h>
#include <WiFi.h>
#include <PubSubClient.h>Create the Sensor Object
Tell the library which pin and sensor type you used by creating a DHT object. This becomes your handle for every reading.
#define DHTPIN 4
DHT dht(DHTPIN, DHT22);Start Things in setup()
In setup() you open Serial, start the sensor with dht.begin(), and connect to WiFi so the node is ready before the loop runs.
void setup() {
Serial.begin(115200);
dht.begin();
}Read Temperature & Humidity
Each cycle, call readTemperature() and readHumidity() to grab fresh numbers from the room into two variables.
float t = dht.readTemperature();
float h = dht.readHumidity();Guard Against Bad Reads
Sensors sometimes return NaN. Check isnan() and skip publishing that round so you never send junk to the cloud.
if (isnan(t) || isnan(h)) {
return;
}Connect to the Broker
Point PubSubClient at your broker's address and port, then keep a reconnect helper so a dropped link is rejoined automatically.
client.setServer(BROKER, 1883);Publish a Reading
Send each value to its topic with client.publish(). The cloud now receives a fresh temperature every cycle.
client.publish("home/livingroom/temp", String(t).c_str());Pace the Loop
Don't flood the network. Use millis() timing to publish about once every few seconds, which is plenty for room climate.
Quick Check
Test your sensor-node code.
Recap
You wired the DHT22, read clean values, guarded bad reads, and published them over MQTT. Your sensor node is alive and talking. 📡
常见问题解答
「连接并编写传感器节点代码」课时是免费的吗?
是的 — 「连接并编写传感器节点代码」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Arduino & IoT Academy 课程的其余内容,请升级到 CoddyKit PRO。 Arduino & IoT Academy 课程共包含 4 节课。
「连接并编写传感器节点代码」这节课中我会学到什么?
读取环境数据,并通过 MQTT 发布 你通过在浏览器中直接运行的动手代码来练习 Arduino & IoT Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Arduino & IoT Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Arduino & IoT Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「连接并编写传感器节点代码」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Arduino & IoT Academy 课中编写并运行代码吗?
能。每节 Arduino & IoT Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 规划端到端架构
- 连接并编写传感器节点代码
- 构建云端仪表盘与警报
- 在现场部署、监控与更新