Skip to content

Instantly share code, notes, and snippets.

@ajsb85
Forked from shantanoo-desai/MQTT_GraphQL_IoT.ino
Created June 19, 2021 03:34
Show Gist options
  • Save ajsb85/5ba2b90bc528d8a105d6a58a5e92da9d to your computer and use it in GitHub Desktop.
Save ajsb85/5ba2b90bc528d8a105d6a58a5e92da9d to your computer and use it in GitHub Desktop.
Arduino Sketch to publish BME280 sensor data in JSON Format to an MQTT Broker
#include<Wire.h>
#include<PubSubClient.h>
#include<WiFi.h>
#include<Adafruit_BME280.h>
#include <ArduinoJson.h>
/*
* WLAN Configuration
*/
const char* ssid = "YOUR_SSID"; // FILL THIS ACCORDINGLY
const char* password = "YOUR_PASSWORD"; // FILL THIS ACCORDINGLY
/*
* MQTT Broker configuration + Topic
*/
const char* mqtt_broker = "mqtt.eclipse.org"; // CHANGE THIS ACCORDINGLY
const char* topic = "test/1/env"; // CHANGE SensorID here!
/*
* NTP Server Configuration for TimeStamps
*/
const char* ntp_server = "pool.ntp.org";
WiFiClient espClient;
PubSubClient client(espClient);
Adafruit_BME280 bme;
/*
* JSON Data Format
*/
const size_t capacity = JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(3);
DynamicJsonDocument doc(capacity);
JsonObject data = doc.createNestedObject("data");
float temp, humid = 0.0;
char output[128];
/*
* getLocalTimeNTP: Get Epoch Time Stamp from NTP server
*/
unsigned long getLocalTimeNTP() {
time_t now;
struct tm timeinfo;
if(!getLocalTime(&timeinfo)) {
Serial.println("Failed to obtain time");
return 0;
}
time(&now);
return now;
}
/*
* reconnect: connect/reconnect to MQTT broker
*/
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
Wire.begin(13, 16); // Needed if using Olimex POE Boards
bme.begin();
Serial.println("BME280 setup complete");
WiFi.begin(ssid, password);
configTime(0, 0, ntp_server);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi Connected");
Serial.println("IP Address: ");
Serial.println(WiFi.localIP());
delay(1000);
client.setServer(mqtt_broker, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Creating JSON Format
data["temp"].set(bme.readTemperature());
data["humid"].set(bme.readHumidity());
data["time"].set(getLocalTimeNTP());
// Output Format
serializeJson(doc, output);
Serial.println(output); // Data Format
client.publish(topic, output);
delay(2000); // Publish data every 2 seconds to the Broker
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment