Agasthya Valluri
Agasthya Valluri

Reputation: 11

ESP-NOW Communication not delivering or receiving messages

I am trying send variables across two ESP32's (two-way communication) to display on a screen. My code was working as desired earlier but when i plug it in the last few hours it doesn't seem to transfer any data. It prints out that ESP-NOW message has been sent but the OnDataSent function's status is returned as "Delivery Failed". (The returned status is 1)

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



#define ZERO_SAMPLES 50
#define COUNTS_PER_PSI 735990  // Increased to further scale down PSI values
#define PSI_TO_CMH2O 70.307    // Conversion factor from PSI to cmH2O
#define DRIFT_THRESHOLD 0.1    // PSI threshold to consider as "no pressure"
#define STABLE_TIME 3000       // Time in ms that readings need to be stable for re-zeroing
#define DRIFT_SAMPLES 10       // Number of samples to check for drift

uint8_t broadcastAddress[] = { 0xf8, 0xb3, 0xb7, 0x4f, 0x4f, 0xf8 };
float pressure;
float oscfreq;
float susttime;

float incomingpres;
float incomingoscfreq;
float incomingsusttime;

int lcdColumns = 20;
int lcdRows = 4;
LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows);
String success;
long zeroOffset = 8290303;
bool isCalibrated = false;
int sampleCount = 0;
long calibrationSum = 0;

// Drift compensation variables
unsigned long stableStartTime = 0;
bool isStable = false;
float lastPSI = 0;
int stableSampleCount = 0;
const int inputpin = 15;
const int outputpin = 2;

typedef struct struct_message {
  float pres;
  float osc;
  float sust;
} struct_message;


struct_message fromwebpage;
struct_message towebpage;


esp_now_peer_info_t peerInfo;

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  //Serial.print("\r\nLast Packet Send Status:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
  if (status == 0) {
    success = "Delivery Success :)";
  } else {
    success = "Delivery Fail :(";
  }
}

void OnDataRecv(const uint8_t *mac, const uint8_t *incomingData, int len) {
  memcpy(&fromwebpage, incomingData, sizeof(fromwebpage));
  Serial.print("Bytes received: ");
  Serial.println(len);
  incomingpres = fromwebpage.pres;
  incomingoscfreq = fromwebpage.osc;
  incomingsusttime = fromwebpage.sust;
}

void checkAndUpdateZero(long rawPressure, float currentPSI) {
  // Check if current pressure is close to zero
  if (abs(currentPSI - 1) < DRIFT_THRESHOLD) {  // Remember we're applying -1 offset to PSI
    if (!isStable) {
      // Start tracking stable period
      isStable = true;
      stableStartTime = millis();
      stableSampleCount = 1;
    } else {
      stableSampleCount++;

      // Check if we've been stable long enough and have enough samples
      if (stableSampleCount >= DRIFT_SAMPLES && (millis() - stableStartTime) >= STABLE_TIME) {
        // Update zero offset
        zeroOffset = rawPressure;
        stableSampleCount = 0;
        isStable = false;
      }
    }
  } else {
    // Reset stable tracking if pressure is not near zero
    isStable = false;
    stableSampleCount = 0;
  }
}
float convertToPSI(long rawValue, long zero) {
  return (float)(rawValue - zero) / COUNTS_PER_PSI;
}

String readPressureRaw() {

  while (digitalRead(inputpin)) {}

  long result = 0;
  noInterrupts();

  for (int i = 0; i < 24; i++) {
    digitalWrite(outputpin, HIGH);
    digitalWrite(outputpin, LOW);
    result = (result << 1);
    if (digitalRead(inputpin)) {
      result++;
    }
  }

  for (char i = 0; i < 3; i++) {
    digitalWrite(outputpin, HIGH);
    digitalWrite(outputpin, LOW);
  }

  interrupts();

  float pressure = result ^ 0x800000;
  if (!isCalibrated) {
    calibrationSum += pressure;
    sampleCount++;
    if (sampleCount >= 3) {
      float zeroOffset = calibrationSum / 3;
      isCalibrated = true;
    }
    return "";
  } else {
    float psi = convertToPSI(pressure, zeroOffset);
    float cmH20 = psi * 70.307;
    String pressurern = String(cmH20, 2);
    return pressurern;
  }
};

float convertToPSI(long rawValue) {
  return (float)(rawValue - zeroOffset) / COUNTS_PER_PSI;
}

float convertToCmH2O(float psi) {
  return psi * PSI_TO_CMH2O;
}


