ESP32 domande per cominciare

Ciao

Mi interessa l uso di questo protocollo ESP NOW, che ho letto nominato in altra discussione, ho trovato in giro link ed esempi interessanti su questo modulo ESP da utilizzare con ide arduino, su ebay ho trovato moduli che hanno un oled integrato

https://randomnerdtutorials.com/esp-now-esp32-arduino-ide/

https://www.espressif.com/en/products/socs/esp32-c2

Sul sito expressif ci sono molti modelli
Mi interressava il modulo wifi+bt per visualizzare i dati su una app, le due modalita' sono utilizzabili insieme?
Voi dove comprate?

Grazie
Stefano

Da quanto mi risulta è possibile, ma non è cosa semplice (usano la stessa antenna e c'è una sequenza precisa da rispettare altrimenti non va) ... devi fare un po' di ricerche ... ci sono alcune discussioni in merito qui sulla sezione Italiana.

Rischiando (... ma, sino ad oggi, con gli ESP non ho mai avuto problemi :grin:) su AliExpress, altrimenti i soliti ditributori sul territorio.

Guglielmo

Ciao
Aggiorno su questo tema
Volevo espandere il progetto con il bt no ble anche se legendo il datasheet mi sembra che abbia solo il ble
Ottengo questo messaggio e non so' cosa togliere per ridurre le dimensioni

Sketch uses 1522197 bytes (116%) of program storage space. Maximum is 1310720 bytes.
Global variables use 57100 bytes (17%) of dynamic memory, leaving 270580 bytes for local variables. Maximum is 327680 bytes.
Sketch too big; see https://support.arduino.cc/hc/en-us/articles/360013825179 for tips on reducing it.
text section exceeds available space in board

Compilation error: text section exceeds available space in board

La scheda e' una esp wroom 32
Ho seguito il link ma non mi ha dato grandi suggerimenti

/**************************************************************************
  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  //built in led blu color

#include <Wire.h>              //RTC3231 OLED

//SD
#include <SPI.h>               //SD
#include "FS.h"                //SD
#include "SD.h"                //SD

//ESP32 wifi
#include <WiFi.h>     //ESP32
#include <esp_now.h>  //ESP32
#include <esp_wifi.h> //ESP32 LR

//ESP32 bt
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

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

//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] };

// REPLACE WITH YOUR ESP RECEIVER'S MAC ADDRESS

uint8_t mac_Add[5][6] = {
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0x41 },  //1st peripherical
  { 0xE4, 0x65, 0xB8, 0x20, 0x24, 0xBC },  //2nd peripherical connected
  { 0x08, 0xD1, 0xF9, 0xE7, 0x5F, 0xD8 },  //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 };

// 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;
//esp_wifi_peer_info_t peerInfo;

//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;  //id sensore
byte num_sensori;

float t, rh;

void setup() {

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

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

//ESP32 bt
  SerialBT.begin("ESP32test"); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");

  pinMode(LED, OUTPUT);

  //variabili
  sampling_delay = 5000;  //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);
  WiFi.mode(WIFI_AP_STA); //LR

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

  // Set Long Range Mode
  esp_wifi_set_protocol(WIFI_IF_STA, WIFI_PROTOCOL_LR);

  // Once ESPNow is successfully Init, we will register for Send CB to get the status of Trasnmitted packet
  esp_now_register_send_cb(OnDataSent);
  //esp_wifi_register_send_cb(OnDataSent);

  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);
  //esp_wifi_register_recv_cb(OnDataRecv);

  // 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) {
      //if (esp_wifi_add_peer(&peerInfo) != ESP_OK) {
      Serial.println("Failed to add peer");
      return;
    }
  }

  id_sens = 0;  //azzero id_sens dopo il for

  delay(2000);

  //RTC
  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    blink_1();
    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);
    blink_1();
  } else {
    Serial.println("SD card initialized...2");
  }

  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);

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

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

    //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();

   //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:
    {
      Serial.println("inizio scrittura su file");

      datafile.print(now.year(), DEC);
      datafile.print('/');
      datafile.print(now.month(), DEC);
      datafile.print('/');
      datafile.print(now.day(), DEC);

      datafile.print(',');

      datafile.print(now.hour());    //scrive ora
      datafile.print(':');           //separatore
      datafile.print(now.minute());  //scrive ora
      datafile.print(':');           //separatore
      datafile.print(now.second());  //scrive ora

      datafile.print(',');

      datafile.print(id_sens);
      datafile.print(',');
      datafile.print(myData.t);
      datafile.print(',');
      datafile.println(myData.rh);

      datafile.close();  //chiude file

      Serial.println("fine scrittura su file");

      //emptying variables
      myData.t = 0.0;
      myData.rh = 0.0;
    }

    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) {
  //void OnDataSent(const uint8_t *mac_addr, esp_wifi_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");
  //Serial.println(status == ESP_WIFI_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}

// callback function that will be executed when data is received
void OnDataRecv(const uint8_t *mac_addr_, const uint8_t *incomingData, int len) {

  myData.id_sens = 0;
  myData.t = 0.0;
  myData.rh = 0.0;

  char macStr_[6];
  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);

  id_sens = myData.id_sens;
  //t = myData.t;
  //rh = myData.rh;
}

void blink_1()  // errori sui collegmanti
{
  do {
    digitalWrite(LED, HIGH);
    delay(500);
    digitalWrite(LED, LOW);
    delay(500);
  } while (1);
}

grazie
stefano

Ti posso assicurare che non è cosi, BLE e WiFi si possono usare insieme senza alcun problema.

Considera che proprio in questi giorni sto sviluppando un gateway BLE che da un lato si collega a più dispositivi BLE e dall'altro aggiorna una database MySQL remoto.
Ad esempio c'è una funzione che fa lo scan dei device BLE e subito dopo aggiorna il database inserendo i record dei device appena trovati.

Anche io mi aspettavo problemi, invece funziona tutto in modo egregio.
C'è da dire che sto usando un ESP32-S3, però non credo che ci siano grandi differenze, in fondo le API da chiamare sono le stesse.

Devi selezionare una shema di partizione che riserva maggior spazio per il firmware (ad esempio Huge App oppure Minimal SPIFFS)

image

grazie per la dritta

mi dai qualche link da studiare?
intanto mi guardo il megatopic

E' corretto che il mio modulo ha solo il ble come sembra?

Se intendi tutorial o cose simili non saprei che cosa darti perché io me ne tengo alla larga :rofl:

Scherzi a parte, basta che prendi gli esempi inclusi nel core e metti insieme i pezzi.

No, non lo è.
L'ESP32 è compatibile con Bluetooth v4.2 e BLE e c'è anche scritto nel datasheet :wink:

Ma alla fine tu stai usando la libreria BluetoothSerial, quindi non capisco cosa ti cambia se la funzionalità viene emulata usando il Bluetooth Classic o il BLE.

La libreria dovrebbe usare il BT Classic, ma non ne sono certo. Bisognerebbe andare a vedere i sorgenti, anche se io proprio non capisco perché rinunciare alle funzionalità offerte dal Bluetooth (che sia Classic o Low Energy poco importa) e ridurre tutto ad una seriale emulata.

grazie vado a vedere

ho letto questo link
https://www.espressif.com/sites/default/files/documentation/esp32-wroom-32_datasheet_en.pdf

Ho letto queste affermazioni anche in altre discussioni mi puoi spiegare meglio?

grazie
stefano

E infatti c'è scritto anche li a pagina 6

A quale affermazioni ti riferisci?
Se stai parlando del NON usare il Bluetooth come se fosse una seriale è che a me sembra una stupidaggine: usi un sistema di trasmissione (Bluetooth) per emularne un altro (Seriale) e poi dover fare via software il parsing dei dati ricevuti per fare quello che il primo sistema ti consente di fare in modo nativo (lettura/scrittura/notifica delle caratteristiche).

Facendola molto molto semplificata, tu parli di voler visualizzare con un'app dei dati presenti nel tuo ESP32:

  • ciascun dato (o aggregato di dati) rappresenta una caratteristica da leggere/scrivere
  • queste caratteristiche possono essere eventualmente organizzate per "categorie"

Il tuo ESP32 dovrà configurare un "service" che espone delle caratteristiche del tipo di cui hai bisogno (interi, floiat, stringhe etc etc) e registrare delle funzioni di callback che verranno eseguite quando qualcuno interagisce con le caratteristiche: ci sarà la funzione per la lettura, quella per la scrittura e quella per la notifica.

La tua APP invece farà la scansione dei device raggiungibili: quando trova il tuo ESP32 si connette e sottoscrive le caratteristiche a cui sei interessato.

Comunque un esempio è più efficace di mille parole, più tardi se riesco faccio un post con uno sketch di test e un progettino MIT App Inventor

vero scusa

anche la mia app fatta con MIT APP Inventor
ho aggiunto una riga per mandare un valore in byte ad una app sul tel con successo

grazie
stefano

Bene ... avranno cambiato qualche cosa ... in passato NON era così ed i crash erano assicurati (se cerchi ci sono un'infinità di thread in merito). Probabilmente con il passare delle versioni del "core" hanno sistemato la cosa ... meglio così :slight_smile:

Guglielmo

1 Like

Ciao
Grazie per quello che hai condiviso lo tengo come bibbia
Sotto quello che ho fatto oggi

/**************************************************************************
  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  //built in led blu color

#include <Wire.h>  //RTC3231 OLED

//SD
#include <SPI.h>  //SD
#include "FS.h"   //SD
#include "SD.h"   //SD

//ESP32 wifi
#include <WiFi.h>      //ESP32
#include <esp_now.h>   //ESP32
#include <esp_wifi.h>  //ESP32 LR

//ESP32 bt
#include <BluetoothSerial.h>

//#define USE_PIN // Uncomment this to use PIN during pairing. The pin is specified on the line below
const char *pin = "1234";  // Change this to more secure PIN.

String device_name = "ESP32-BT-Slave";

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif

BluetoothSerial SerialBT;

char dataT[8] = { 0 };   //temperature HTU21DF
char dataRH[8] = { 0 };  //humidity HTU21DF

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

//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] };

// REPLACE WITH YOUR ESP RECEIVER'S MAC ADDRESS

uint8_t mac_Add[5][6] = {
  { 0xA0, 0xA3, 0xB3, 0x2F, 0x84, 0x41 },  //1st peripherical
  { 0xE4, 0x65, 0xB8, 0x20, 0x24, 0xBC },  //2nd peripherical not working
  { 0x08, 0xD1, 0xF9, 0xE7, 0x5F, 0xD8 },  //3rd peripherical not connected
  { 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 };

// 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;
//esp_wifi_peer_info_t peerInfo;

//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;  //id sensore
byte num_sensori;

float t, rh;

void setup() {

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

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

  //ESP32 bt
  SerialBT.begin(device_name);  //Bluetooth device name
  Serial.printf("The device with name \"%s\" is started.\nNow you can pair it with Bluetooth!\n", device_name.c_str());
//Serial.printf("The device with name \"%s\" and MAC address %s is started.\nNow you can pair it with Bluetooth!\n", device_name.c_str(), SerialBT.getMacString()); // Use this after the MAC method is implemented
#ifdef USE_PIN
  SerialBT.setPin(pin);
  Serial.println("Using PIN");
#endif

  pinMode(LED, OUTPUT);

  //variabili
  sampling_delay = 5000;  //millis intervallo delle interrogazioni delle stazioni
  previousMillis = 0;

  //numero sensori della rete
  num_sensori = 5;

  //ESP32
  //WiFi.mode(WIFI_STA);
  WiFi.mode(WIFI_AP_STA);  //LR

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

  // Set Long Range Mode
  esp_wifi_set_protocol(WIFI_IF_STA, WIFI_PROTOCOL_LR);

  // Once ESPNow is successfully Init, we will register for Send CB to get the status of Trasnmitted packet
  esp_now_register_send_cb(OnDataSent);
  //esp_wifi_register_send_cb(OnDataSent);

  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);
  //esp_wifi_register_recv_cb(OnDataRecv);

  // 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) {
      //if (esp_wifi_add_peer(&peerInfo) != ESP_OK) {
      Serial.println("Failed to add peer");
      return;
    }
  }

  id_sens = 0;  //azzero id_sens dopo il for

  delay(2000);

  //RTC
  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    blink_1();
    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);
    blink_1();
  } else {
    Serial.println("SD card initialized...2");
  }

  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

    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);

    //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

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

    delay(500);

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

    //RTC
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);

    Serial.print('/');

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

    Serial.print('/');

    if (now.day() < 10) {
      Serial.print('0');
    }
    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();

    //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:
    {
      Serial.println("inizio scrittura su file");

      datafile.print(now.year(), DEC);
      datafile.print('/');
      datafile.print(now.month(), DEC);
      datafile.print('/');
      datafile.print(now.day(), DEC);

      datafile.print(',');

      datafile.print(now.hour());    //scrive ora
      datafile.print(':');           //separatore
      datafile.print(now.minute());  //scrive ora
      datafile.print(':');           //separatore
      datafile.print(now.second());  //scrive ora

      datafile.print(',');

      datafile.print(id_sens);
      datafile.print(',');
      datafile.print(myData.t);
      datafile.print(',');
      datafile.println(myData.rh);

      datafile.close();  //chiude file

      Serial.println("fine scrittura su file");
      /*
      //BT
      dtostrf(myData.t, 7, 2, dataT);    //temperatura in un vettore scritto in dataT
      dtostrf(myData.rh, 7, 2, dataRH);  //temperatura in un vettore scritto in dataT

      Serial.println("scrivo su BT");

      Serial.print("dataT");  //control print
      Serial.println(dataT);  //control print

      Serial.print("dataRH");  //control print
      Serial.println(dataRH);  //control print

      SerialBT.println(id_sens);
      SerialBT.println(dataT);
      SerialBT.println(dataRH);
      SerialBT.println();
*/
      //emptying variables
      myData.t = 0.0;
      myData.rh = 0.0;
      dataT[8] = { 0 };   //temperatura HTU21DF
      dataRH[8] = { 0 };  //umidità HTU21DF
    }

    id_sens++;

    if (id_sens == num_sensori) {
      id_sens = 0;
    }

    Serial.print("next id is ");
    Serial.println(id_sens);
    Serial.println();
    Serial.println();
    Serial.println();
  }
}  //-------------------------------------------------------------------fine loop

// callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  //void OnDataSent(const uint8_t *mac_addr, esp_wifi_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");

  delay(500);

  Serial.println();
  Serial.println();
  Serial.println();
}

// callback function that will be executed when data is received
void OnDataRecv(const uint8_t *mac_addr_, const uint8_t *incomingData, int len) {

  myData.id_sens = 0;
  myData.t = 0.0;
  myData.rh = 0.0;

  char macStr_[6];
  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);

  //BT
  dtostrf(myData.t, 7, 2, dataT);    //temperatura in un vettore scritto in dataT
  dtostrf(myData.rh, 7, 2, dataRH);  //temperatura in un vettore scritto in dataT

  Serial.println("scrivo su BT");

  Serial.print("dataT");  //control print
  Serial.println(dataT);  //control print

  Serial.print("dataRH");  //control print
  Serial.println(dataRH);  //control print

  SerialBT.println(myData.id_sens);
  SerialBT.println(dataT);
  SerialBT.println(dataRH);
  SerialBT.println();
}

//viene eseguita se SD o RTC hanno problemi
void blink_1()  // errori sui collegmanti
{
  do {
    digitalWrite(LED, HIGH);
    delay(500);
    digitalWrite(LED, LOW);
    delay(500);
  } while (1);
}

al momento uso questa app per debug e testare il bt dell esp32
image

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