#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHT_PIN 19 // Pin connected to the DHT sensor
#define DHT_TYPE DHT22 // DHT type (DHT11, DHT22, AM2302)
// Defining Pins
#define LED1 15
#define LED2 2
#define FAN1 4
#define FAN2 16
#define echoPIN 5
#define trgPIN 17
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
DHT dht(DHT_PIN, DHT_TYPE);
// MQTT Credentials
const char* ssid = "Wokwi-GUEST"; // Setting your AP SSID
const char* password = ""; // Setting your AP PSK
const char* mqttServer = "91.121.93.94";
// const char* mqttUserName = "bqzbdodo";
// const char* mqttPwd = "5oU2W_QN2WD8";
const char* clientID = "ujaisldaaasdh;laslsdja1"; // Client ID username+0001
const char* topic = "project-smart-house/led1"; // Publish topic
unsigned long previousMillis = 0;
const long interval = 1000000; // Interval in microseconds (2 seconds)
long dur, distance;
String msgStr = ""; // MQTT message buffer
bool LEDstate1 = LOW;
bool LEDstate2 = LOW;
bool FANstatus1 = LOW;
bool FANstatus2 = LOW;
int ctr = 0;
int tankPercentage = 0;
float humidity;
float temperature;
// Setting up WiFi and MQTT client
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password,6);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
while (!client.connected()) {
if (client.connect(clientID)) {
Serial.println("MQTT connected");
client.subscribe("project-smart-house/led1");
client.subscribe("project-smart-house/led2");
client.subscribe("project-smart-house/fan1");
client.subscribe("project-smart-house/fan2");
client.subscribe("project-smart-house/tank");
Serial.println("Topic Subscribed");
}
else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000); // wait 5sec and retry
}
}
}
// Subscribe callback
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message: ");
String data = "";
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
data += (char)payload[i];
}
Serial.println();
Serial.println(data);
if (String(topic) == "project-smart-house/tank") {
tankPercentage = data.toInt();
}
if (String(topic) == "project-smart-house/led1") {
LEDstate1 = (data == "1");
digitalWrite(LED1,(data == "1"));
} else if (String(topic) == "project-smart-house/led2") {
LEDstate2 = (data == "1");
digitalWrite(LED2,(data == "1"));
} else if (String(topic) == "project-smart-house/fan1") {
FANstatus1 = (data == "1");
digitalWrite(FAN1,(data == "1"));
} else if (String(topic) == "project-smart-house/fan2") {
FANstatus2 = (data == "1");
digitalWrite(FAN2,(data == "1"));
}
}
void setup() {
// Initialize with the I2C addr 0x3C (for the 128x64)
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
}
Serial.begin(115200);
// Initialize device.
Serial.println("Starting....");
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(FAN1, OUTPUT);
pinMode(FAN2, OUTPUT);
pinMode( echoPIN, INPUT);
pinMode( trgPIN, OUTPUT);
setup_wifi();
client.setServer(mqttServer, 1883); // Setting MQTT server
client.setCallback(callback);
dht.begin();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
}
void loop() {
if (!client.connected()) { // If client is not connected
reconnect(); // Try to reconnect
}
client.loop();
unsigned long currentMillis = micros(); // Get the current time in microseconds
if (currentMillis - previousMillis >= interval) {
// It's time to do something
getWaterPercentage();
ctr++ ;
previousMillis = currentMillis; // Save the last time the function was called
}
updateDisplay();
if (ctr == 5){
ctr = 0;
SendWeatherData();
}
}
void getWaterPercentage(){
int prevPer = tankPercentage;
//Giving 10 microseconds Pulse to trigger pin
digitalWrite(trgPIN,LOW);
delayMicroseconds(2);
digitalWrite(trgPIN,HIGH);
delayMicroseconds(10);
digitalWrite(trgPIN,LOW);
dur = pulseIn(echoPIN,HIGH);
//For changing time into distance
distance = dur*0.034/2;
tankPercentage = map(distance, 0 , 400, 100, 0);
// Convert int tankPercentage to string and publish
if(prevPer != tankPercentage){
msgStr = String(tankPercentage);
char msgPercentage[6]; // Maximum 5 characters for digits + 1 for null terminator
msgStr.toCharArray(msgPercentage, sizeof(msgPercentage));
client.publish("project-smart-house/tank", msgPercentage);
}
}
void drawLEDStatus(int x, int y, bool status) {
// Draw a rectangle to represent LED status
if (status) {
display.fillRect(x, y, 9, 9, SSD1306_WHITE); // LED is on
} else {
display.drawRect(x, y, 9, 9, SSD1306_WHITE); // LED is off
}
}
void drawWaterTank(int x, int y, int percentage) {
// Draw water tank outline
display.drawRect(x, y, 94, 14, SSD1306_WHITE);
// Calculate width of the filled portion based on the percentage
int filledWidth = map(percentage, 0, 100, 0, 94);
// Draw filled portion of the water tank
display.fillRect(x, y, filledWidth, 14, SSD1306_WHITE);
// Display percentage
display.setCursor(x + 97, y + 3);
display.print(percentage);
display.print("%");
}
void updateDisplay(){
// Clear the display
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
//display.drawRect(0,0,128,64,SSD1306_WHITE);
display.setCursor(32, 2);
display.print("Water Tank");
// Draw water tank capacity
drawWaterTank(4, 12, tankPercentage); // Example: Water tank at 75%
/**************************************************/
display.drawLine(0,31,127,31,SSD1306_WHITE);
display.drawLine(0,33,127,33,SSD1306_WHITE);
// Draw LED status indicators
display.setCursor(8, 40);
display.print("LED1:");
// Draw LED1 status, change X position if necessary
drawLEDStatus(40, 39, LEDstate1); // Change the last argument to false for off
display.setCursor(68, 40);
display.print("LED2:");
// Draw LED2 status
drawLEDStatus(100, 39, LEDstate2); // Example: LED2 is off
display.setCursor(8, 54);
display.print("FAN1:");
// Draw FAN1 status
drawLEDStatus(40, 53, FANstatus1); // Example: FAN1 is on
display.setCursor(68, 54);
display.print("FAN2:");
// Draw FAN2 status
drawLEDStatus(100, 53, FANstatus2); // Example: FAN2 is off
display.display();
}
void SendWeatherData(){
humidity = dht.readHumidity(); // Read humidity (in %)
temperature = dht.readTemperature();
msgStr = String(temperature);
msgStr = msgStr + "°C" ;
char msgTemp[9]; // Maximum 5 characters for digits + 1 for null terminator
msgStr.toCharArray(msgTemp, sizeof(msgTemp));
client.publish("project-smart-house/temp", msgTemp);
msgStr = String(humidity);
msgStr = msgStr + "%" ;
char msgHumidity[8]; // Maximum 5 characters for digits + 1 for null terminator
msgStr.toCharArray(msgHumidity, sizeof(msgHumidity));
client.publish("project-smart-house/humidity", msgHumidity);
}