void setup() {
  pinMode(inputpin, INPUT);
  pinMode(outputpin, OUTPUT);
  // Serial port for debugging purposes
  Serial.begin(115200);

  WiFi.mode(WIFI_STA);
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  };
  esp_now_register_send_cb(OnDataSent);
  memset(&peerInfo, 0, sizeof(peerInfo));
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

  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(esp_now_recv_cb_t(OnDataRecv));


  // Initialize sensor - power cycle the clock line
  digitalWrite(outputpin, LOW);
  delay(100);
  for (int i = 0; i < 10; i++) {
    digitalWrite(outputpin, HIGH);

    digitalWrite(outputpin, LOW);
  }

  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Press. |");
  lcd.setCursor(8, 0);
  lcd.print("Oscil.|");
  lcd.setCursor(15, 0);
  lcd.print("Sust.");
  lcd.setCursor(7, 1);
  lcd.print("|");
  lcd.setCursor(7, 2);
  lcd.print("|");
  lcd.setCursor(7, 3);
  lcd.print("|");
  lcd.setCursor(14, 1);
  lcd.print("|");
  lcd.setCursor(14, 2);
  lcd.print("|");
  lcd.setCursor(14, 3);
  lcd.print("|");
  lcd.setCursor(1, 3);
  lcd.print("cmH20");
  lcd.setCursor(10, 3);
  lcd.print("Hz");
  lcd.setCursor(17, 3);
  lcd.print("s");
}

void loop() {
  String pressuredata = readPressureRaw();
  float presslider = pressuredata.toFloat();
  float pressuresensor = round(presslider * 100) / 100;
  //Serial.println(fromwebpage.pres);
  towebpage.pres = pressuresensor;
  towebpage.osc = 0;
  towebpage.sust = 0;
  esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&towebpage, sizeof(towebpage));
  if (result == ESP_OK) {
    Serial.println("ESP-NOW message sent successfully");
  } else {
    Serial.println(result);
  }
  lcd.setCursor(0, 2);
  lcd.print(pressuresensor);
  lcd.setCursor(10, 2);
  lcd.print(fromwebpage.osc);
  lcd.setCursor(16, 2);
  lcd.print(fromwebpage.sust);
  delay(1000);
}

This is the output given by the code -

enter image description here

The same error is echoed in my receiver code -

#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <LittleFS.h>
#include <Arduino_JSON.h>
#include <esp_now.h>


const char* ssid = "Asian Crew";
const char* password = "Agastulate";

uint8_t broadcastAddress[] = {0x3c, 0x8a, 0x1f, 0xa8, 0xf9, 0x34};
float pressure;
float oscfreq;
float susttime;

float incomingpres;
float incomingoscfreq;
float incomingsusttime;

AsyncWebServer server(80);
AsyncEventSource events("/events");

String presVal = "0";
String oscVal = "0";
String sustVal = "0";
String recording = "0";

String success;

const char* PARAM_INPUT = "value";
unsigned long lastTime = 0;
unsigned long timerDelay = 750;
int newfile = 0;
bool seconditer = false;

typedef struct struct_message{
  float pres;
  float osc;
  float sust;
}struct_message;


struct_message fromsensor; 
struct_message tosensor;

esp_now_peer_info_t peerInfo;

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  //Serial.print("\r\nLast Packet Send Status:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
  if (status ==0){
    success = "Delivery Success :)";
  }
  else{
    success = "Delivery Fail :(";
  }
}

void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
  memcpy(&fromsensor, incomingData, sizeof(fromsensor));
  incomingpres = fromsensor.pres;
  incomingoscfreq = fromsensor.osc;
  incomingsusttime = fromsensor.sust;
} 

void initLittleFS() {
  if (!LittleFS.begin()) {
    Serial.println("An error has occurred while mounting LittleFS");
  }
  else{
    Serial.println("LittleFS mounted successfully");
  }
}

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi ..");
  //Serial.println(cmH20)
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

/* void writeToCSV(float pressure, float timeStamp, int newfile){
  if(newfile == 1){
    File file = LittleFS.open("/data.csv","w");
    file.printf("Time","Pressure");
    file.printf("%.2f,%.2f\n",timeStamp,pressure);
    file.close();
    }else if (newfile == 0){
      File file = LittleFS.open("/data.csv", "a");
      file.printf("%.2f,%.2f\n", timeStamp, pressure);
      file.close();
    }   
}; */

/* void triggerDownload() {
    File file = LittleFS.open("/data.csv", "r");
    if (!file) {
        Serial.println("Failed to open CSV file");
        return;
    }
    file.close();
    server.on("/trigger", HTTP_GET, [](AsyncWebServerRequest *request) {
        request->send(200, "text/html", "<script>window.location.href='/download';</script>");
    });
}
 */
void setup() {
  Serial.begin(115200);
  initWiFi();
  Serial.println();
  initLittleFS();
  if (esp_now_init() != ESP_OK){
    Serial.println("Error with ESP Now");
    return;
  };

  esp_now_register_send_cb(OnDataSent);
  memset(&peerInfo, 0, sizeof(peerInfo));
  memcpy(peerInfo.peer_addr,broadcastAddress,6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;
  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(esp_now_recv_cb_t(OnDataRecv)); 

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(LittleFS, "/index.html", "text/html");
  });
  server.serveStatic("/",LittleFS,"/");

  server.on("/Pressure", HTTP_GET, [] (AsyncWebServerRequest *request) {
    String inputMessage;
    // GET input1 value on <ESP_IP>/slider?value=<inputMessage>
    if (request->hasParam(PARAM_INPUT)) {
      inputMessage = request->getParam(PARAM_INPUT)->value();
      presVal = inputMessage;
    }
    else {
      inputMessage = "No message sent";
    }
    request->send(200, "text/plain", "OK");
  });
  server.on("/download", HTTP_GET, [](AsyncWebServerRequest *request) {
        request->send(LittleFS, "/data.csv", "text/csv");
    });
  server.on("/Oscillation", HTTP_GET, [] (AsyncWebServerRequest *request) {
    String inputMessage;
    // GET input1 value on <ESP_IP>/slider?value=<inputMessage>
    if (request->hasParam(PARAM_INPUT)) {
      inputMessage = request->getParam(PARAM_INPUT)->value();
      oscVal = inputMessage;
    }
    else {
      inputMessage = "No message sent";
    }
    request->send(200, "text/plain", "OK");
  });

  server.on("/record", HTTP_GET, [] (AsyncWebServerRequest *request) {
    String inputMessage;
    // GET input1 value on <ESP_IP>/slider?value=<inputMessage>
    if (request->hasParam(PARAM_INPUT)) {
      inputMessage = request->getParam(PARAM_INPUT)->value();
      recording = inputMessage;
    }
    else {
      inputMessage = "No message sent";
    }
    request->send(200, "text/plain", "OK");
  });
  
  
  server.on("/SustainTime", HTTP_GET, [] (AsyncWebServerRequest *request) {
    String inputMessage;
    // GET input1 value on <ESP_IP>/slider?value=<inputMessage>
    if (request->hasParam(PARAM_INPUT)) {
      inputMessage = request->getParam(PARAM_INPUT)->value();
      sustVal = inputMessage;
    }
    else {
      inputMessage = "No message sent";
    }
    request->send(200, "text/plain", "OK");
  });

  server.on("/readings", HTTP_GET, [](AsyncWebServerRequest *request){
    String json = String(fromsensor.pres,3);
    request->send(200, "application/json", json);
    json = String();
  });

  events.onConnect([](AsyncEventSourceClient *client){
    if(client->lastId()){
      Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId());
    }
    // send event with message "hello!", id current millis
    // and set reconnect delay to 1 second
    client->send("hello!", NULL, millis(), 10000);
  });
  server.addHandler(&events);

  // Start server
  server.begin();

}

void loop() {
  float PresValfloat = presVal.toFloat();
  float OscValfloat = oscVal.toFloat();
  float SustValfloat = sustVal.toFloat();
  String sensorpres = String(fromsensor.pres,3);
  tosensor.pres = PresValfloat;
  tosensor.osc = OscValfloat;
  tosensor.sust = SustValfloat;

  /* if (recording == "1"){
    if (seconditer == false){
      newfile = 1;
    } else {
      newfile = 0;
    }
    unsigned currentTime = millis()/1000;
    writeToCSV(fromsensor.pres,currentTime,newfile);
    seconditer = true;
  } else {
    seconditer = false;
  }; */

  esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &tosensor, sizeof(tosensor));
  //Serial.println(fromsensor.pres);
  if ((millis() - lastTime) > timerDelay) {
    // Send Events to the client with the Sensor Readings Every 10 seconds
    events.send("ping",NULL,millis());
    events.send(sensorpres.c_str(),"pressure",millis());
    lastTime = millis();
  }
 // printstuff();
  delay(1000);
} 

Was expecting data to be delivered successfully but instead got an error.

Upvotes: 0

Views: 31

Answers (0)

Related Questions