在arduino uno中使用DHT11监测温度湿度,MQ135监测co2、甲醛。GP2Y1014AU监测PM2.5浓度。当温度大于35摄氏度或者小于20摄氏度,蜂鸣器报警LDE灯闪烁。
时间: 2023-05-13 22:06:48 浏览: 478
带有Arduino代码的Arduino和MQ 135气体传感器-电路方案
可以使用以下代码实现:
```
#include <DHT.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_MQTT_Client.h>
#include <Adafruit_MQTT.h>
#include <Adafruit_MQTT_Simple.h>
#include <SoftwareSerial.h>
#define DHTPIN 2
#define DHTTYPE DHT11
#define CO2PIN A0
#define PM2_5PIN A1
#define BUZZERPIN 3
#define LEDPIN 4
DHT dht(DHTPIN, DHTTYPE);
SoftwareSerial mySerial(10, 11); // RX, TX
Adafruit_MQTT_Client mqtt(&myClient, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
Adafruit_MQTT_Publish temperature = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temperature");
Adafruit_MQTT_Publish humidity = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/humidity");
Adafruit_MQTT_Publish co2 = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/co2");
Adafruit_MQTT_Publish formaldehyde = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/formaldehyde");
Adafruit_MQTT_Publish pm2_5 = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/pm2_5");
void setup() {
Serial.begin(9600);
dht.begin();
mySerial.begin(9600);
pinMode(BUZZERPIN, OUTPUT);
pinMode(LEDPIN, OUTPUT);
}
void loop() {
float t = dht.readTemperature();
float h = dht.readHumidity();
int co2Value = analogRead(CO2PIN);
int pm2_5Value = analogRead(PM2_5PIN);
if (isnan(t) || isnan(h)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C");
Serial.print("Humidity: ");
Serial.print(h);
Serial.println(" %");
temperature.publish(t);
humidity.publish(h);
co2.publish(co2Value);
formaldehyde.publish(formaldehydeValue);
pm2_5.publish(pm2_5Value);
if (t > 35 || t < 20) {
digitalWrite(BUZZERPIN, HIGH);
digitalWrite(LEDPIN, HIGH);
} else {
digitalWrite(BUZZERPIN, LOW);
digitalWrite(LEDPIN, LOW);
}
delay(2000);
}
```
这段代码使用了 DHT 库、Wire 库、Adafruit_Sensor 库、Adafruit_MQTT_Client 库、Adafruit_MQTT 库、Adafruit_MQTT_Simple 库、SoftwareSerial 库,可以通过串口监视器输出温度、湿度、CO2、甲醛、PM2.5 的值,并将这些值通过 MQTT 协议上传到云端。当温度大于 35 摄氏度或者小于 20 摄氏度时,蜂鸣器报警,LED 灯闪烁。
阅读全文