#include <WiFi.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <PubSubClient.h>
//#include <Servo.h>
#include <ESP32Servo.h>
// Pin Definitions
#define UTC_OFFSET 0
#define UTC_OFFSET_DST 0
#define pinoLedAmarelo 17
#define alarmLedAmarelo 2
#define DHTPIN 15 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)
#define ServoMotorPIN 16
// Blynk Configuration
#define BLYNK_TEMPLATE_ID "TMPL5rXTiJpIJ"
#define BLYNK_TEMPLATE_NAME "ESP32 IoT Template"
#define BLYNK_AUTH_TOKEN "wUz2JM2KoXzLt0awtD8fCmdN0a2jTOEk"
#include <BlynkSimpleEsp32.h>
#define ID_MQTT "SENAI_IOT101"
// Global Variables
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);
DHT dht(DHTPIN, DHTTYPE);
BlynkTimer timer;
Servo servo; // ervoMotor
WiFiClient wifiClient;
PubSubClient client (wifiClient); // Instantiation of MQTT
// Fields
const int GREEN_LED_PIN = 2;
const int BLUE_LED_PIN = 4;
const int LED_PIN = 17;
const int buzzerPin = 5;
const float TEMP_THRESHOLD = 60; // Temperature threshold
const float HUMIDITY_THRESHOLD = 60.0; // Humidity threshold
float lastTemperature = 37; // Initialize last temperature value to an unlikely value
float lastHumidity = 50; // Initialize last humidity value to an unlikely value
int loadingState = 0;
int powerState = 1;
float pos = 0.0; // Variable where the arm's position will be stored (in degrees)
float step = 1.0; // Variable used for the arm's position step
int servoPosition = 180;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
char auth[] = "wUz2JM2KoXzLt0awtD8fCmdN0a2jTOEk";
// MQTT Broker Configuration
const char* msg_broker_username = "xhBHGzEHwCVkdfP4kQu3BuHh0HakqcISm3W3VSWfil6Ov5wD7I5MchNaXSVBaUhu"; // token
const char* msg_broker_username_password = "Principal160";
const char* msg_broker_server = "mqtt.flespi.io"; //URL do broker MQTT que se deseja utilizar
int msg_broker_server_port = 1883;
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (500)
char msg[MSG_BUFFER_SIZE];
int value = 0;
char clientId[50];
// Function Prototypes
void setup();
void loop();
void heartBeat(float temperature, float humidity);
void sendToBlynk();
void powerOff();
void turgleServo(float temperature);
void alertBuzzer();
void ConnectMQTT();
void callback(char* topic, byte* payload, unsigned int length);
void initDisplay ();
void setup() {
Serial.begin(115200);
Blynk.begin(auth, ssid, pass);
pinMode(LED_PIN,OUTPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(GREEN_LED_PIN , OUTPUT);
pinMode(BLUE_LED_PIN , OUTPUT);
// Initializing welcome messages
initDisplay();
// Attach the servo motor to the specified pin
servo.attach(ServoMotorPIN);
client.setServer(msg_broker_server, msg_broker_server_port);
client.setCallback(callback);
// Initializing Wifi connection
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
}
// Invoking MQQT connection
ConnetMQTT();
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
LCD.clear();
LCD.setCursor(0, 0);
LCD.println("Loading .......");
delay(3000);
timer.setInterval(100L, sendToBlynk);
}
void loop() {
float temperature = dht.readTemperature(); // Read temperature in Celsius
float humidity = dht.readHumidity();
ConnetMQTT();
turgleServo(temperature);
delay(1000);
Blynk.run();
timer.run();
if (powerState == 1) {
heartBeat(temperature,humidity);
}
}
void heartBeat(float temperature, float humidity){
digitalWrite(LED_PIN, HIGH); // Turn on the LED
// Turn on the LED
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
if(loadingState == 0)
{
LCD.clear();
LCD.setCursor(0, 0);
LCD.println("Temp loading .....");
LCD.setCursor(0, 1);
LCD.println("Humidity loading .....");
delay(2000);
loadingState = 1;
// Clear the LCD
LCD.clear();
// Display temperature
LCD.setCursor(0, 0); // Set cursor to column 0, row 0
LCD.print("Temp: ");
LCD.print(temperature);
LCD.print(" C");
// Display humidity
LCD.setCursor(0, 1); // Set cursor to column 0, row 1
LCD.print("Humidity: ");
LCD.print(humidity);
LCD.print(" %");
//servo.attach(ServoMotorPIN);
};
// Check if temperature or humidity exceeds thresholds
if (temperature > TEMP_THRESHOLD && humidity > HUMIDITY_THRESHOLD) {
alertBuzzer();
digitalWrite(GREEN_LED_PIN, HIGH);
digitalWrite(BLUE_LED_PIN, HIGH);
delay(1000);
// Both temperature and humidity exceeded thresholds
// Blue LED blink
// You can add your code here for blue LED blinking
} else if (temperature > TEMP_THRESHOLD) {
alertBuzzer();
digitalWrite(GREEN_LED_PIN, HIGH);
digitalWrite(BLUE_LED_PIN, LOW);
delay(1000);
// Temperature exceeded threshold
// Green LED blink
// You can add your code here for green LED blinking
} else if (humidity > HUMIDITY_THRESHOLD) {
alertBuzzer();
digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(BLUE_LED_PIN, HIGH);
delay(1000);
// You can add your code here for yellow LED blinking
} else {
// No threshold exceeded
// Turn off all LEDs
digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(BLUE_LED_PIN, LOW);
noTone(buzzerPin);
}
// Only update the LCD if temperature or humidity has changed
if (temperature != lastTemperature || humidity != lastHumidity) {
// Update temperature value
LCD.setCursor(6, 0); // Move cursor to the position after "Temp: "
LCD.print(" "); // Clear the existing temperature value
LCD.setCursor(6, 0); // Move cursor back to the same position
LCD.print(temperature); // Print the new temperature value
// Update humidity value
LCD.setCursor(9, 1); // Move cursor to the position after "Humidity: "
LCD.print(" "); // Clear the existing humidity value
LCD.setCursor(9, 1); // Move cursor back to the same position
LCD.print(humidity); // Print the new humidity value
// Update last values
// Create a message string with both temperature and humidity
String publishMsg = "Temperature: " + String(temperature) + ", Humidity: " + String(humidity);
// Publish the message
client.publish("testTopic", publishMsg.c_str());
lastTemperature = temperature;
lastHumidity = humidity;
}
}
void sendToBlynk()
{
float t= dht.readTemperature(); // Read temperature in Celsius
float h = dht.readHumidity(); // Read humidity
Blynk.virtualWrite(V1, h);
Blynk.virtualWrite(V0, t);
}
BLYNK_WRITE(V2)
{
int powerButtonValue = param.asInt();
if(powerButtonValue == 0)
{
powerOff();
powerState = 0;
loadingState = 0;
}
else{
powerState = 1;
LCD.backlight();
}
}
void powerOff()
{
LCD.clear();
LCD.setCursor(0, 0); // Set cursor to column 0, row 0
LCD.print("Power off: ");
// Display humidity
LCD.setCursor(0, 1); // Set cursor to column 0, row 1
LCD.print("Good by !");
LCD.clear();
Blynk.virtualWrite(V1, 0);
Blynk.virtualWrite(V0, 0);
digitalWrite(LED_PIN, LOW);
noTone(buzzerPin);
LCD.noBacklight();
}
void turgleServo(float temperature) {
//float temperature = dht.readTemperature();
int temperatureInt = int(temperature); // Convert float to int
int temperatureServoPosition = map(temperatureInt, -40, 80, 0, 180); // Map temperature to servo position
Serial.print("Servo position: ");
Serial.println(temperatureServoPosition);
Serial.print("temp: ");
Serial.println(temperatureInt);
servo.write(temperatureServoPosition);
}
void alertBuzzer() {
const int BUZZER_FREQUENCY = 1000; // Frequency in Hz
const int BUZZER_DURATION = 250; // Duration in milliseconds
// Generate a square wave of the specified frequency and duration
tone(buzzerPin, BUZZER_FREQUENCY, BUZZER_DURATION);
}
void ConnetMQTT()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
LCD.clear();
LCD.setCursor(0, 0); // Set cursor to column 0, row 0
LCD.print("Attempting MQTT connection…");
delay(1000);
// Display humidity
LCD.setCursor(0, 1); // Set cursor to column 0, row 1
LCD.print("....................");
LCD.clear();
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(clientId, msg_broker_username, msg_broker_username_password)) {
Serial.println("connected");
// Once connected, publish an announcement...
client.subscribe("testTopic");
client.publish("testTopic", "Client connected");
// ... and resubscribe
} else {
Serial.print("connection failure");
Serial.print(client.state());
Serial.println(" trying again in 3 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String stMessage;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
stMessage += (char)message[i];
}
Serial.println(stMessage);
}
void initDisplay()
{
LCD.init();
LCD.backlight();
LCD.setCursor(0, 0);
LCD.print("Welcome to ");
LCD.setCursor(0, 1);
LCD.print("Alfh2A IoT System");
delay(3000);
LCD.clear();
LCD.backlight();
LCD.setCursor(0, 0);
LCD.print("Connecting to ");
LCD.setCursor(0, 1);
LCD.print("WiFi........... ");
delay(3000);
}