Changing received data with distance (ESP-Now)

berguinsson
Posts: 5
Joined: Mon Apr 13, 2020 9:04 am

Changing received data with distance (ESP-Now)

Postby berguinsson » Mon Apr 13, 2020 9:42 am

Hi everyone!

It's my first post in this forum and is about a strange problem that i have receiving data...

I have one board (2) with ds18b20 temperature sensor, and i have another board (1) which sends to the second board the interval and resolution values that i configure.
I do a structured message with IntervalT2, ResolutionT2, IntervalT3 and ResolutionT3. Sensor T3 is a sensor which i haven't put on the circuit yet. So by the moment i only have data of the sensor T2.
My problem is: when i have both boards close, i am able to send from board (1) to (2) interval and resolution. Thus, the second board receives these data and perform the modifications to get temperature following the interval and resolution set. Then, the second board sends it back to board (1). Instead, when i have the second board more far away, the second board receive correctly the interval but not the resolution.

Is it possible that, due to the major distance, i can't receive correctly the whole message, only a part (interval part).

When i have the boards far away, the resolution value of T2 is always set at the initialization value, so, it is not updated with the values that should be received from the board(1). Instead, the interval is changing as i indicate in board (1)

I calculate that up to 12 m i receive correctly interval and resolution. Up to 18 m, i only receive correctly the interval.

I think is something a little bit weird.

I append my code if someone wants to check it. (You will see that i do modbus stuff but theoretically this shouldn't affect Esp Now work.

Thank you so much for your help.

Hear is my code. I'm sorry some values names are in catalan. Resolution = Resolucio(In catalan)


Board(1)

Code: Select all

#include <SPI.h>
#include <Ethernet.h>
#include "local_config.h"  // <--- Change settings for YOUR network here.
#include <ModbusTCPServer.h>
#include <esp_now.h>
#include <WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>

/////////////////////////DEFINICIONS DS18B20///////////////////////////////////
#define ONEWIREBUS 17// els dos van pel mateix bus
OneWire ourWire(ONEWIREBUS);

DallasTemperature sensors(&ourWire); //Per a referir-nos a DallasTemperatura en referirem com sensors 
DeviceAddress sensorNP = {0x28,0xFF,0xE1,0x46,0x62,0x15,0x01,0x11}; //DeviceAddress es un tipus definit que correspon a un array de tipus enter de 8 posicions
///////////////////////////////////////////////////////////////////////////////
/////////////////DEFINICIONS TIMER I MODBUS (A TRAVÉS DE ETHERNET)///////////////////////////
bool _1s;
bool _2s;
unsigned long TimeAct2;
unsigned long TimeAct, TimePrev, HoldingResult, InputResult;
unsigned long TimePrev2;
EthernetServer EthServer(502);
ModbusTCPServer modbusTCPServer;
int i=0;
/////////////////////////////////////////////////////////////////////////////////////////

/////////////////////DEFINCIONS ESPNOW//////////////////////////////////////////////
// Global copy of slave
esp_now_peer_info_t peer;
char macStr[18];
#define NUMSLAVES 20
esp_now_peer_info_t slaves[NUMSLAVES] = {};
int SlaveCnt = 0;

void addPeer(uint8_t *peerMacAddress);
#define SENDCHANNEL 0
#define PRINTSCANRESULTS 0
uint8_t MACENVIAR[]={0x30,0xAE,0xA4,0xFA,0xF4,0x0C};//MAC DOIT ESP32
///////////////////////////////////////////////////////////////////////////////

float tempT2=0;
float tempT1=0;
float tempT3=0;
int32_t TempSensorT2=0;
int32_t TempSensorT1=0;
long IntervalT1=1000;
long IntervalT2=1000;
uint32_t ResolucioT1=12;
uint32_t ResolucioT2=12;
//Definim estrctura de les dades que rebrem
//De moment programat per a 2 sensors connectats al bus de la placa wifi
typedef struct struct_message {
    float T2;
    float T3;
   
} struct_message;

struct_message lecturesrebudes;

//De moment programam les dades amb les que enviarem l'interval
typedef struct dades_message{
  uint32_t InT2;
  uint8_t ReT2;
  uint32_t InT3;
  uint8_t ReT3;
}dades_message;

dades_message Dades_enviades;

/////////////////DETECCIONS DE ETHERNET//////////////////////////////
/*
 * Wiz W5500 reset function.  Change this for the specific reset
 * sequence required for your particular board or module.
 */
void WizReset() {
    Serial.print("Resetting Wiz W5500 Ethernet Board...  ");
    pinMode(RESET_P, OUTPUT);
    digitalWrite(RESET_P, HIGH);
    delay(250);
    digitalWrite(RESET_P, LOW);
    delay(50);
    digitalWrite(RESET_P, HIGH);
    delay(350);
    Serial.println("Done.");
}

//Detectam quin shield de ethernet empram
void prt_hwval(uint8_t refval) {
    switch (refval) {
    case 0:
        Serial.println("No hardware detected.");
        break;
    case 1:
        Serial.println("WizNet W5100 detected.");
        break;
    case 2:
        Serial.println("WizNet W5200 detected.");
        break;
    case 3:
        Serial.println("WizNet W5500 detected.");
        break;
    default:
        Serial.println
            ("UNKNOWN - Update espnow_gw.ino to match Ethernet.h");
    }
}


void prt_ethval(uint8_t refval) {
    switch (refval) {
    case 0:
        Serial.println("Uknown status.");
        break;
    case 1:
        Serial.println("Link flagged as UP.");
        break;
    case 2:
        Serial.println("Link flagged as DOWN. Check cable connection.");
        break;
    default:
        Serial.println
            ("UNKNOWN - Update espnow_gw.ino to match Ethernet.h");
    }
}
///////////////////////////FINAL DE DETECCIONS DE ETHERNET//////////////////


///////////////////////////ESP NOW MÈTODES/////////////////////////////////
/*
// Scan for slaves in AP mode
void ScanForSlave() {
  int8_t scanResults = WiFi.scanNetworks();
  //reset slaves
  memset(slaves, 0, sizeof(slaves));
  SlaveCnt = 0;
  Serial.println("");
  if (scanResults == 0) {
    Serial.println("No WiFi devices in AP Mode found");
  } else {
    Serial.print("Found "); Serial.print(scanResults); Serial.println(" devices ");
    for (int i = 0; i < scanResults; ++i) {
      // Print SSID and RSSI for each device found
      String SSID = WiFi.SSID(i);
      int32_t RSSI = WiFi.RSSI(i);
      String BSSIDstr = WiFi.BSSIDstr(i);

      if (PRINTSCANRESULTS) {
        Serial.print(i + 1); Serial.print(": "); Serial.print(SSID); Serial.print(" ["); Serial.print(BSSIDstr); Serial.print("]"); Serial.print(" ("); Serial.print(RSSI); Serial.print(")"); Serial.println("");
      }
      delay(10);
      // Check if the current device starts with `Slave`
      if (SSID.indexOf("Slave") == 0) {
        // SSID of interest
        Serial.print(i + 1); Serial.print(": "); Serial.print(SSID); Serial.print(" ["); Serial.print(BSSIDstr); Serial.print("]"); Serial.print(" ("); Serial.print(RSSI); Serial.print(")"); Serial.println("");
        // Get BSSID => Mac Address of the Slave
        int mac[6];

        if ( 6 == sscanf(BSSIDstr.c_str(), "%x:%x:%x:%x:%x:%x",  &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5] ) ) {
          for (int ii = 0; ii < 6; ++ii ) {
            slaves[SlaveCnt].peer_addr[ii] = (uint8_t) mac[ii];
          }
        }
        slaves[SlaveCnt].channel = CHANNEL; // pick a channel
        slaves[SlaveCnt].encrypt = 0; // no encryption
        SlaveCnt++;
      }
    }
  }

  if (SlaveCnt > 0) {
    Serial.print(SlaveCnt); Serial.println(" Slave(s) found, processing..");
  } else {
    Serial.println("No Slave Found, trying again.");
  }

  // clean up ram
  WiFi.scanDelete();
}
*/
// Check if the slave is already paired with the master.
// If not, pair the slave with master
void manageSlave() {
  if (SlaveCnt > 0) {
    for (int i = 0; i < SlaveCnt; i++) {
      Serial.print("Processing: ");
      for (int ii = 0; ii < 6; ++ii ) {
        Serial.print((uint8_t) slaves[i].peer_addr[ii], HEX);
        if (ii != 5) Serial.print(":");
      }
      Serial.print(" Status: ");
      // check if the peer exists
      bool exists = esp_now_is_peer_exist(slaves[i].peer_addr);
      if (exists) {
        // Slave already paired.
        Serial.println("Already Paired");
      } else {
        // Slave not paired, attempt pair
        esp_err_t addStatus = esp_now_add_peer(&slaves[i]);
        if (addStatus == ESP_OK) {
          // Pair success
          Serial.println("Pair success");
        } else if (addStatus == ESP_ERR_ESPNOW_NOT_INIT) {
          // How did we get so far!!
          Serial.println("ESPNOW Not Init");
        } else if (addStatus == ESP_ERR_ESPNOW_ARG) {
          Serial.println("Add Peer - Invalid Argument");
        } else if (addStatus == ESP_ERR_ESPNOW_FULL) {
          Serial.println("Peer list full");
        } else if (addStatus == ESP_ERR_ESPNOW_NO_MEM) {
          Serial.println("Out of memory");
        } else if (addStatus == ESP_ERR_ESPNOW_EXIST) {
          Serial.println("Peer Exists");
        } else {
          Serial.println("Not sure what happened");
        }
        delay(100);
      }
    }
  } else {
    // No slave found to process
    Serial.println("No Slave found to process");
  }
}

///Mètode per a afegir parella
void addPeer(uint8_t *peerMacAddress)
{
    peer.channel = SENDCHANNEL;
    
    peer.encrypt = false;
    
    memcpy(peer.peer_addr, peerMacAddress, 6);
    esp_err_t addStatus = esp_now_add_peer(&peer);
    if (addStatus == ESP_OK)
    {
      // Pair success
      Serial.println("Pair success");
    } 
    else if (addStatus == ESP_ERR_ESPNOW_NOT_INIT)
    {
      // How did we get so far!!
      Serial.println("ESPNOW Not Init");
    } 
    else if (addStatus == ESP_ERR_ESPNOW_ARG)
    {
      Serial.println("Add Peer - Invalid Argument");
    } 
    else if (addStatus == ESP_ERR_ESPNOW_FULL)
    {
      Serial.println("Peer list full");
    } 
    else if (addStatus == ESP_ERR_ESPNOW_NO_MEM)
    {
      Serial.println("Out of memory");
    } 
    else if (addStatus == ESP_ERR_ESPNOW_EXIST)
    {
      Serial.println("Peer Exists");
    } 
    else
    {
      Serial.println("Not sure what WENT WRONG");
    }
    delay(100);
}




// callback when data is sent from Master to Slave
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  char macStr[18];
  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("Last Packet Sent to: "); Serial.println(macStr);
  Serial.print("Last Packet Send Status: "); Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");*/
}

// Callback when data is sent from Slave To Master
// Mostram les dades
void onDataRecv(const uint8_t *mac_addr, const uint8_t *r_data, int data_len) {
  char macStr[18];
  
  uint8_t inData;  
  //MAC Adresse slave as info
  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("Last Packet Recv from: ");
  Serial.println(macStr);
  memcpy(&lecturesrebudes, r_data, sizeof(lecturesrebudes));
  
 tempT2 = lecturesrebudes.T2; //Estructura definida anteriorment
 tempT3 = lecturesrebudes.T3;
 /*
 Serial.println("La temperatura del sensor T2 es: ");
 Serial.println(tempT2,4);

 Serial.println("IntervalT1");
 Serial.println(IntervalT1);
 */
 
}


//////////////////////////////FINAL ESP NOW MÈTODES//////////////////////////////////



void setup() {
  sensors.begin();
   sensors.setResolution(12);
   Serial.begin(9600);
  //////////////////////////ETHERNET INICIALITZACIÓ///////////////////
      

    // Use Ethernet.init(pin) to configure the CS pin.
    Ethernet.init(5);           // GPIO5 on the ESP32.
    WizReset();

    /* 
     * Network configuration - all except the MAC are optional.
     *
     * IMPORTANT NOTE - The mass-produced W5500 boards do -not-
     *                  have a built-in MAC address (depite 
     *                  comments to the contrary elsewhere). You
     *                  -must- supply a MAC address here.
     */
    Serial.println("Starting ETHERNET connection...");
    Ethernet.begin(eth_MAC, eth_IP, eth_DNS, eth_GW, eth_MASK);
    Serial.println("S'ha iniciat l'ethernet");
    delay(200);
    EthServer.begin();          // start listening for Modbus clients
    modbusTCPServer.begin();    // start listening for Modbus clients
    
  // Define Holding register:
  HoldingResult = modbusTCPServer.configureHoldingRegisters(0, 100);
  InputResult = modbusTCPServer.configureInputRegisters(0, 100);

  Serial.print("Holding Reg init result =");
  Serial.print(HoldingResult);
  Serial.print("\n");

  Serial.print("Input Reg init result =");
  Serial.print(InputResult);
  Serial.print("\n");

  Serial.print("Modbus server address=");
  Serial.println(Ethernet.localIP());
  Serial.print("\n");

    /*
     * Sanity checks for W5500 and cable connection.
     */
    Serial.print("Checking connection.");
    bool rdy_flag = false;
    for (uint8_t i = 0; i <= 20; i++) {
        if ((Ethernet.hardwareStatus() == EthernetNoHardware)
            || (Ethernet.linkStatus() == LinkOFF)) {
            Serial.print(".");
            rdy_flag = false;
            Serial.println("Valor de HardwareStatus amb el qual es dictamina quin shield es");
            Serial.println(Ethernet.hardwareStatus());
            delay(80);
        } else {
            rdy_flag = true;
            Serial.println("Valor de HardwareStatus amb el qual es dictamina quin shield es");
            Serial.println(Ethernet.hardwareStatus());
            break;
        }
    }
    if (rdy_flag == false) {
        Serial.println
            ("\n\r\tHardware fault, or cable problem... cannot continue.");
        Serial.print("Hardware Status: ");
        prt_hwval(Ethernet.hardwareStatus());
        Serial.print("   Cable Status: ");
        prt_ethval(Ethernet.linkStatus());
        while (true) {
            delay(10);          // Halt.
            Serial.println("ENS QUEDAM AQUÍ SI NO HI HA CABLE ETHERNET PER TANT ESPNOW NO S'INICIALITZA");
        }
    } else {
        Serial.println(" OK");
    }
    ///////////////////////////////////////////////////////////////////////
 
  //Set device in STA mode to begin with
  WiFi.mode(WIFI_STA);
  Serial.println("ESPNow/Multi-Slave/Master Example");
  // This is the mac address of the Master in Station Mode
  Serial.print("STA MAC: "); Serial.println(WiFi.macAddress());
  // Init ESPNow with a fallback logic
 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);
  esp_now_register_recv_cb(onDataRecv);

  
            addPeer(MACENVIAR);
  snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
           MACENVIAR[0], MACENVIAR[1], MACENVIAR[2], MACENVIAR[3], MACENVIAR[4], MACENVIAR[5]);
           Serial.println("Parella afegida: "); Serial.println(macStr);
           
}





