Los dos modulos esp32 que utilizo son «doit esp32 devkit v1» y «doit esp32 devkit v4», el sensor de movimiento es «HC-SR501», el rele es el «SRD05», la fuente de alimentación «MB102» y el entorno de programación es Visual Studio Code PlatformIO.
Codigo del modulo esp32 para la recepción del sensor de movimiento, funcionamiento del rele y envio de datos a través del wifi protocolo esp-now:
#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 de la direccion mac para el envio
uint8_t broadcastAddress[] = {0xc0, 0x40, 0xec, 0xcf, 0x30, 0xd2};
//estructura y variable del mensaje
typedef struct struct_message {
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;
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;
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(300000);
} 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(){
}
A continuación se muestra el código para el modulo esp32 que recibe los datos via wifi protocolo esp-now, y abre un punto de acceso via wifi para poder ver el resultado en cualquier dispositivo en la dirección 192.168.1.1
#include <WiFi.h>
#include <Arduino.h>
#include <esp_now.h>
//ESTA PARTE PERTENECE AL MODO AP
// Replace with your network credentials
const char* ssid = "NombreWifiESP32";
const char* password = "ContrasenaWifiESP32";
// 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";
//ESTA PARTE PERTENECE AL ESP-NOW
int releEstado = 0;//si esta a uno la lampara esta encendida
int det = 0; //si detecta envia un uno
typedef struct struct_message{
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;
}else {
esp_now_register_recv_cb(OnDataRecv);
det = myData.b;
releEstado = myData.a;
}
//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 (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";
}
// 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>");
}
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("");
}
}
Esquema eléctrico del sensor, el relé, fuente de alimentación y modulo esp32:
A continuación me gustaría describir algunas características de los elementos que estamos utilizando en el proyecto.

El primer componente es una fuente de alimentación (MB102), la tensión de entrada es de 6.5 a 12 voltios en continua, nos puede proporcionar 5 voltios o 3.3 voltios, dependiendo de donde coloquemos el jumper. La corriente máxima a la que puede trabajar es 700 mA, que nos daría una potencia de 2.31 Watios en 3.3 voltios o 3.5 Watios en 5 voltios.
Sensor de movimiento (HC-SR501), este sensor de movimiento trabaja con una tensión de 5 voltios en corriente continua, cuando detecta movimiento envía señal con 3.3 voltios y consume una corriente de aproximadamente 2 miliamperios.
El rele (SDR05), este rele trabaja con una tensión de 5 voltios y se activa con una señal de 3.3 voltios. El rele tiene dos contactos, un contacto abierto y un contacto cerrado que al recibir tensión en rele a través del contacto de señal el contacto abierto se cierra y el contacto cerrado se abre. Los contactos abiertos y cerrados pueden trabajar a 240 voltios en corriente alternar y soportan una intensidad de 10 amperios.
El modulo ESP32 (doit ESP32 devkit v1), este modulo trabaja con una tensión de 5 voltios, aunque soporta hasta 12 voltios. El voltaje de salida por los pines GPIO es a 3.3 voltios en continua y pueden suministrar hasta 1200 mA (cada pin aproximadamente 40 mA) máximo. La placa tiene un consumo de aprox. 300 mA, y el wifi puede llegar a consumir 180 mA.
Es recomendable conectar un condensador de 10 microFaradios entre el pin EN y GND para evitar pulsar el boton BOOT cada vez que queremos cargar un programa en la placa.
Deja una respuesta Cancelar la respuesta