Code of the card that collects the DHT11 data:
#include <Arduino.h>
#include <DHT.h>
#include "memoriaFlash.h"
#include <WiFi.h>
#include <esp_now.h>
#include <LittleFS.h>
#define FORMAT_LITTLEFS_IF_FAILED true
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
char buffer[20];
#define DHTPIN 25
#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");
if (status == ESP_NOW_SEND_SUCCESS){
FSHelper::deleteFile(LittleFS, "/midir/temperatura.txt"); // Se borra el archivo .txt
FSHelper::removeDir(LittleFS, "/midir"); // Se borra el directorio
}else if (status != ESP_NOW_SEND_SUCCESS){
FSHelper::createDir(LittleFS, "/midir");
FSHelper::writeFile(LittleFS, "/midir/temperatura.txt", buffer);
FSHelper::readFile(LittleFS, "/midir/temperatura.txt");
}
}
void setup() {
if (!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED)) {
Serial.println("LittleFS Mount Failed");
return;
}
// Init Serial Monitor
Serial.begin(9600);
// Set device as a Wi-Fi STA
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 f = dht.readTemperature();
// Read temperature as Fahrenheit
float t = dht.readTemperature(false);
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);
myDataSen.b=h;
myDataSen.c=t;
Serial.println("");
Serial.print("humedad: ");
Serial.println(h);
Serial.print("temperatura: ");
Serial.println(t);
dtostrf(t, 5, 2, buffer);
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myDataSen, sizeof(myDataSen));
delay(5000);
}
MemoryFlas.cpp library code:
#include "memoriaFlash.h"
#include <LittleFS.h>
#define FORMAT_LITTLEFS_IF_FAILED true
bool FSHelper::createDir(fs::FS &fs, const char *path) {
if (fs.exists(path)) {
Serial.println("El directorio ya existe.");
return false;
}
Serial.printf("Creating Dir: %s\n", path);
if (fs.mkdir(path)) {
Serial.println("Dir created");
return true;
} else {
Serial.println("mkdir failed");
return false;
}
}
bool FSHelper::removeDir(fs::FS &fs, const char *path){
//Serial.printf("Removing Dir: %s\n", path);
if(fs.rmdir(path)){
Serial.println("Dir removed");
return true;
} else {
//Serial.println("rmdir failed");
return false;
}
}
void FSHelper::readFile(fs::FS &fs, const char *path){
Serial.printf("Reading file: %s\r\n", path);
File file = fs.open(path);
if(!file || file.isDirectory()){
Serial.println("- failed to open file for reading");
return;
}
Serial.println("- read from file:");
while(file.available()){
Serial.write(file.read());
}
file.close();
}
void FSHelper::writeFile(fs::FS &fs, const char *path, const char *message){
Serial.printf("Writing file: %s\r\n", path);
File file = fs.open(path, FILE_WRITE);
if(!file){
//Serial.println("- failed to open file for writing");
return;
}
if(file.print(message)){
Serial.println("- file written");
} else {
//Serial.println("- write failed");
}
file.close();
}
void FSHelper::appendFile(fs::FS &fs, const char *path, const char *message){
Serial.printf("Appending to file: %s\r\n", path);
File file = fs.open(path, FILE_APPEND);
if(!file){
Serial.println("- failed to open file for appending");
return;
}
if(file.print(message)){
Serial.println("- message appended");
} else {
Serial.println("- append failed");
}
file.close();
}
bool FSHelper::deleteFile(fs::FS &fs, const char *path){
//Serial.printf("Deleting file: %s\r\n", path);
if(fs.remove(path)){
Serial.println("- file deleted");
return true;
} else {
//Serial.println("- delete failed");
return false;
}
}
MemoryFlash.h library header file code:
#ifndef memoriaFlash_H
#define memoriaFlash_H
#include <Arduino.h>
#include <LittleFS.h>
class FSHelper {
public:
// Function prototypes
static bool createDir(fs::FS &fs, const char *path);
static bool removeDir(fs::FS &fs, const char *path);
static void readFile(fs::FS &fs, const char *path);
static void writeFile(fs::FS &fs, const char *path, const char *message);
static void appendFile(fs::FS &fs, const char *path, const char *message);
static bool deleteFile(fs::FS &fs, const char *path);
private:
// No private members needed in this case
};
#endif
Platformio.ini file to include the dht11 library:
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:az-delivery-devkit-v4]
platform = espressif32
board = az-delivery-devkit-v4
framework = arduino
lib_deps =
hwspeedy/DHT-Sensor@^1.4.3
Espnow protocol receiver file code:
#include <Arduino.h>
#include <WiFi.h>
#include <esp_now.h>
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 STA
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() {
}
Leave a Reply Cancel reply