#include <WiFi.h>
#include <DHT.h>
#include "ThingSpeak.h"
const char* ssid = "Wokwi-GUEST"; // Nombre de red WiFi
const char* password = ""; // Contraseña WiFi
const char* myWriteAPIKey = "GZR3W5OPJ7S0U8AU"; // API Key de escritura de ThingSpeak
DHT dht(15, DHT22); // Inicializar el sensor DHT en el pin 15
WiFiClient client; // Crear un objeto cliente WiFi
unsigned long myChannelNumber = 2540012; // Número de canal de ThingSpeak
String myStatus = "";
bool lastMotionState = false;
//Pines LED y PIR
const int led = 26;
const int motionSensor = 27;
unsigned long now = 0;
unsigned long lastTrigger = 0;
boolean motion = false;
void setup() {
Serial.begin(115200);
dht.begin();
conexion();
pinMode(led, OUTPUT); // Configurar el pin del LED como salida
pinMode(motionSensor, INPUT); // Configurar el pin del sensor PIR como entrada
}
void conexion(){
WiFi.begin(ssid, password); // Conectar a la red WiFi
Serial.print("Conectando a ");
Serial.println(ssid);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConectado.");
ThingSpeak.begin(client); // Inicializar ThingSpeak
}
void loop() {
Wifi();
initdht22();
PIR();
}
void Wifi(){
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Error: No se pudo conectar a WiFi. Intentando reconectar...");
WiFi.reconnect();
delay(1000);
return;
}
}
void initdht22(){
float temp = dht.readTemperature(); // Leer temperatura
float humidity = dht.readHumidity(); // Leer humedad
Serial.print("Temperatura: ");
Serial.print(temp);
Serial.println(" °C");
Serial.print("Humedad: ");
Serial.print(humidity);
Serial.println(" %");
int attempts = 3; // Número máximo de intentos
while (attempts > 0) {
ThingSpeak.setField(1, temp);
ThingSpeak.setField(2, humidity);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (x == 200) {
Serial.println("Datos enviados correctamente.");
break; // Salir del bucle si la operación fue exitosa
} else {
Serial.println("Problema al enviar datos. Código de error HTTP " + String(x));
attempts--; // Decrementar el contador de intentos
delay(1000); // Esperar 1 segundo antes de intentar nuevamente
}
}
if (attempts == 0) {
Serial.println("Error: No se pudo enviar el dato después de varios intentos.");
}
delay(20000); // Esperar 20 segundos antes de enviar nuevos datos
}
void PIR() {
now = millis();
bool motionDetected = (digitalRead(motionSensor) == HIGH);
if ((motionDetected) && (!motion)) {
Serial.println("Movimiento Detectado!!!");
motion = true;
lastTrigger = now; // Reiniciar el temporizador cuando se detecta movimiento
digitalWrite(led, HIGH); // Encender el LED cuando se detecta movimiento
// Intentar enviar el estado del sensor de movimiento a ThingSpeak cuando el LED se enciende
int attempts = 3; // Número máximo de intentos
while (attempts > 0) {
ThingSpeak.setField(3, motionDetected);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (x == 200) {
Serial.println("Datos enviados correctamente.");
break; // Salir del bucle si la operación fue exitosa
} else {
Serial.println("Problema al enviar datos. Código de error HTTP " + String(x));
attempts--; // Decrementar el contador de intentos
delay(1000); // Esperar 1 segundo antes de intentar nuevamente
}
}
if (attempts == 0) {
Serial.println("Error: No se pudo enviar el dato después de varios intentos.");
}
}
// Apagar el LED después de 10 segundos si no se detecta movimiento
if ((motion) && (now - lastTrigger > 10000) && (!motionDetected)) {
Serial.println("Fuera de Movimiento");
digitalWrite(led, LOW); // Apagar el LED después de 10 segundos sin movimiento
motion = false;
// Intentar enviar el estado del sensor de movimiento a ThingSpeak cuando el LED se apaga
int attempts = 3; // Número máximo de intentos
while (attempts > 0) {
ThingSpeak.setField(3, motionDetected);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (x == 200) {
Serial.println("Datos enviados correctamente.");
break; // Salir del bucle si la operación fue exitosa
} else {
Serial.println("Problema al enviar datos. Código de error HTTP " + String(x));
attempts--; // Decrementar el contador de intentos
delay(1000); // Esperar 1 segundo antes de intentar nuevamente
}
}
if (attempts == 0) {
Serial.println("Error: No se pudo enviar el dato después de varios intentos.");
}
}
// Enviar el estado del sensor de movimiento a ThingSpeak solo si hay un cambio de estado
if (motionDetected != lastMotionState) {
ThingSpeak.setField(3, motionDetected);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (x == 200) {
Serial.println("Datos enviados correctamente.");
} else {
Serial.println("Problema al enviar datos. Código de error HTTP " + String(x));
}
lastMotionState = motionDetected;
}
}