Codigo de los 3 modulos:
Modulo ESP32 sensor de movimiento, rele y lampara:
#include <Arduino.h>
#include "WiFi.h"
#include <esp_now.h>
//parametros de trabajo de los nucleos
TaskHandle_t Nucleo1;
TaskHandle_t Nucleo2;
//parametros del hc sr501
const int pir = 14;
const int led = 2;
const int rele = 12;
int det = 0; //si detecta envia un uno
int releEstado =0;//si detecta envia 1
//parametros del envio
uint8_t broadcastAddress[] = {0xc0, 0x49, 0xef, 0xca, 0x38, 0xd0};
//estructura y variable del mensaje
typedef struct struct_message {
int id;
int a;
int b;
} struct_message;
struct_message myData;
esp_now_peer_info_t peerInfo;
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status){
//Serial.print("\r\nEstado del ultimo paquete enviado:\t");
//Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Enviado con exito" : "Fallo en el envio");
}
void Tarea_Nucleo1( void * pvParameters ){
for(;;){
// Serial.println("Esto se ejecuta en el nucleo1");
delay(1000);
if (digitalRead(pir) == LOW){
det = 0;
digitalWrite(led, LOW);
}
if (digitalRead(pir) == HIGH){
det = 1;
digitalWrite(led, HIGH);
}
myData.b = det;
myData.id = 1;
esp_now_register_send_cb(OnDataSent);
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
if(result == ESP_OK){
// Serial.println("enviado con exito");
}
else{
Serial.println("fallo en el envio");
}
}
}
void Tarea_Nucleo2( void * pvParameters ){
for(;;){
// Serial.println("Esto se ejecuta en el nucleo2");
// Serial.println();
delay(1000);
if (digitalRead(pir) == LOW){
digitalWrite(rele, LOW);
releEstado=0;
} else if(digitalRead(pir) == HIGH){
digitalWrite(rele, HIGH);
releEstado=1;
}
myData.a = releEstado;
myData.id = 1;
esp_now_register_send_cb(OnDataSent);
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
if(result == ESP_OK){
// Serial.println("enviado con exito");
}
else{
Serial.println("fallo en el envio");
}
if (releEstado==1){
//Serial.println("relede estado en 1");
delay(600000);
} else {
//Serial.println("rele de estado en 0");
delay(1000);
}
}
}
void setup(){
Serial.begin(9200);
//parametros del rele
pinMode(rele, OUTPUT);
//parametros del hc sr501
pinMode(pir, INPUT);
pinMode(led, OUTPUT);
WiFi.mode(WIFI_STA);
xTaskCreatePinnedToCore(Tarea_Nucleo1,"Tarea1",10000,NULL,1,&Nucleo1,1);
xTaskCreatePinnedToCore(Tarea_Nucleo2,"Tarea2",10000,NULL,1,&Nucleo2,0);
if(esp_now_init() != ESP_OK){
Serial.println("Error inicializando ESP-NOW");
return;
}
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
if(esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Fallo al añadir peer");
return;
}
}
void loop(){
}
Modulo ESP32 sensor de temperatura y led:
#include <Adafruit_Sensor.h>
#include <Arduino.h>
#include "DHT.h"
#include <WiFi.h>
#include <esp_now.h>
#define DHTPIN 14
#define vent 12
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
float temperatura = 5.00;
int temperatura2=0;
int led = 0;
//parametros del envio
uint8_t broadcastAddress[] = {0xc0, 0x49, 0xef, 0xca, 0x38, 0xd0};
//estructura y variable del mensaje
typedef struct struct_message {
int id;
int a;
int b;
} struct_message;
struct_message myData;
esp_now_peer_info_t peerInfo;
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status){
Serial.print("\r\nEstado del ultimo paquete enviado:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Enviado con exito" : "Fallo en el envio");
}
void setup() {
Serial.begin(9600);
pinMode(vent, OUTPUT);
Serial.println(F("DHTxx test!"));
dht.begin();
WiFi.mode(WIFI_STA);
if(esp_now_init() != ESP_OK){
Serial.println("Error inicializando ESP-NOW");
return;
}
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
if(esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Fallo al añadir peer");
return;
}
}
void loop() {
delay(3000);
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
float hif = dht.computeHeatIndex(f, h);
float hic = dht.computeHeatIndex(t, h, false);
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("°C "));
Serial.print(f);
Serial.print(F("°F Heat index: "));
Serial.print(hic);
Serial.print(F("°C "));
Serial.print(hif);
Serial.println(F("°F"));
if (t>=23.00){
digitalWrite(vent, HIGH);
led=1;
} else {
digitalWrite(vent, LOW);
led=0;
}
temperatura=t;
temperatura2=(int)temperatura;
myData.b = temperatura2;
myData.a = led;
myData.id = 2;
esp_now_register_send_cb(OnDataSent);
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
if(result == ESP_OK){
Serial.println("enviado con exito");
}
else{
Serial.println("fallo en el envio");
}
}
Modulo ESP32 receptor y Web Server para visualizar el resultado:
#include <WiFi.h>
#include <Arduino.h>
#include <esp_now.h>
//ESTA PARTE PERTENECE AL MODO AP
// Replace with your network credentials
const char* ssid = "ESP32AP";
const char* password = "123456789";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
String outputDetector = "detector de movimiento";
String outputLampara = "rele de lampara";
String outputLed = "estado del led";
String outputTemperatura = "Temperatura:";
//ESTA PARTE PERTENECE AL ESP-NOW
int releEstado = 0; //si esta a uno la lampara esta encendida, otro esp32 led
int det = 0; //si detecta envia un uno, otro esp32 detector de temperatura
int id = 0;//identificador de esp32, 1 det movimiento, 2 detector temperatura
int temperatura = 0; //temperatura del sensor
typedef struct struct_message{
int id;
int a;
int b;
} struct_message;
struct_message myData;
void OnDataRecv(const uint8_t *mac, const uint8_t *incomingData, int len){
memcpy(&myData, incomingData, sizeof(myData));
}
void setup() {
//ESTA PARTE PERTENECE AL AP
Serial.begin(9200);
// Connect to Wi-Fi network with SSID and password
Serial.print("Configuracion AP (Punto de Aceso)…");
IPAddress local_ip(192,168,1,1);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
// Remove the password parameter, if you want the AP (Access Point) to be open
WiFi.mode(WIFI_AP_STA);
//ESTA PARTE PERTENECE AL ESP-NOW
if(esp_now_init() != ESP_OK){
Serial.println("Error iniciando ESP_NOW");
return;
}
WiFi.softAPConfig(local_ip, gateway, subnet);
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP direccion: ");
Serial.println(IP);
server.begin();
}
void loop(){
//ESTA PARTE PERTENECE AL ESP-NOW
if(esp_now_register_recv_cb(OnDataRecv) != ESP_OK){
esp_now_deinit();
det=0;
releEstado=0;
id=0;
} else {
esp_now_register_recv_cb(OnDataRecv);
det = myData.b;
releEstado = myData.a;
id = myData.id;
}
if (id==1){
det=myData.b;
}else if(id==2){
temperatura=myData.b;
}
//ESTA PERTENECE AL AP
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns the GPIOs on and off
if (id == 1){
if (det == 1) {
Serial.println("outputDetector on");
outputDetector = "on";
} else if (det == 0){
Serial.println("outputDetector off");
outputDetector = "off";
}
if (releEstado == 1) {
Serial.println("outputLampara on");
outputLampara = "on";
} else if (releEstado == 0){
Serial.println("outputLampara off");
outputLampara = "off";
}
} else if(id == 2){
if (releEstado == 1) {
Serial.println("outputLed on");
outputLed = "on";
} else if (releEstado == 0){
Serial.println("outputLed off");
outputLed = "off";
}
} else {
Serial.println("no recibo nada");
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta http-equiv=refresh content=5 name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");
// If the output26State is off, it displays the ON button
if (outputDetector=="on") {
client.println("<p>estoy recibiendo senal de deteccion</p>");
} else {
client.println("<p>no recibo senal de deteccion</p>");
}
//informacion recibida del rele de la lampara
if (outputLampara=="on") {
client.println("<p>la lampara esta encendida</p>");
} else {
client.println("<p>no esta la lampara encendida</p>");
}
//informacion recibida del rele de la lampara
if (outputLed=="on") {
client.println("<p>El led esta encendido</p>");
} else {
client.println("<p>no esta el led encendido</p>");
}
client.print("<p>La temperatura es: </p>");
client.println(temperatura);
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Deja una respuesta Cancelar la respuesta