#include "DHTesp.h"
#include <WiFi.h>
#include <PubSubClient.h>
#include <ThingSpeak.h>
#include <RTClib.h>
const int trig = 32;
const int echo = 33;
int statusCode;
RTC_DS3231 rtc; // Create an instance of the RTC DS3231 object
void tdmy();
long duration;
float distance;
#define SECRET_SSID "Wokwi-GUEST" // replace with your WiFi network name
#define SECRET_PASS "" // replace with your WiFi password
#define SECRET_CH_ID 2463312 // replace with your channel number
#define SECRET_CH_IDr 2022763
#define SECRET_WRITE_APIKEY "WMFJMT9UXRM04XOF" // replace with your channel write API Key
#define SECRET_READ_APIKEY "47HAAS2M6GPPTY0E" // replace with your channel read API Key
#define MQTT_BROKER "broker.mqttdashboard.com"
#define MQTT_CLIENT_ID "micropython-weather-demo"
#define MQTT_TOPIC_TEMPERATURE "wokwi-weather"
#define MQTT_TOPIC_HUMIDITY "wokwi-weather"
#define MQTT_TOPIC_DISTANCE "wokwi-weather"
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_PASS; // your network password
WiFiClient client;
PubSubClient mqttClient(client);
unsigned long myChannelNumber = SECRET_CH_ID;
unsigned long readmyChannelNumber = SECRET_CH_IDr;
const char* myWriteAPIKey = SECRET_WRITE_APIKEY;
const char* myReadAPIKey = SECRET_READ_APIKEY;
unsigned int dataFieldOne = 1;
float aConst = 2.25E-02;
const int DHT_PIN = 15;
DHTesp dhtSensor;
void setup() {
Serial.begin(115200);
pinMode(7, OUTPUT);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(18, OUTPUT);
WiFi.mode(WIFI_STA); // Set Wi-Fi to station mode
connectToWiFi();
ThingSpeak.begin(client); // Initialize ThingSpeak
mqttClient.setServer(MQTT_BROKER, 1883); // Initialize MQTT
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) {
Serial.println("RTC lost power, let's set the time!");
// When time needs to be set on a new device or after a power loss, the
// following line sets the RTC to the date & time this sketch was compiled
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void connectToWiFi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi.");
}
void reconnectMQTT() {
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
if (mqttClient.connect(MQTT_CLIENT_ID)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
connectToWiFi();
}
if (!mqttClient.connected()) {
reconnectMQTT();
}
mqttClient.loop();
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
distance = duration * 0.034 / 2;
if( distance<=100)
{
tone(4,100,100);
delay(100);
noTone(4);
delay(200);
}
TempAndHumidity data = dhtSensor.getTempAndHumidity();
Serial.println("----------------------------------------------------");
tdmy();
Serial.println("Temp : " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("Distance: " + String(distance) + " cm");
Serial.println("----------------------------------------------------");
if (mqttClient.publish(MQTT_TOPIC_TEMPERATURE, ("Temperature: "+ String(data.temperature, 2)).c_str())) {
Serial.println("Temperature data published successfully");
} else {
Serial.print("Failed to publish temperature data. Error code: ");
Serial.println(mqttClient.state());
}
if (mqttClient.publish(MQTT_TOPIC_HUMIDITY, ("Humidity: "+String(data.humidity, 1)).c_str())) {
Serial.println("Humidity data published successfully");
} else {
Serial.print("Failed to publish humidity data. Error code: ");
Serial.println(mqttClient.state());
}
if (mqttClient.publish(MQTT_TOPIC_DISTANCE,("Distance: "+ String(distance)).c_str())) {
Serial.println("Distance data published successfully");
} else {
Serial.print("Failed to publish distance data. Error code: ");
Serial.println(mqttClient.state());
}
// ThingSpeak
ThingSpeak.setField(1, data.temperature);
ThingSpeak.setField(2, data.humidity);
ThingSpeak.setField(3, distance);
statusCode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
aConst = readTSData(readmyChannelNumber, dataFieldOne);
Serial.println(aConst);
if (aConst == 1) {
digitalWrite(18, HIGH);
Serial.println("Relay on");
} else {
digitalWrite(18, LOW);
Serial.println("Relay off");
}
delay(1500); // data to be uploaded every 15secs
}
float readTSData(long TSChannel, unsigned int TSField) {
float data = ThingSpeak.readFloatField(TSChannel, TSField, myReadAPIKey);
return data;
}
void tdmy()
{
DateTime now = rtc.now(); // Get the current time from the RTC
Serial.print(now.day(), DEC);
Serial.print(".");
Serial.print(now.month(), DEC);
Serial.print('.');
Serial.print(now.year(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
delay(1000); // Wait for a second
}