void loop() {
  sensors.setResolution(sensorNP,ResolucioT1);
  Serial.println(sensors.getResolution(sensorNP));
     EthernetClient client = EthServer.available();
  
  
       if (client.connected()) {
    modbusTCPServer.accept(client);
    // poll for Modbus TCP requests, while client connected
    modbusTCPServer.poll();
    
  }

   //---------------------------------------------------------------------------------
  // TIME  clock Interval
  TimeAct = millis();      // Millis value between  0 and  4294967295 //MILLIS ES UNSIGNED LOOOONG!!!

  _1s = false;
  if (  ( (TimeAct > TimePrev) and (TimeAct - TimePrev) > (IntervalT1)) or ((TimeAct < TimePrev) and (4294967295 - TimePrev + TimeAct) > (IntervalT1) )  ) {
    _1s = true;
    TimePrev = TimeAct;
    
    
  }

  TimeAct2= millis();
  _2s= false;
   if (  ( (TimeAct2 > TimePrev2) and (TimeAct2 - TimePrev2) > (IntervalT2)) or ((TimeAct2 < TimePrev2) and (4294967295 - TimePrev2 + TimeAct2) > (IntervalT2) )  ) {
    _2s = true;
    TimePrev2 = TimeAct2;
    
  }
  //---------------------------------------------------------------------------------

  if (_1s) {
    _1s = false;
    
  
     Serial.println("Temp sensor 1");
     Serial.println(tempT1,4);
     
     
     
    /* Serial.println("Temp sensor T2");
     Serial.println(TempSensorT2);*/

  
     TempSensorT1 = round(tempT1*10);   //Si tenim valor 23.6875 =236.875 i round() redondeja al valor enter més proxim =236. Es a dir, ja el tenim en enter i ja el podem enviar directament.
    /* Serial.println("Temp sensor T1");
     Serial.println(TempSensorT1);*/
     
  
    modbusTCPServer.holdingRegisterWrite(0x19,TempSensorT1 );//AQUÍ S'ASSENYALA L'ADREÇA, AL VALOR SE LI SUMA 40001
   
     sensors.requestTemperaturesByAddress(sensorNP);//Mesuram temperatura//PENTURA HEM DE FER REQUEST PER ADREESS!!
  tempT1=sensors.getTempC(sensorNP);
  /*Serial.println("Valor de T llegit:");
  Serial.println(tempT1,4);*/

     Serial.println("Intervals T1 i T2");
   Serial.println(IntervalT1);
   Serial.println(IntervalT2);
  }
  
if (_2s){
  
     TempSensorT2 = round(tempT2*10);
     Serial.println("Temp sensor 2");
     Serial.println(tempT2,4);
  _2s = false;

   
  modbusTCPServer.holdingRegisterWrite(0x0B,TempSensorT2);
}

   IntervalT1 = modbusTCPServer.holdingRegisterRead(0x1B);
   IntervalT2 = modbusTCPServer.holdingRegisterRead(0x1F);
   ResolucioT1 = modbusTCPServer.holdingRegisterRead(0x21);
   ResolucioT2 = modbusTCPServer.holdingRegisterRead(0x23);
  Serial.println("RESOLUCIOOOOOOOOOOOOOOOO DEL T2");
   Serial.println(ResolucioT2);
   Dades_enviades.InT2=IntervalT2;
   Dades_enviades.InT3=0;
   Dades_enviades.ReT2=ResolucioT2;
   Dades_enviades.ReT3=0;
esp_err_t result = esp_now_send(MACENVIAR,(uint8_t *) &Dades_enviades, sizeof(Dades_enviades));
//delay(100);

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

 

   
   
}


Board (2):

Code: Select all


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


/////////////////////////DEFINICIONS DS18B20///////////////////////////////////
#define ONEWIREBUS 17// els dos van pel mateix bus
OneWire ourWire(ONEWIREBUS);

DallasTemperature sensors(&ourWire); //Per a referir-nos a DallasTemperatura en referirem com sensors 
 
DeviceAddress sensorP = {0x28,0xFF,0x4C,0x96,0xC0,0x17,0x05,0x86}; //DeviceAddress es un tipus definit que correspon a un array de tipus enter de 8 posicions
//DeviceAddress sensorNP = {0x28,0xFF,0xE1,0x46,0x62,0x15,0x01,0x11}; 
///////////////////////////////////////////////////////////////////////////////
/////////////////////DEFINICIONS ESPNOW///////////////////////////

#define SENDCHANNEL 0

  char macStr[18];
esp_now_peer_info_t peer;
void addPeer(uint8_t *peerMacAddress);

//MAC DE LES PLAQUES
//uint8_t MACENVIAR[6]={0x30,0xAE,0xA4,0xFA,0xF4,0x0C};//MAC SI EL MESTRE ES DOIT ESP32
 uint8_t MACENVIAR[]={0x30,0xAE,0xA4,0x75,0x5E,0xC0};//MAC SI EL MESTRE ES ESP32 DEVMODULE
////////////////////////////////////////////////////////////////////

uint32_t IntervalT2=0;
uint32_t IntervalT3=0;
float tempT2;
float tempT3;
uint32_t ResolucioT2=9;
uint32_t ResolucioT3=0;
bool _2s;
unsigned long TimeAct, TimePrev2;



 //Definim estrctura de les dades que enviarem
//De moment programat per a 2 sensors connectats al bus de la placa wifi
typedef struct struct_message{
  float T2;
  float T3;
}struct_message;

struct_message lecturesds18b20;

typedef struct dades_message{
  uint32_t InT2;
  uint8_t ReT2;
  uint32_t InT3;
  uint8_t ReT3;
}dades_message;

dades_message Dades_rebudes;





// callback when data is recv from Master
void OnDataRecv(const uint8_t *mac_addr, const uint8_t *r_data, int data_len) {
  char macStr[18];

  //const uint8_t MACENVIAR[6];
  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("Last Packet Recv from: "); Serial.println(macStr);
  memcpy(&Dades_rebudes, r_data, sizeof(Dades_rebudes));
  IntervalT2 = Dades_rebudes.InT2;
  IntervalT3 = Dades_rebudes.InT3;
  ResolucioT2 = Dades_rebudes.ReT2;
  ResolucioT3 = Dades_rebudes.ReT3;

  Serial.println(IntervalT2);
  Serial.println(IntervalT3);
  Serial.println(ResolucioT2);
  Serial.println(ResolucioT3);
  
}


// callback when data is sent from Slave to Master
// AQUÍ MOSTRAM A QUI LI HEM ENVIAT LES DADES

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  char macStr[18];
 
  
  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("Last Packet Sent to: "); 
  Serial.println(macStr);
  Serial.print("Last Packet Send Status: "); 
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
  Serial.println("------------------------------------------------");
}


///Mètode per a afegir parella
void addPeer(uint8_t *peerMacAddress)
{
    peer.channel = SENDCHANNEL;
   
    peer.encrypt = false;
    
    memcpy(peer.peer_addr, peerMacAddress, 6);
    esp_err_t addStatus = esp_now_add_peer(&peer);
    if (addStatus == ESP_OK)
    {
      // Pair success
      Serial.println("Pair success");
    } 
    else if (addStatus == ESP_ERR_ESPNOW_NOT_INIT)
    {
      // How did we get so far!!
      Serial.println("ESPNOW Not Init");
    } 
    else if (addStatus == ESP_ERR_ESPNOW_ARG)
    {
      Serial.println("Add Peer - Invalid Argument");
    } 
    else if (addStatus == ESP_ERR_ESPNOW_FULL)
    {
      Serial.println("Peer list full");
    } 
    else if (addStatus == ESP_ERR_ESPNOW_NO_MEM)
    {
      Serial.println("Out of memory");
    } 
    else if (addStatus == ESP_ERR_ESPNOW_EXIST)
    {
      Serial.println("Peer Exists");
    } 
    else
    {
      Serial.println("Not sure what WENT WRONG");
    }
    delay(100);
}

void setup() {

  sensors.begin();
  Serial.begin(115200);
  Serial.println("ESPNow/Basic/Slave Example");
  //Set device in AP mode to begin with
  WiFi.mode(WIFI_STA);
 
  // This is the mac address of the Slave in AP Mode
  Serial.print("AP MAC: "); Serial.println(WiFi.macAddress());
  // Init ESPNow with a fallback logic
   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);
  esp_now_register_send_cb(OnDataSent);
  

  ///////////////////////AFEGIM PARELLA//////////////////////////////////////////
  /*Pos l'afegiment de la parella en el setup() perque tanmateix, si dormim amb sleep mode, torna a
  executar el setup()cada vegada. Abans ho tenia al principi del loop() amb una variable i 
  que només feia que s'executés una vegada, amb el deep sleep posant RTC_DATA_ATTR, conservava la
  variable i=1 i no tornava a entrar però no enviava correctament. Jo em pensava que era perque
  també perdia la variable MACENVIAR, però vaig poder comprovar que no. Arribava just abans del 
  esp_now_send amb la i=1 i MACENVIAR valguent el que havia de valer (direcció de la placa mestre)
  i no enviava correctament. Vaig arribar a la conclusió que amb el deep_sleep s'esborrava algun 
  dels valors que forçava l'AddPeer(), però que no me'ls deixava conservar amb el RTC_DATA_ATTR. Per tant
  em veig veure forçat executar aquest fragment de codi cada vegada, per tant el fic dins el setup()
  */
  addPeer(MACENVIAR);
  snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
           MACENVIAR[0], MACENVIAR[1], MACENVIAR[2], MACENVIAR[3], MACENVIAR[4], MACENVIAR[5]);
           Serial.println("Parella afegida: "); Serial.println(macStr);
           
  /////////////////////////////////////////////////////////////////////////////////
  
}












void loop() {

  sensors.setResolution(sensorP,ResolucioT2);

  Serial.println(sensors.getResolution(sensorP));
 // TIME  clock Interval
  TimeAct = millis();      // Millis value between  0 and  4294967295 //MILLIS ES UNSIGNED LOOOONG!!!

  _2s = false;
  if (  ( (TimeAct > TimePrev2) and (TimeAct - TimePrev2) > (IntervalT2)) or ((TimeAct < TimePrev2) and (4294967295 - TimePrev2 + TimeAct) > (IntervalT2) )  ) {
    _2s = true;
    TimePrev2 = TimeAct;
    
    
  }

  if(_2s){

 _2s = false;
sensors.requestTemperaturesByAddress(sensorP); //realitzam conversió de tots els sensors connectats, en canvi, requestTemperaturesByAdress, realitza la conversió només del sensor que li indicam.

  
 
  tempT2 = sensors.getTempC(sensorP);
  //tempT3 = sensors.getTempC(sensorNP);
  Serial.println("Temp sensor T2 :");
  Serial.println(tempT2,4);
  
  lecturesds18b20.T2=tempT2; //Encapsulam dades dins format definit de la trama a enviar
  lecturesds18b20.T3=tempT3;

 ///////ENVIAM DADES I ANALITZAM SI S'HAN ENVIAT CORRECTAMENT/////////////
  esp_err_t result = esp_now_send(MACENVIAR,(uint8_t *) &lecturesds18b20, sizeof(lecturesds18b20));
    if (result == ESP_OK) {
    Serial.println("Sent with success");
  }
  else {
    Serial.println("Error sending the data");
  }
 //////////////////////////////////////////////////////////////////////   

  }

/*
esp_sleep_enable_timer_wakeup(2000*1000);
    esp_deep_sleep_start();
    */
    /*
    delay(2000);
     */
}

ESP_Sprite
Posts: 9739
Joined: Thu Nov 26, 2015 4:08 am

Re: Changing received data with distance (ESP-Now)

Postby ESP_Sprite » Mon Apr 13, 2020 10:00 am

Mod note: I think your caps lock was accidentally on while typing the topic title. I fixed it for you.

berguinsson
Posts: 5
Joined: Mon Apr 13, 2020 9:04 am

Re: Changing received data with distance (ESP-Now)

Postby berguinsson » Tue Apr 14, 2020 11:49 am

ESP_Sprite wrote:
Mon Apr 13, 2020 10:00 am
Mod note: I think your caps lock was accidentally on while typing the topic title. I fixed it for you.
Oh, yes yo're right. Thank you!
Would anyone know why is changing the data received due to the distance?

Who is online

Users browsing this forum: snutw_ and 100 guests