Created
December 25, 2015 12:56
-
-
Save igrr/6568c330c4197e514be4 to your computer and use it in GitHub Desktop.
ESP8266 + K-30 CO2 Sensor over UART + DHT22 temperature/humidity sensor + MQTT
This file contains 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 <ESP8266WiFi.h> | |
#include <PubSubClient.h> | |
#include <DHT.h> | |
DHT dht(D5, DHT22); | |
const char* ssid = "........"; | |
const char* password = "........"; | |
IPAddress mqttServer(192, 168, 1, 10); | |
WiFiClient mqttTcpClient; | |
PubSubClient mqttClient(mqttTcpClient, mqttServer); | |
void setup() { | |
delay(1000); | |
Serial.begin(9600); | |
Serial.swap(); | |
delay(1000); | |
// We start by connecting to a WiFi network | |
Serial1.begin(115200); | |
Serial1.println(); | |
Serial1.println(); | |
Serial1.print("Connecting to "); | |
Serial1.println(ssid); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial1.print("."); | |
} | |
Serial1.println(""); | |
Serial1.println("WiFi connected"); | |
Serial1.println("IP address: "); | |
Serial1.println(WiFi.localIP()); | |
String clientName = "arduinoClient"; | |
clientName += micros(); | |
for (int retries = 0; retries < 10; ++retries) { | |
Serial1.print("connecting to "); | |
Serial1.println(mqttServer); | |
Serial1.print("Connecting to MQTT broker... as "); | |
Serial1.println(clientName); | |
if (!mqttClient.connect(clientName)) | |
continue; | |
Serial1.println("Connect successful"); | |
break; | |
} | |
} | |
int value = 0; | |
void loop() { | |
delay(5000); | |
Serial1.println("reading co2 level"); | |
const uint8_t request[] = {0xFE, 0x44, 0x00, 0x08, 0x02, 0x9F, 0x25}; | |
Serial.write(request, sizeof(request)); | |
uint8_t response[8]; | |
int t = millis(); | |
for (int i = 0; i < 7; ++i) { | |
if (Serial.available()) { | |
response[i] = Serial.read(); | |
} | |
if (millis() - t > 1000) { | |
Serial1.println("no response"); | |
return; | |
} | |
} | |
int co2value = static_cast<int>(response[3]) * 256 + static_cast<int>(response[4]); | |
Serial1.print("co2:"); | |
Serial1.println(co2value); | |
if (co2value > 2000) | |
return; | |
mqttClient.publish("/sensor/office/co2", String(co2value)); | |
float h = dht.readHumidity(); | |
char buf[20]; | |
dtostrf(h, 2, 0, buf); | |
Serial1.print("humidity:"); | |
Serial1.println(buf); | |
mqttClient.publish("/sensor/office/humidity", String(buf)); | |
float temp = dht.readTemperature(); | |
dtostrf(temp, 2, 1, buf); | |
Serial1.print("temperature:"); | |
Serial1.println(buf); | |
mqttClient.publish("/sensor/office/temperature", String(buf)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment