Codigo de la tarjeta ESP32 midiendo temperatura y humedad con DHT11 y enviando datos por esp-now a otra ESP32:
#include <Arduino.h>
#include <WiFi.h>
#include <esp_now.h>
#include <DHT.h>
#include <Adafruit_Sensor.h>
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
#define DHTPIN 14
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// Structure example to send data
// Must match the receiver structure
typedef struct struct_message {
String dht="dht";
int a;
float b;
float c;
} struct_message;
// Create a struct_message called myData
struct_message myDataSen;
esp_now_peer_info_t peerInfo;
// callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("\r\nLast Packet Send Status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}
void setup() {
// Init Serial Monitor
Serial.begin(9600);
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
dht.begin();
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for Send CB to
// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);
// Register peer
//Este apartado del peer es util para enviar el paquete
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Failed to add peer");
return;
}
}
void loop() {
float h = dht.readHumidity();
// Read temperature as Celsius
float t = dht.readTemperature();
// Read temperature as Fahrenheit
float f = dht.readTemperature(true);
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Fahrenheit
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius
float hic = dht.computeHeatIndex(t, h, false);
myDataSen.b=h;
myDataSen.c=hic;
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myDataSen, sizeof(myDataSen));
delay(2000);
}
Este código pertenece al detector de humedad de suelo, colocado en una planta, y enviando los datos a otra ESP32 por esp-now:
#include <Arduino.h>
#include <WiFi.h>
#include <esp_now.h>
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
int sensorValue;
const int SensorPin=14;
// Structure example to send data
// Must match the receiver structure
typedef struct struct_message {
String moisture="moisture";
int a;
float b;
float c;
} struct_message;
// Create a struct_message called myData
struct_message myDataSen;
esp_now_peer_info_t peerInfo;
// callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("\r\nLast Packet Send Status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}
void setup() {
// Init Serial Monitor
Serial.begin(9600);
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
pinMode(SensorPin, INPUT_PULLDOWN);
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for Send CB to
// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);
// Register peer
//Este apartado del peer es util para enviar el paquete
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Failed to add peer");
return;
}
}
void loop() {
sensorValue = analogRead(SensorPin);
int humedad = (100 - ((sensorValue/4095.00) * 100));
myDataSen.a=humedad;
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myDataSen, sizeof(myDataSen));
Serial.println(myDataSen.moisture);
Serial.println(myDataSen.a);
delay(2000);
}
Este codigo de abajo pertenece al tarjeta ESP32 que recoge los datos de las otras tarjetas ESP32 por esp-now y los envia por USB a una tarjeta CPU PINE A64:
#include <Arduino.h>
#include <WiFi.h>
#include <esp_now.h>
uint8_t broadcastAddress1[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
uint8_t broadcastAddress2[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
typedef struct struct_message {
String sensor;
int a;
float b;
float c;
} struct_message;
// Create a struct_message called myData
struct_message myDataRec;
esp_now_peer_info_t peerInfo;
String array[4];
// callback function that will be executed when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&myDataRec, incomingData, sizeof(myDataRec));
array[0]=myDataRec.sensor;
array[1]=myDataRec.a;
array[2]=myDataRec.b;
array[3]=myDataRec.c;
Serial.print(array[0]);
Serial.print(",");
Serial.print(array[1]);
Serial.print(",");
Serial.print(array[2]);
Serial.print(",");
Serial.println(array[3]);
}
void setup() {
// Initialize Serial Monitor
Serial.begin(9600);
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for recv CB to
// get recv packer info
esp_now_register_recv_cb(OnDataRecv);
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Failed to add peer");
return;
}
}
void loop() {
}
El código de abajo pertenece a la CPU de la tarjeta PINE A64, que recoge los datos de la ESP32 por puerto USB y los muestra en una pantalla, el sistema operativo es linux-armbian, y el código que administra los datos es python:
import tkinter as tk
import serial
from PIL import Image, ImageTk
window=tk.Tk()
def end_fullscreen(event=None):
window.attributes('-fullscreen', False)
window.geometry('500x500')
window.title("Ventana de control")
window.attributes('-fullscreen', True)
window.bind('<F10>', end_fullscreen)
image1 = Image.open("/home/control/Downloads/planta.jpeg")
image1=image1.resize((200, 200))
photo1 = ImageTk.PhotoImage(image1)
image2 = Image.open("/home/control/Downloads/sol.gif")
image2=image2.resize((200, 200))
photo2 = ImageTk.PhotoImage(image2)
frame1 = tk.Frame(window, bg='white')
frame1.pack(side='left', fill='both', expand=True)
label1=tk.Label(frame1, image=photo1)
label1.pack(padx=10, pady=10)
frame2 = tk.Frame(window, bg='white')
frame2.pack(side='right', fill='both', expand=True)
label2=tk.Label(frame2, image=photo2)
label2.pack(padx=10, pady=10)
esp32_1_label=tk.Label(frame1, text="")
esp32_1_label.pack()
esp32_2_label=tk.Label(frame2, text="")
esp32_2_label.pack()
#Centrar la ventana
window_width=window.winfo_reqwidth()
window_height=window.winfo_reqheight()
position_top=int(window.winfo_screenmmheight() / 2 - window_height / 2)
position_right=int(window.winfo_screenmmwidth() / 2 - window_width / 2)
window.geometry("+{}+{}".format(position_right, position_top))
ser=serial.Serial('/dev/ttyUSB0', 9600)
def update_label():
if ser.in_waiting > 0:
line=ser.readline().decode('utf-8').rstrip()
values=line.split(',')
if values[0] == 'moisture':
esp32_1_label.config(text="La humedad de la planta es:" + "\n" + values[1] + " %")
if values[0] == 'dht':
esp32_2_label.config(text="La temperatura que hace es:" + "\n" + values[3] + " °C" + "\nLa humedad que hace es de:" + "\n" + values[2] + " %")
window.after(100, update_label)
update_label()
window.mainloop()
La siguiente imagen pertenece a la pantalla que monitorea las señales de los sensores: