Created
August 2, 2019 14:40
-
-
Save JonasDoesThings/b422618820dec6236c41c187340fd4a0 to your computer and use it in GitHub Desktop.
SDS011 + DHT22 + ESP8266 + MQTT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Arduino.h> | |
#include <Adafruit_Sensor.h> | |
#include <DHT.h> | |
#include <SDS011.h> | |
#include <ESP8266WiFi.h> | |
#include <PubSubClient.h> | |
#define mqttIP "MQTT IP" | |
#define mqttPort 1883 | |
#define mqttUsername "MQTT USERNAME" | |
#define mqttPassword "MQTT PASSWORD" | |
#define wifiSSID "WIFI SSID" | |
#define wifiPassword "WIFI PASSWORD" | |
#define measureDelay 10000 | |
WiFiClient client; | |
PubSubClient mqttClient(client); | |
#define D22DATA D3 | |
DHT dht22(D22DATA, DHT22); | |
float temperature, humidity; | |
#define SDS011TX D1 | |
#define SDS011RX D2 | |
SDS011 sds011Sensor; | |
float p10, p25; | |
int sds011Error; | |
void setup() { | |
Serial.begin(9600); | |
dht22.begin(); | |
sds011Sensor.begin(SDS011TX, SDS011RX); | |
WiFi.mode(WIFI_STA); | |
WiFi.begin(wifiSSID, wifiPassword); | |
Serial.println("Connecting to WiFi"); | |
while(WiFi.status() != WL_CONNECTED) { | |
Serial.print("."); | |
delay(150); | |
} | |
mqttClient.setServer(mqttIP, mqttPort); | |
} | |
void mqttConnect() { | |
while(!mqttClient.connected()) { | |
String clientId = mqttUsername; | |
clientId += "-" + String(millis()); | |
if(mqttClient.connect(clientId.c_str(), mqttUsername, wifiPassword)) { | |
Serial.println("Connected to MQTT!"); | |
} else { | |
Serial.print("Couldn't connect to MQTT, rc="); | |
Serial.print(mqttClient.state()); | |
Serial.println(); | |
delay(5000); | |
} | |
} | |
} | |
void loop() { | |
if(!WiFi.isConnected()) { | |
Serial.println("Lost WiFi Connection"); | |
WiFi.reconnect(); | |
} | |
if(!mqttClient.connected()) { | |
Serial.println("MQTTClient lost connection!"); | |
mqttConnect(); | |
delay(50); | |
} | |
mqttClient.loop(); | |
temperature = dht22.readTemperature(); | |
humidity = dht22.readHumidity(); | |
sds011Error = sds011Sensor.read(&p25, &p10); | |
if(sds011Error) { | |
Serial.println("Error while reading SDS011!"); | |
} | |
char buf[8]; | |
dtostrf(temperature, 6, 2, buf); | |
mqttClient.publish("workspace/air/temperature", buf); | |
dtostrf(humidity, 6, 2, buf); | |
mqttClient.publish("workspace/air/humidity", buf); | |
dtostrf(p25, 6, 2, buf); | |
mqttClient.publish("workspace/air/pm25", buf); | |
dtostrf(p10, 6, 2, buf); | |
mqttClient.publish("workspace/air/pm10", buf); | |
delay(measureDelay); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment