Mancata ricezione dati

Ciao
Ritorno al forum con un problema di ricezione dati con ESP32
Ho 2 sketch A trasmette a B e B deve trasmettere ad A i dati di un sensore che in questo momento e' rappresentato dalla funzione random()
la trasmissione da A verso B funziona
sotto a sx B, a dx A

La trasmissione da B verso A non funziona anche se su B il messaggio sembra positivo, ma non viene eseguita questa funzione sullo sketch B

// 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");
}

sotto A

/**************************************************************************
  This is an example for our Monochrome OLEDs based on SSD1306 drivers

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/category/63_98

  This example is for a 128x64 pixel display using I2C to communicate
  3 pins are required to interface (two I2C and one reset).

  Adafruit invests time and resources providing this open
  source code, please support Adafruit and open-source
  hardware by purchasing products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries,
  with contributions from the open source community.
  BSD license, check license.txt for more information
  All text above, and the splash screen below must be
  included in any redistribution.
 **************************************************************************/

//mst

#include <SPI.h>               //SD
#include <Wire.h>              //RTC3231 OLED
#include <Adafruit_GFX.h>      //OLED
#include <Adafruit_SSD1306.h>  //OLED
#include "FS.h"                //SD
#include "SD.h"                //SD

//sezione ESP32
#include <esp_now.h>  //ESP32
#include <WiFi.h>     //ESP32

// REPLACE WITH YOUR ESP RECEIVER'S MAC ADDRESS

//uint8_t broadcastAddress1[] = { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0xC0 };
//uint8_t broadcastAddress2[] = { 0x24, 0x0A, 0xC4, 0xAE, 0xAE, 0x44 };
//uint8_t broadcastAddress3[] = { 0x80, 0x7D, 0x3A, 0x58, 0xB4, 0xB0 };
//uint8_t broadcastAddress4[] = { 0x3C, 0x71, 0xBF, 0xC3, 0xBF, 0xB0 };
//uint8_t broadcastAddress5[] = { 0x04, 0x0A, 0xC4, 0xAE, 0xAE, 0x44 };

// REPLACE WITH YOUR ESP RECEIVER'S MAC ADDRESS

uint8_t mac_Add[5][6] = {
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0x41 },
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0x42 },
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0x43 },
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0x44 },
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0xC0 }  //scheda collegata
};

uint8_t broadcastAddress[] = { 0, 0, 0, 0, 0, 0 };

//uint8_t broadcastAddress1[] = { mac_Add[0][0], mac_Add[0][1], mac_Add[0][2], mac_Add[0][3], mac_Add[0][4], mac_Add[0][5] };
//uint8_t broadcastAddress2[] = { mac_Add[1][0], mac_Add[1][1], mac_Add[1][2], mac_Add[1][3], mac_Add[1][4], mac_Add[1][5] };
//uint8_t broadcastAddress3[] = { mac_Add[2][0], mac_Add[2][1], mac_Add[2][2], mac_Add[2][3], mac_Add[2][4], mac_Add[3][5] };
//uint8_t broadcastAddress4[] = { mac_Add[3][0], mac_Add[3][1], mac_Add[3][2], mac_Add[3][3], mac_Add[3][4], mac_Add[3][5] };
//uint8_t broadcastAddress5[] = { mac_Add[4][0], mac_Add[4][1], mac_Add[4][2], mac_Add[4][3], mac_Add[4][4], mac_Add[4][5] };

// Structure example to send data Must match the peripherical structure
typedef struct test_struct {
  byte id;
} test_struct;

test_struct test_1;

// Structure message from the peripherical structure
typedef struct struct_msg_2 {
  byte id_sens;
  float t;
  float rh;
} struct_msg_2;

struct_msg_2 myData;  // Create a struct_message called myData

esp_now_peer_info_t peerInfo;

//OLED

#define SCREEN_WIDTH 128  // OLED display width, in pixels
#define SCREEN_HEIGHT 64  // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET -1        // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3c  ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

//RTC DS3231

#include "RTClib.h"
RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

//SD

byte chipSDSelect;
File datafile;

//variabili

unsigned long previousMillis;  // will store last time
long sampling_delay;           //intervallo di campionamento
byte SD_delay;
byte rx_delay;
byte id_sens;  //id sensore
byte num_sensori;

void setup() {

  Serial.begin(115200);  // Start the serial interface

  Wire.begin();  // Start the I2C interface

  //sezione delay con millis() timer

  sampling_delay = 4000;  //millis intervallo delle interrogazioni delle stazioni
  SD_delay = 2;           //ritardo scrittura valori su SD
  rx_delay = 7;           //ritardo ciclo ricezione dati
  previousMillis = 0;
  num_sensori = 5;

  //ESP32

  WiFi.mode(WIFI_STA);

  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
  }

  // 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
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

  // register peers
  for (id_sens = 0; id_sens < num_sensori; id_sens++) {

    //broadcastAddress[] = { mac_Add[id_sens][0], mac_Add[id_sens][1], mac_Add[id_sens][2], mac_Add[id_sens][3], mac_Add[id_sens][4], mac_Add[id_sens][5] };

    //memcpy(peerInfo.peer_addr, broadcastAddress, 6);
    memcpy(peerInfo.peer_addr, mac_Add[id_sens], (sizeof(mac_Add[id_sens]) / sizeof(mac_Add[id_sens][0])));  //dal forum

    if (esp_now_add_peer(&peerInfo) != ESP_OK) {
      Serial.println("Failed to add peer");
      return;
    }
  }

  id_sens = 0;  //azzero id_sens dopo il for

  //OLED

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C, false, false)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ;  // Don't proceed, loop forever
  }

  // Show initial display buffer contents on the screen --
  // the library initializes this with an Adafruit splash screen.

  display.display();

  // display.display() is NOT necessary after every single drawing command,
  // unless that's what you want...rather, you can batch up a bunch of
  // drawing operations and then update the screen all at once by calling
  // display.display(). These examples demonstrate both approaches...

  delay(2000);  // Pause for 2 seconds

  display.clearDisplay();  // Clear the buffer

  display.display();

  delay(2000);

  //RTC

  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    while (1) delay(10);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }

  //SD

  chipSDSelect = 5;
  pinMode(chipSDSelect, OUTPUT);
  SD.begin(chipSDSelect);
  Serial.println("Initializing SD card...1");

  delay(500);

  if (!SD.begin(chipSDSelect))  // see if the card is present and can be initialized:
  {
    Serial.println("Card failed, or not present");  // don't do anything more
    digitalWrite(5, HIGH);
    while (1)
      ;
  } else {
    Serial.println("SD card initialized...2");
  }
}

void loop() {

  if (millis() - previousMillis >= sampling_delay) {
    previousMillis = millis();  //save the last time

    //ESP32
    // Set values to send

    //broadcastAddress[] = { mac_Add[id_sens][0], mac_Add[id_sens][1], mac_Add[id_sens][2], mac_Add[id_sens][3], mac_Add[id_sens][4], mac_Add[id_sens][5] };

    memcpy(broadcastAddress, mac_Add[id_sens], (sizeof(mac_Add[id_sens]) / sizeof(mac_Add[id_sens][0])));  //dal forum arduino

    test_1.id = id_sens;

    Serial.print("actual id_sens/peripherical is ");
    Serial.println(id_sens);
    Serial.print("test_1.id ");
    Serial.println(test_1.id);

    esp_err_t result_1 = esp_now_send(broadcastAddress, (uint8_t *)&test_1, sizeof(test_1));

    if (result_1 == ESP_OK) {
      Serial.println("Sent with success");
    } else {
      Serial.println("Error sending the data");
    }

    delay(200);

    //RTC

    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");

    if (now.hour() < 10) {
      Serial.print('0');
    }
    Serial.print(now.hour(), DEC);
    Serial.print(':');

    if (now.minute() < 10) {
      Serial.print('0');
    }
    Serial.print(now.minute(), DEC);
    Serial.print(':');

    if (now.second() < 10) {
      Serial.print('0');
    }
    Serial.print(now.second(), DEC);
    Serial.println();

    //OLED
    // Not all the characters will fit on the display. This is normal.
    // Library will draw what it can and the rest will be clipped.
    display.clearDisplay();

    display.setTextSize(2);               // Normal 1:1 pixel scale
    display.setTextColor(SSD1306_WHITE);  // Draw white text
    //display.setCursor(0, 0);              // Start at top-left corner
    display.cp437(true);  // Use full 256 char 'Code Page 437' font

    display.setCursor(0, 0);  // Start at top-left corner
    display.println(now.hour());
    display.setCursor(30, 0);  // Start at top-left corner
    display.println("ora");

    display.setCursor(0, 20);  // Start at top-left corner
    display.println(now.minute());
    display.setCursor(30, 20);  // Start at top-left corner
    display.println("min");

    display.setCursor(0, 40);  // Start at top-left corner
    display.println(now.second());
    display.setCursor(30, 40);  // Start at top-left corner
    display.println("sec");

    display.display();

    //SD

    // Check to see if the file exists:
    if (SD.exists("/test.txt")) {
      Serial.println(".txt exists.");
    } else {
      Serial.println(".txt doesn't exist.");
    }

    datafile = SD.open("/test.txt", FILE_APPEND);  //apre file .txt e appende i dati alla fine del file

    if (datafile)  //if the file is available, write to it:
    {
      datafile.print(now.hour());      //scrive ora
      datafile.print(':');             //separatore
      datafile.print(now.minute());    //scrive ora
      datafile.print(':');             //separatore
      datafile.println(now.second());  //scrive ora
      datafile.close();                //chiude file

      Serial.println("scrivo su file");
    }

    id_sens++;

    Serial.print("next id is ");
    Serial.println(id_sens);
    Serial.println();
    Serial.println();
    Serial.println();
  }

  if (id_sens == num_sensori) {
    id_sens = 0;
  }
}  //fine loop

// callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  char macStr[30];
  Serial.print("Packet to: ");
  // Copies the sender mac address to a string
  snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",

  mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);

  Serial.print(macStr);
  Serial.print(" send status:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}

//data from periphericals
//callback function that will be executed when data is received
void OnDataRecv(const uint8_t *mac, const uint8_t *incomingData, int len) {
  Serial.println("dati ricevuti");
  memcpy(&myData, incomingData, sizeof(myData));
  Serial.print("Bytes received: ");
  Serial.println(len);
  Serial.println("id_sens:");
  Serial.print(myData.id_sens);
  Serial.println();
  Serial.print("Float: ");
  Serial.println(myData.t);
  Serial.print("Float: ");`Use code tags to format code for the forum`
  Serial.println(myData.rh);
}

sotto B

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp-now-esp32-arduino-ide/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

//SLV

#define LED 2

#include <SPI.h>   //SPI, OLED SPI, max 31855, HTU21D
#include <Wire.h>  //I2C, RTC DS1307, OLED I2C

//HTU21D

// Connect Vin to 3-5VDC
// Connect GND to ground
// Connect SCL to I2C clock pin (A5 on UNO)
// Connect SDA to I2C data pin (A4 on UNO)

#include "Adafruit_HTU21DF.h"
Adafruit_HTU21DF htu = Adafruit_HTU21DF();

//variabili

byte id_sens;  //id periferica
float t;       // HTU21D
float rh;      //HTU21D
byte flag;
byte tx_delay;

//ESP32

#include <esp_now.h>
#include <WiFi.h>

// Structure example to receive data Must match the trasmitter structure
typedef struct struct_msg_1 {
  byte id_sens;  //variabile per id slave
} struct_msg_1;

struct_msg_1 myID;  // Create a struct_message called myData

// Structure example to send data Must match the receiver structure
typedef struct struct_msg_2 {
  byte id_sens;
  float t;
  float rh;
} struct_msg_2;

struct_msg_2 myData;  // Create a struct_message called myData

//address master REPLACE WITH YOUR MST RECEIVER MAC Address
uint8_t broadcastAddress_MST[] = { 0x58, 0xBF, 0x25, 0xE9, 0x70, 0xC8 };

esp_now_peer_info_t peerInfo;

void setup() {

  Serial.begin(115200);  // Initialize Serial Monitor

  WiFi.mode(WIFI_STA);  // Set device as a Wi-Fi Station

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }

  esp_now_register_recv_cb(OnDataRecv);  // Once ESPNow is successfully Init, we will register for recv CB to get recv packer info

  memcpy(peerInfo.peer_addr, broadcastAddress_MST, 6);  // Register peer
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

  if (esp_now_add_peer(&peerInfo) != ESP_OK) {  // Add peer
    Serial.println("Failed to add peer");
  }

  /*
  //HTU21D

  delay(2000);  //tempo di avvio sensore

  if (!htu.begin()) {
    delay(5000);  //attesa risposta
    Serial.println("01 Couldn't find HTU21D sensor");
    blink_1();
  } else {
    Serial.println("HTU21D ready");
    t = 0.0;   //inizializzo variabili sensore
    rh = 0.0;  //inizializzo variabili sensore
  }
 */

  pinMode(LED, OUTPUT);

  digitalWrite(LED, HIGH);  //turn the LED on (HIGH is the voltage level)
  delay(5000);
  digitalWrite(LED, LOW);  //turn the LED on (HIGH is the voltage level)

  //id_sens = 4;  //id periferica
  tx_delay = 500;

  Serial.println("program starts");  //stampa controllo
}

void loop() {
  if (flag == 1) {

    //HTU21D
    /*
    if (!htu.begin())  //check if returns are valid, if they are NaN (not a number) then something went wrong!
    {
      delay(5000);
      Serial.println("02 Couldn't find HTU21D sensor");
      blink_1();
    } else {
      t = htu.readTemperature();  //leggo temperatura
      rh = htu.readHumidity();    //leggo umidità  }

    myData.t = htu.readTemperature();  //leggo temperatura
    myData.rh = htu.readHumidity();    //leggo umidità
    }
   */

    Serial.println("spedisco dati");  //control print

    myData.id_sens = id_sens;    //id peripherical
    myData.t = random(10, 50);   //reading temperature
    myData.rh = random(10, 50);  //reading hunidity

    Serial.println(myData.id_sens);  //control print
    Serial.println(myData.t);        //control print
    Serial.println(myData.rh);       //control print

    // Send message via ESP-NOW
    esp_err_t result = esp_now_send(broadcastAddress_MST, (uint8_t *)&myData, sizeof(myData));

    if (result == ESP_OK) {
      Serial.println("Sent with success");
    } else {
      Serial.println("Error sending the data");
    }
    flag = 0;
  }
}  //fine loop

//richiamata quando HTU21D non risponde
void blink_1()  // HTU21D non pervenuto
{
  do {
    digitalWrite(LED, HIGH);
    delay(500);
    digitalWrite(LED, LOW);
    delay(500);
  } while (1);
}

// 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");
}

// callback function that will be executed when data is received
void OnDataRecv(const uint8_t *mac, const uint8_t *incomingData, int len) {
  Serial.println("data received");
  memcpy(&myID, incomingData, sizeof(myID));
  Serial.print("Bytes received: ");
  Serial.println(len);
  Serial.println("id_sens:");
  Serial.print(myID.id_sens);
  Serial.println();
  Serial.println();
  Serial.println();

id_sens = myID.id_sens;

  flag = 1;
}

Nello sketch A non hai nessuna funzione di callback registrata per la ricezione e nello sketch B invece non hai registrato la funzione di callback per l'invio dei dati quindi il messaggio da B verso A, anche se inviato con successo, non viene mai "processato" né in trasmissione e né soprattutto in ricezione.

ciao
grazie ci sto lavorando, mi sono accorto

sotto A come lo ho scritto adesso

/**************************************************************************
  This is an example for our Monochrome OLEDs based on SSD1306 drivers

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/category/63_98

  This example is for a 128x64 pixel display using I2C to communicate
  3 pins are required to interface (two I2C and one reset).

  Adafruit invests time and resources providing this open
  source code, please support Adafruit and open-source
  hardware by purchasing products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries,
  with contributions from the open source community.
  BSD license, check license.txt for more information
  All text above, and the splash screen below must be
  included in any redistribution.
 **************************************************************************/

//MST
#define LED 2

#include <SPI.h>               //SD
#include <Wire.h>              //RTC3231 OLED
#include <Adafruit_GFX.h>      //OLED
#include <Adafruit_SSD1306.h>  //OLED
#include "FS.h"                //SD
#include "SD.h"                //SD

//sezione ESP32
#include <esp_now.h>  //ESP32
#include <WiFi.h>     //ESP32

// REPLACE WITH YOUR ESP RECEIVER'S MAC ADDRESS

//uint8_t broadcastAddress1[] = { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0xC0 };
//uint8_t broadcastAddress2[] = { 0x24, 0x0A, 0xC4, 0xAE, 0xAE, 0x44 };
//uint8_t broadcastAddress3[] = { 0x80, 0x7D, 0x3A, 0x58, 0xB4, 0xB0 };
//uint8_t broadcastAddress4[] = { 0x3C, 0x71, 0xBF, 0xC3, 0xBF, 0xB0 };
//uint8_t broadcastAddress5[] = { 0x04, 0x0A, 0xC4, 0xAE, 0xAE, 0x44 };

