Skip to content

Instantly share code, notes, and snippets.

@f1dz
Created March 28, 2021 12:09
Show Gist options
  • Save f1dz/712eb8e0ab5e029b100619f2c40d4961 to your computer and use it in GitHub Desktop.
Save f1dz/712eb8e0ab5e029b100619f2c40d4961 to your computer and use it in GitHub Desktop.
RSS #20 Demo IoT in Action Using MQTT
/**
* Written by offiedz@gmail.com
* 28 March 2021
* To use this script you should using ESP32, DHT22 sensor and LCD SSD1306
* Please comment when you got any issue
*/
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#include "SSD1306Wire.h"
#include <ArduinoJson.h>
#define DHTPIN 15 // what digital pin the DHT22 is conected to
#define DHTPIN2 23
#define DHTTYPE DHT22 // There are multiple kinds of DHT sensors
DHT dht(DHTPIN, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
SSD1306Wire display(0x3c, 18, 19);
// WiFi credentials.
const char* WIFI_SSID = "";
const char* WIFI_PASS = "";
// Broker
const char* mqtt_server = "";
WiFiClient wifiClient;
PubSubClient client(wifiClient);
float temperature=0, suhu = 0;
float humidity=0, lembab = 0;
const int ledPin = 4;
long lastMsg = 0;
char msg[50];
int value = 0;
String mac;
void setup() {
Serial.begin(9600);
dht.begin();
dht2.begin();
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(ledPin, OUTPUT);
display.init();
display.flipScreenVertically();
display.setFont(ArialMT_Plain_16);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASS);
mac = WiFi.macAddress();
mac.replace(":", "");
mac.toLowerCase();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
// Feel free to add more if statements to control more GPIOs with MQTT
// If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
// Changes the output state according to the message
if (String(topic) == "temptron/output") {
Serial.print("Changing output to ");
if(messageTemp == "on"){
Serial.println("on");
digitalWrite(ledPin, HIGH);
}
else if(messageTemp == "off"){
Serial.println("off");
digitalWrite(ledPin, LOW);
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe
client.subscribe("temptron/output");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
char tempString[8];
char humString[8];
char suhuString[8];
char lembabString[8];
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 5000) {
lastMsg = now;
// Temperature in Celsius
temperature = dht.readTemperature();
// Uncomment the next line to set temperature in Fahrenheit
// (and comment the previous temperature line)
//temperature = 1.8 * bme.readTemperature() + 32; // Temperature in Fahrenheit
suhu = dht2.readTemperature();
// Convert the value to a char array
// char tempString[8];
dtostrf(temperature, 1, 2, tempString);
dtostrf(suhu, 1, 2, suhuString);
Serial.print("Temperature: ");
Serial.println(tempString);
humidity = dht.readHumidity();
lembab = dht2.readHumidity();
// Convert the value to a char array
// char humString[8];
dtostrf(humidity, 1, 2, humString);
dtostrf(lembab, 1, 2, lembabString);
Serial.print("Humidity: ");
Serial.println(humString);
StaticJsonBuffer<500> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonObject& data = jsonBuffer.createObject();
data["tempA"] = temperature;
data["tempB"] = suhu;
data["humidityA"] = humidity;
data["humidityB"] = lembab;
root["data"] = data;
root["deviceId"] = mac;
char buffer[200];
root.printTo(buffer);
client.publish("temptron/json", buffer);
String deviceTopic = mac + "/state";
char topic[20];
deviceTopic.toCharArray(topic, 20);
client.publish(topic, buffer);
}
drawFontFaceDemo(tempString, humString, suhuString, lembabString);
}
void drawFontFaceDemo(char *temp, char *hum, char *suhu, char *lembab) {
//char *degree = "C";
// clear the display
display.clear();
// Font Demo1
// create more fonts at http://oleddisplay.squix.ch/
display.drawRect(0, 0, 128, 48);
display.drawLine(0, 16, 128, 16);
display.drawLine(64, 0, 64, 47);
display.drawRect(0, 64, 64, 34);
display.setTextAlignment(TEXT_ALIGN_LEFT);
display.setFont(ArialMT_Plain_16);
// HEADER
display.fillRect(0,0,128,16);
display.setColor(BLACK);
display.drawString(7, 0, "ATAS");
display.drawString(66, 0, "BAWAH");
display.setColor(WHITE);
// ATAS
display.drawString(3, 15, temp);
display.drawString(48, 15, "C");
display.drawString(3, 31, hum);
display.drawString(48, 31, "%");
// BAWAH
display.drawString(67, 15, suhu);
display.drawString(110, 15, "C");
display.drawString(67, 31, lembab);
display.drawString(110, 31, "%");
// write the buffer to the display
// display.fillRect(0,48,128,16);
display.display();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment