写一个用arudino开发的温湿度传感器传送数据到MOTT服务器的代码
时间: 2024-02-13 17:04:19 浏览: 71
以下是一个基于Arduino开发的温湿度传感器上传数据到MQTT服务器的示例代码:
```c++
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <WiFi.h>
#include <PubSubClient.h>
// Wi-Fi参数
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// MQTT参数
const char* mqtt_server = "your_MQTT_server_address";
const char* mqtt_username = "your_MQTT_username";
const char* mqtt_password = "your_MQTT_password";
const char* mqtt_client_id = "your_MQTT_client_id";
const char* mqtt_topic = "your_MQTT_topic";
// DHT传感器参数
#define DHTPIN 4 // DHT传感器连接的引脚
#define DHTTYPE DHT11 // DHT11型号
DHT dht(DHTPIN, DHTTYPE);
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
delay(10);
// 连接Wi-Fi
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// 连接MQTT服务器
client.setServer(mqtt_server, 1883);
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect(mqtt_client_id, mqtt_username, mqtt_password)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" retrying in 5 seconds");
delay(5000);
}
}
// 初始化DHT传感器
dht.begin();
}
void loop() {
delay(2000);
// 读取温湿度数据
float h = dht.readHumidity();
float t = dht.readTemperature();
// 检查是否读取成功
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// 将温湿度数据转换为JSON格式
String payload = "{\"temperature\":";
payload += t;
payload += ",\"humidity\":";
payload += h;
payload += "}";
// 将数据发布到MQTT服务器
Serial.print("Publishing to ");
Serial.print(mqtt_topic);
Serial.print(" -> ");
Serial.println(payload);
client.publish(mqtt_topic, payload.c_str());
}
```
在上面的代码中,我们使用了DHT库来读取温湿度传感器的数据,并使用WiFi和PubSubClient库连接到MQTT服务器并将数据发布到指定的主题上。需要将代码中的Wi-Fi和MQTT参数替换为自己的参数才能正常工作。
阅读全文