// REPLACE WITH YOUR ESP RECEIVER'S MAC ADDRESS

uint8_t mac_Add[5][6] = {
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0x41 },  //1st peripherical
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0x42 },  //2nd peripherical
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0x43 },  //3rd peripherical
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0x44 },  //4th peripherical
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0xC0 }   //5th peripherical connected
};

uint8_t broadcastAddress[] = { 0, 0, 0, 0, 0, 0 };

//uint8_t broadcastAddress1[] = { mac_Add[0][0], mac_Add[0][1], mac_Add[0][2], mac_Add[0][3], mac_Add[0][4], mac_Add[0][5] };
//uint8_t broadcastAddress2[] = { mac_Add[1][0], mac_Add[1][1], mac_Add[1][2], mac_Add[1][3], mac_Add[1][4], mac_Add[1][5] };
//uint8_t broadcastAddress3[] = { mac_Add[2][0], mac_Add[2][1], mac_Add[2][2], mac_Add[2][3], mac_Add[2][4], mac_Add[3][5] };
//uint8_t broadcastAddress4[] = { mac_Add[3][0], mac_Add[3][1], mac_Add[3][2], mac_Add[3][3], mac_Add[3][4], mac_Add[3][5] };
//uint8_t broadcastAddress5[] = { mac_Add[4][0], mac_Add[4][1], mac_Add[4][2], mac_Add[4][3], mac_Add[4][4], mac_Add[4][5] };

// Structure example to send data Must match the peripherical structure
typedef struct test_struct {
  byte id;
} test_struct;

test_struct test_1;

// Structure message from the peripherical structure
typedef struct struct_msg_2 {
  byte id_sens;
  float t;
  float rh;
} struct_msg_2;

struct_msg_2 myData;  // Create a struct_message called myData

esp_now_peer_info_t peerInfo;

//OLED

#define SCREEN_WIDTH 128  // OLED display width, in pixels
#define SCREEN_HEIGHT 64  // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET -1        // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3c  ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

//RTC DS3231

#include "RTClib.h"
RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

//SD

byte chipSDSelect;
File datafile;

//variabili

unsigned long previousMillis;  // will store last time
long sampling_delay;           //intervallo di campionamento
byte SD_delay;
byte rx_delay;
byte id_sens;  //id sensore
byte num_sensori;

void setup() {

  Serial.begin(115200);  // Start the serial interface

  Wire.begin();  // Start the I2C interface

  //variabili

  sampling_delay = 4000;  //millis intervallo delle interrogazioni delle stazioni
  SD_delay = 2;           //ritardo scrittura valori su SD
  rx_delay = 7;           //ritardo ciclo ricezione dati
  previousMillis = 0;
  num_sensori = 5;

  //ESP32

  WiFi.mode(WIFI_STA);

  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
  }

  // 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
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

  // register peers
  for (id_sens = 0; id_sens < num_sensori; id_sens++) {

    //broadcastAddress[] = { mac_Add[id_sens][0], mac_Add[id_sens][1], mac_Add[id_sens][2], mac_Add[id_sens][3], mac_Add[id_sens][4], mac_Add[id_sens][5] };

    //memcpy(peerInfo.peer_addr, broadcastAddress, 6);
    memcpy(peerInfo.peer_addr, mac_Add[id_sens], (sizeof(mac_Add[id_sens]) / sizeof(mac_Add[id_sens][0])));  //dal forum

    if (esp_now_add_peer(&peerInfo) != ESP_OK) {
      Serial.println("Failed to add peer");
      return;
    }
  }

  id_sens = 0;  //azzero id_sens dopo il for

  //OLED

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C, false, false)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ;  // Don't proceed, loop forever
  }

  // Show initial display buffer contents on the screen --
  // the library initializes this with an Adafruit splash screen.

  display.display();

  // display.display() is NOT necessary after every single drawing command,
  // unless that's what you want...rather, you can batch up a bunch of
  // drawing operations and then update the screen all at once by calling
  // display.display(). These examples demonstrate both approaches...

  delay(2000);  // Pause for 2 seconds

  display.clearDisplay();  // Clear the buffer

  display.display();

  delay(2000);

  //RTC

  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    while (1) delay(10);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }

  //SD

  chipSDSelect = 5;
  pinMode(chipSDSelect, OUTPUT);
  SD.begin(chipSDSelect);
  Serial.println("Initializing SD card...1");

  delay(500);

  if (!SD.begin(chipSDSelect))  // see if the card is present and can be initialized:
  {
    Serial.println("Card failed, or not present");  // don't do anything more
    digitalWrite(5, HIGH);
    while (1)
      ;
  } else {
    Serial.println("SD card initialized...2");
  }

  pinMode(LED, OUTPUT);

  digitalWrite(LED, HIGH);  //turn the LED on (HIGH is the voltage level)
  delay(5000);
  digitalWrite(LED, LOW);  //turn the LED on (HIGH is the voltage level)

  Serial.println("program starts");  //stampa controllo
}

void loop() {

  if (millis() - previousMillis >= sampling_delay) {
    previousMillis = millis();  //save the last time

    //ESP32
    // Set values to send

    memcpy(broadcastAddress, mac_Add[id_sens], (sizeof(mac_Add[id_sens]) / sizeof(mac_Add[id_sens][0])));  //dal forum arduino

    test_1.id = id_sens;

    Serial.print("actual id_sens/peripherical is ");
    Serial.println(id_sens);
    Serial.print("test_1.id ");
    Serial.println(test_1.id);

    esp_err_t result_1 = esp_now_send(broadcastAddress, (uint8_t *)&test_1, sizeof(test_1));

    if (result_1 == ESP_OK) {
      Serial.println("Sent with success");
    } else {
      Serial.println("Error sending the data");
    }

    //delay(200);

    //RTC

    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");

    if (now.hour() < 10) {
      Serial.print('0');
    }
    Serial.print(now.hour(), DEC);
    Serial.print(':');

    if (now.minute() < 10) {
      Serial.print('0');
    }
    Serial.print(now.minute(), DEC);
    Serial.print(':');

    if (now.second() < 10) {
      Serial.print('0');
    }
    Serial.print(now.second(), DEC);
    Serial.println();

    //OLED
    // Not all the characters will fit on the display. This is normal.
    // Library will draw what it can and the rest will be clipped.
    display.clearDisplay();

    display.setTextSize(2);               // Normal 1:1 pixel scale
    display.setTextColor(SSD1306_WHITE);  // Draw white text
    //display.setCursor(0, 0);              // Start at top-left corner
    display.cp437(true);  // Use full 256 char 'Code Page 437' font

    display.setCursor(0, 0);  // Start at top-left corner
    display.println(now.hour());
    display.setCursor(30, 0);  // Start at top-left corner
    display.println("ora");

    display.setCursor(0, 20);  // Start at top-left corner
    display.println(now.minute());
    display.setCursor(30, 20);  // Start at top-left corner
    display.println("min");

    display.setCursor(0, 40);  // Start at top-left corner
    display.println(now.second());
    display.setCursor(30, 40);  // Start at top-left corner
    display.println("sec");

    display.display();

    //SD

    // Check to see if the file exists:
    if (SD.exists("/test.txt")) {
      Serial.println(".txt exists.");
    } else {
      Serial.println(".txt doesn't exist.");
    }

    datafile = SD.open("/test.txt", FILE_APPEND);  //apre file .txt e appende i dati alla fine del file

    if (datafile)  //if the file is available, write to it:
    {
      datafile.print(now.hour());      //scrive ora
      datafile.print(':');             //separatore
      datafile.print(now.minute());    //scrive ora
      datafile.print(':');             //separatore
      datafile.println(now.second());  //scrive ora
      datafile.close();                //chiude file

      Serial.println("scrivo su file");
    }

    id_sens++;

    Serial.print("next id is ");
    Serial.println(id_sens);
    Serial.println();
    Serial.println();
    Serial.println();
  }

  if (id_sens == num_sensori) {
    id_sens = 0;
  }
}  //fine loop

// callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  char macStr[30];
  Serial.print("Packet to: ");
  // Copies the sender mac address to a string
  snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",

  mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);

  Serial.print(macStr);
  Serial.print(" send status:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}

//data from periphericals
// callback function that will be executed when data is received
void OnDataRecv(const uint8_t * mac_addr, const uint8_t *incomingData, int len) {
  char macStr[30];
  Serial.print("Packet received from: ");
  snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
           mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
  Serial.println(macStr);
  memcpy(&myData, incomingData, sizeof(myData));
  Serial.printf("Board ID %u: %u bytes\n", myData.id_sens, len);
  Serial.print("Float: ");
  Serial.println(myData.t);
  Serial.print("Float: ");
  Serial.println(myData.rh);

  digitalWrite(LED, HIGH);  //turn the LED on (HIGH is the voltage level)
  delay(1000);
  digitalWrite(LED, LOW);  //turn the LED on (HIGH is the voltage level)
}

sotto B

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp-now-esp32-arduino-ide/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

//SLV

#define LED 2

#include <SPI.h>   //SPI, OLED SPI, max 31855, HTU21D
#include <Wire.h>  //I2C, RTC DS1307, OLED I2C

//HTU21D

// Connect Vin to 3-5VDC
// Connect GND to ground
// Connect SCL to I2C clock pin (A5 on UNO)
// Connect SDA to I2C data pin (A4 on UNO)

#include "Adafruit_HTU21DF.h"
Adafruit_HTU21DF htu = Adafruit_HTU21DF();

//variabili

byte id_sens;  //id periferica
float t;       // HTU21D
float rh;      //HTU21D
byte flag;
byte tx_delay;

//ESP32

#include <esp_now.h>
#include <WiFi.h>

// Structure example to receive data Must match the trasmitter structure
typedef struct struct_msg_1 {
  byte id_sens;  //variabile per id slave
} struct_msg_1;

struct_msg_1 myID;  // Create a struct_message called myID

// Structure example to send data Must match the receiver structure
typedef struct struct_msg_2 {
  byte id_sens;
  float t;
  float rh;
} struct_msg_2;

struct_msg_2 myData;  // Create a struct_message called myData

//address master REPLACE WITH YOUR MST RECEIVER MAC Address
uint8_t broadcastAddress_MST[] = { 0x58, 0xBF, 0x25, 0xE9, 0x70, 0xC8 };

esp_now_peer_info_t peerInfo;

void setup() {

  Serial.begin(115200);  // Initialize Serial Monitor

  WiFi.mode(WIFI_STA);  // Set device as a Wi-Fi Station

  // 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
  memcpy(peerInfo.peer_addr, broadcastAddress_MST, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

  // Add peer
  if (esp_now_add_peer(&peerInfo) != ESP_OK) {
    Serial.println("Failed to add peer");
    return;
  }
#
  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);

  /*
  //HTU21D

  delay(2000);  //tempo di avvio sensore

  if (!htu.begin()) {
    delay(5000);  //attesa risposta
    Serial.println("01 Couldn't find HTU21D sensor");
    blink_1();
  } else {
    Serial.println("HTU21D ready");
    t = 0.0;   //inizializzo variabili sensore
    rh = 0.0;  //inizializzo variabili sensore
  }
 */

  pinMode(LED, OUTPUT);

  digitalWrite(LED, HIGH);  //turn the LED on (HIGH is the voltage level)
  delay(5000);
  digitalWrite(LED, LOW);  //turn the LED on (HIGH is the voltage level)

  //id_sens = 4;  //id periferica
  tx_delay = 500;

  Serial.println("program starts");  //stampa controllo
}

void loop() {
  if (flag == 1) {

    //HTU21D
    /*
    if (!htu.begin())  //check if returns are valid, if they are NaN (not a number) then something went wrong!
    {
      delay(5000);
      Serial.println("02 Couldn't find HTU21D sensor");
      blink_1();
    } else {
      t = htu.readTemperature();  //leggo temperatura
      rh = htu.readHumidity();    //leggo umidità  }

    myData.t = htu.readTemperature();  //leggo temperatura
    myData.rh = htu.readHumidity();    //leggo umidità
    }
   */

    Serial.println("spedisco dati");  //control print

    myData.id_sens = id_sens;    //id peripherical
    myData.t = random(10, 50);   //reading temperature
    myData.rh = random(10, 50);  //reading hunidity

    Serial.println(myData.id_sens);  //control print
    Serial.println(myData.t);        //control print
    Serial.println(myData.rh);       //control print

    // Send message via ESP-NOW
    esp_err_t result = esp_now_send(broadcastAddress_MST, (uint8_t *)&myData, sizeof(myData));

    if (result == ESP_OK) {
      Serial.println("Sent with success");
    } else {
      Serial.println("Error sending the data");
    }
    flag = 0;
  }
}  //fine loop

//richiamata quando HTU21D non risponde
void blink_1()  // HTU21D non pervenuto
{
  do {
    digitalWrite(LED, HIGH);
    delay(500);
    digitalWrite(LED, LOW);
    delay(500);
  } while (1);
}

// 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");
}

