esp8266检测烟雾传感器,火焰传感器,温度的值并使用mqtt协议上传阿里云arduino的代码
时间: 2024-03-03 22:51:00 浏览: 168
好的,下面是代码:
```c++
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// WiFi网络信息
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// 阿里云账号信息
const char* mqtt_server = "your_mqtt_server";
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";
// 烟雾传感器引脚
const int smoke_sensor_pin = D0;
// 火焰传感器引脚
const int flame_sensor_pin = D1;
// 温度传感器引脚
const int temperature_sensor_pin = D2;
// 温度传感器类型
const int temperature_sensor_type = DHT11;
// MQTT客户端
WiFiClient espClient;
PubSubClient client(espClient);
// 温度传感器
DHT dht(temperature_sensor_pin, temperature_sensor_type);
void setup() {
// 初始化串口
Serial.begin(115200);
// 连接WiFi网络
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// 连接MQTT服务器
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT server...");
if (client.connect(mqtt_client_id, mqtt_username, mqtt_password)) {
Serial.println("Connected to MQTT server");
} else {
Serial.print("Failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// 初始化温度传感器
dht.begin();
}
void loop() {
// 检测烟雾传感器
int smoke_sensor_value = analogRead(smoke_sensor_pin);
Serial.print("Smoke sensor value: ");
Serial.println(smoke_sensor_value);
if (smoke_sensor_value > 500) {
Serial.println("Smoke detected");
client.publish(mqtt_topic, "Smoke detected");
}
// 检测火焰传感器
int flame_sensor_value = digitalRead(flame_sensor_pin);
Serial.print("Flame sensor value: ");
Serial.println(flame_sensor_value);
if (flame_sensor_value == LOW) {
Serial.println("Flame detected");
client.publish(mqtt_topic, "Flame detected");
}
// 检测温度传感器
float temperature_value = dht.readTemperature();
Serial.print("Temperature value: ");
Serial.println(temperature_value);
if (!isnan(temperature_value)) {
String temperature_string = String(temperature_value);
client.publish(mqtt_topic, temperature_string.c_str());
}
// 等待一段时间
delay(1000);
}
void callback(char* topic, byte* payload, unsigned int length) {
}
```
需要注意的是,本代码中使用的是阿里云的MQTT服务器,默认端口为1883。如果你使用其他的MQTT服务器,需要修改对应的服务器地址和端口。另外,你还需要将代码中的`your_SSID`、`your_PASSWORD`、`your_mqtt_server`、`your_mqtt_username`、`your_mqtt_password`、`your_mqtt_client_id`、`your_mqtt_topic`修改为你自己的信息。
阅读全文