#include <WiFi.h>
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
#include <HTTPClient.h>
// ==================== CONFIGURAÇÕES WiFi ====================
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ==================== CONFIGURAÇÕES HTTP ====================
// Troque essa URL pela URL da sua API (ngrok, servidor, etc.)
const char* api_url = "http://b18922adb64b.ngrok-free.app/sensores";
// ==================== CONFIGURAÇÕES DE PINOS ====================
#define DHT_PIN 4 // DHT22 no GPIO 4
#define DHT_TYPE DHT22
#define LDR_PIN 34 // LDR no GPIO 34 (ADC1)
#define LED_R 25 // LED Vermelho
#define LED_G 26 // LED Verde
#define LED_B 27 // LED Azul
#define BUZZER_PIN 13 // Buzzer
// ==================== INICIALIZAÇÃO DE COMPONENTES ====================
DHT dht(DHT_PIN, DHT_TYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2); // Endereço I2C padrão 0x27
// ==================== VARIÁVEIS GLOBAIS ====================
unsigned long ultimaLeitura = 0;
unsigned long tempoTrabalhando = 0;
const unsigned long INTERVALO_LEITURA = 10000; // 10 segundos
const unsigned long TEMPO_PAUSA = 1800000; // 30 minutos (em ms)
// Condições ideais para produtividade
const float TEMP_MIN = 20.0;
const float TEMP_MAX = 25.0;
const float UMIDADE_MIN = 40.0;
const float UMIDADE_MAX = 60.0;
const int LUZ_MIN = 300; // Valor ADC mínimo
const int LUZ_MAX = 3000; // Valor ADC máximo
// ==================== PROTÓTIPOS ====================
void conectarWiFi();
bool verificarCondicoes(float temp, float umid, int luz);
void enviarDadosHTTP(float temp, float umid, int luz, bool condicoesIdeais);
void setLED(int r, int g, int b);
void tocarSom(int frequencia, int duracao);
void alertarPausa();
// ==================== SETUP ====================
void setup() {
Serial.begin(115200);
// Inicializa pinos
pinMode(LED_R, OUTPUT);
pinMode(LED_G, OUTPUT);
pinMode(LED_B, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LDR_PIN, INPUT);
// Inicializa sensores
dht.begin();
// Inicializa LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("EQUILIBRA AI");
lcd.setCursor(0, 1);
lcd.print("Iniciando...");
delay(2000);
// Conecta WiFi
conectarWiFi();
lcd.clear();
lcd.setCursor(0, 0);
lcd.setCursor(0, 1);
lcd.print("Status: OK");
}
void loop() {
unsigned long tempoAtual = millis();
// Leitura periódica dos sensores
if (tempoAtual - ultimaLeitura >= INTERVALO_LEITURA) {
ultimaLeitura = tempoAtual;
// Lê sensores
float temperatura = dht.readTemperature();
float umidade = dht.readHumidity();
int luminosidade = analogRead(LDR_PIN);
// Valida leituras
if (isnan(temperatura) || isnan(umidade)) {
Serial.println("Erro ao ler DHT22!");
setLED(255, 0, 0); // LED vermelho (erro)
return;
}
// Exibe leituras no Serial Monitor
Serial.println("\n--- Leitura dos Sensores ---");
Serial.printf("Temperatura: %.1f°C\n", temperatura);
Serial.printf("Umidade: %.1f%%\n", umidade);
Serial.printf("Luminosidade: %d\n", luminosidade);
// Verifica se condições estão ideais
bool condicoesIdeais = verificarCondicoes(temperatura, umidade, luminosidade);
if (condicoesIdeais) {
tempoTrabalhando += INTERVALO_LEITURA;
setLED(0, 255, 0); // LED verde (tudo ok)
tocarSom(1000, 100); // Bip de confirmação
Serial.println("✓ Condições ideais!");
// Atualiza LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Status: IDEAL ");
lcd.setCursor(0, 1);
lcd.print("Temp:");
lcd.print(temperatura, 1);
lcd.print("C");
} else {
setLED(255, 255, 0); // LED amarelo (condições não ideais)
Serial.println("⚠ Condições não ideais.");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Status: ALERTA ");
lcd.setCursor(0, 1);
lcd.print("Temp:");
lcd.print(temperatura, 1);
lcd.print("C");
}
// Envia dados para a API via HTTP
enviarDadosHTTP(temperatura, umidade, luminosidade, condicoesIdeais);
}
// Alerta de pausa inteligente (a cada 30 minutos em condições ideais)
if (tempoTrabalhando >= TEMPO_PAUSA) {
alertarPausa();
tempoTrabalhando = 0;
}
}
// ==================== FUNÇÕES AUXILIARES ====================
void conectarWiFi() {
Serial.print("Conectando ao WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n✓ WiFi conectado!");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
}
bool verificarCondicoes(float temp, float umid, int luz) {
bool tempOk = (temp >= TEMP_MIN && temp <= TEMP_MAX);
bool umidOk = (umid >= UMIDADE_MIN && umid <= UMIDADE_MAX);
bool luzOk = (luz >= LUZ_MIN && luz <= LUZ_MAX);
Serial.printf("Temp OK: %s | Umid OK: %s | Luz OK: %s\n",
tempOk ? "✓" : "✗",
umidOk ? "✓" : "✗",
luzOk ? "✓" : "✗");
return (tempOk && umidOk && luzOk);
}
void enviarDadosHTTP(float temp, float umid, int luz, bool condicoesIdeais) {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("✗ WiFi desconectado, não foi possível enviar HTTP");
return;
}
HTTPClient http;
Serial.print("Enviando dados para API: ");
Serial.println(api_url);
http.begin(api_url);
http.addHeader("Content-Type", "application/json");
String payload = "{";
payload += "\"temperatura\":" + String(temp, 1) + ",";
payload += "\"umidade\":" + String(umid, 1) + ",";
payload += "\"luminosidade\":" + String(luz) + ",";
payload += "\"condicoesIdeais\":" + String(condicoesIdeais ? "true" : "false");
payload += "}";
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
Serial.print("✓ HTTP Response code: ");
Serial.println(httpResponseCode);
String response = http.getString();
Serial.print("Resposta da API: ");
Serial.println(response);
} else {
Serial.print("✗ Erro ao enviar HTTP: ");
Serial.println(httpResponseCode);
}
http.end();
}
void setLED(int r, int g, int b) {
analogWrite(LED_R, r);
analogWrite(LED_G, g);
analogWrite(LED_B, b);
}
void tocarSom(int frequencia, int duracao) {
tone(BUZZER_PIN, frequencia, duracao);
}
void alertarPausa() {
Serial.println("\n🔔 ALERTA: Hora de fazer uma pausa!");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("HORA DA PAUSA!");
lcd.setCursor(0, 1);
lcd.print("Descanse :)");
// Animação de LED e som
for (int i = 0; i < 3; i++) {
setLED(255, 0, 255); // Roxo
tocarSom(2000, 200);
delay(300);
setLED(0, 0, 0);
delay(300);
}
delay(3000);
}