// callback function that will be executed when data is received
void OnDataRecv(const uint8_t *mac, const uint8_t *incomingData, int len) {
  Serial.println("data received");
  memcpy(&myID, incomingData, sizeof(myID));
  Serial.print("Bytes received: ");
  Serial.println(len);
  Serial.println("id_sens:");
  Serial.print(myID.id_sens);
  Serial.println();
  Serial.println();
  Serial.println();

  id_sens = myID.id_sens;

  flag = 1;
}

Non capisco se questo è normale...

ciao
da A verso B

// Send message via ESP-NOW
    esp_err_t result_1 = esp_now_send(broadcastAddress, (uint8_t *)&test_1, sizeof(test_1));

funziona
quindi penso che da B verso A sia corretta

// Send message via ESP-NOW
    esp_err_t result = esp_now_send(broadcastAddress_MST, (uint8_t *)&myData, sizeof(myData));

Non credo

Puntatore a byte
Ma è un indirizzo, infatti gli si passa poi la dimensione
Penso che semplicemente decada ad indirizzo nella chiamata di funzione

La funzione è definita in questo modo

esp_err_t esp_now_send(const uint8_t *peer_addr, const uint8_t *data, size_t len)

Solo che nel suo caso myData è una struct di tipo struct_msg_2 quindi ha dovuto forzare il casting del puntatore altrimenti il compilatore segnala un errore di errata conversione da struct_msg_2* a const uint8_t*

In realtà avrebbe dovuto forzare il casting a (const uint8_t *) se proprio vogliamo fare i puntigliosi :sweat_smile:

ciao
gli esempi che seguo sono qui e altri sullo stesso sito
https://randomnerdtutorials.com/esp-now-many-to-one-esp32/
consapevole dei miei limiti, pensavo di avere compreso, ma non saprei cosa cambiare

Ma non potevano farla con argomento void* ?
Mi sembra una pippa mentale

In questo modo però ogni volta che vuoi usare la funzione devi necessariamente fare il casting del puntatore a prescindere dal tipo di dati.

Comunque la funzione è definita cosi nell'SDK Espressif.
Avranno avuto le loro ragioni e considerata la posizione che ha raggiunto nel mercato delle MCU, non mi pare che quelli di Espressif siano proprio degli incompetenti... :thinking:

Gli esempi sono dei punti di partenza che vanno presi come riferimento e poi sviluppati aggiundendo del proprio.
Nell'esempio in questione, l'autore vuole realizzare una connessione many-to-one dove i dati viaggiano solo in una direzione (da "many" verso "one" e non in quella inversa) ragione per cui nel primo sketch (quello che invia soltanto) registra solo questa funzione di callback

esp_now_register_send_cb(OnDataSent);

e nel secondo (quello che riceve e basta) registra solo questa

esp_now_register_recv_cb(OnDataRecv);

Tu invece vuoi realizzare una comunicazione bidirezionale, quindi ognuno dei nodi usati dovrà gestire sia la trasmissione che la ricezione dei dati, ragione per cui devi registrare e gestire sia la funzione di callback per la trasmissione e sia quella per la ricezione.

ciao
si gli esempi come punto di partenza
grazie per avermi risolto una parte del progetto in un altro post
quello che devo fare e' ad intervalli regolari
A interroga B0 e B0 trasmette i dati 0 ad A che scrive su SD
A interroga B1 e B1 trasmette i dati 1 ad A che scrive su SD
...
A interroga B4 e B4 trasmette i dati 4 ad A che scrive su SD
E il ciclo ricomincia
la comunicazione da A verso i B funziona
la comunicazione da Bi verso A no
provo a rivedermi gli esempi
soprattutto questo

https://randomnerdtutorials.com/esp-now-many-to-one-esp32/

anche se a me non cerco questa parte

// Create a structure to hold the readings from each board
struct_message board1;
struct_message board2;
struct_message board3;

grazie

ciao
ho aggiunto

esp_now_register_recv_cb(OnDataRecv);

adesso ricevo, era anche negli esempi :sleepy:

grazie per il suggerimento

Te l'ho scritto 3 volte che mancava quell'istruzione!!!

ciao
abbiate pazienza penso che a questo punto della vita ci si metta anche la eta'
non smettero' mai di ringraziare per il supporto che mi date

Stefano

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.