Created
December 10, 2019 17:01
-
-
Save Dvorson/8d6ba540154b8d137a59175f78a28926 to your computer and use it in GitHub Desktop.
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 "MHZ19.h" | |
#include <SoftwareSerial.h> | |
#include <ESP8266WiFi.h> | |
#include <PubSubClient.h> | |
#define RX_PIN 12 | |
#define TX_PIN 13 | |
#define BAUDRATE 9600 | |
MHZ19 myMHZ19; | |
SoftwareSerial mySerial(RX_PIN, TX_PIN); | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
unsigned long getDataTimer = 0; | |
const char* ssid = "........."; | |
const char* password = "........"; | |
const char* mqtt_server = "........"; | |
void reconnect() { | |
while (!client.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
// Create a random client ID | |
String clientId = "ESP8266_MH-Z19"; | |
// Attempt to connect | |
if (client.connect(clientId.c_str())) { | |
Serial.println("connected"); | |
} else { | |
Serial.print("failed, rc="); | |
Serial.print(client.state()); | |
Serial.println(" try again in 5 seconds"); | |
delay(5000); | |
} | |
} | |
} | |
void setup() { | |
Serial.begin(9600); | |
Serial.println(); | |
Serial.print("Connecting to "); | |
Serial.println(ssid); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
client.setServer(mqtt_server, 1883); | |
mySerial.begin(BAUDRATE); | |
myMHZ19.begin(mySerial); | |
myMHZ19.autoCalibration(false); | |
} | |
void loop() { | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
if (millis() - getDataTimer >= 10000) { | |
int CO2; | |
CO2 = myMHZ19.getCO2(); | |
Serial.print("CO2 (ppm): "); | |
Serial.println(CO2); | |
int8_t Temp; | |
Temp = myMHZ19.getTemperature(); | |
Serial.print("Temperature (C): "); | |
Serial.println(Temp); | |
String pubStr = "{\"co2\":" + String(CO2) + ",\"tmp\":" + String(Temp) + "}"; | |
client.beginPublish("........", pubStr.length(), false); | |
client.print(pubStr); | |
client.endPublish(); | |
getDataTimer = millis(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment