// Inclye las bibliotecas necesarias
#include "WiFi.h"
#include "ThingSpeak.h" // Biblioteca para ThingSpeak
#define FC28 32
#define Rele 17
int humedad = 0;
int offset = 4;
int bomba = 0;
int x = 0;
//Credenciales Wifi
const char* WIFI_NAME = "Wokwi-GUEST"; //Nombre de la red
const char* WIFI_PASSWORD = "";//Contraseña de Wifi
WiFiClient client;
//Credenciales del canal de ThingSpeak
const int myChannelNumber = 2475768;
const char* myApiKey = "6ELPANBTIV6GJPEH";
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(FC28, INPUT); //Pin del FC-28
pinMode(Rele, OUTPUT); // Pin Rele
WiFi.begin(WIFI_NAME,WIFI_PASSWORD); //Conectar a internet
while(WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Wifi no connected");
}
Serial.println("Wifi connected!");
ThingSpeak.begin(client); // Inicia la coneccion con nuestro canal de ThinkSpeak
}
void loop() {
// menor al 50% se enciende y mayor al 85% se apaga
int Lectura = analogRead(FC28);
delay(5);
humedad = map(Lectura,0, 4095, 0,100);
Serial.print("Humedad: ");
Serial.println(humedad);
Serial.print(" Bomba: ");
Serial.println(bomba);
// 0 ----ON---- 62 ---ON---- 85 ---OFF--- 100
if(humedad <= 62 + offset/2 || humedad <= 62 - offset/2)
{
digitalWrite(Rele, HIGH);
bomba = 1;
delay(5);
}
else if(humedad > 85 + offset/2 || humedad > 85 - offset/2)
{
digitalWrite(Rele, LOW);
bomba = 0;
delay(5);
}
//Envio de datos a ThingSpeak
ThingSpeak.setField(1,humedad);
ThingSpeak.setField(2,bomba);
int x = ThingSpeak.writeFields(myChannelNumber,myApiKey);
//Manejo de error en comunicacion con ThingSpeak
if(x == 200)
{
Serial.println("Mensaje enviado correctamente");
}
else
{
Serial.println("Error "+ String(x));
}
delay(1500); // this speeds up the simulation
}