espressif / arduino-esp32

Arduino core for the ESP32
GNU Lesser General Public License v2.1
13.31k stars 7.35k forks source link

Esp Now stop working after random days and freeze the esp32 #10220

Open Armagedon13 opened 3 weeks ago

Armagedon13 commented 3 weeks ago

Board

NodeMCU-32S

Device Description

NodeMCU-32S-details-3

Hardware Configuration

ifndef ETH_PHY_TYPE

define ETH_PHY_TYPE ETH_PHY_W5500

define ETH_PHY_ADDR 1

define ETH_PHY_CS 15

define ETH_PHY_IRQ 4

define ETH_PHY_RST 5

endif

// SPI pins

define ETH_SPI_SCK 14

define ETH_SPI_MISO 12

define ETH_SPI_MOSI 13

Version

latest master (checkout manually)

IDE Name

Arduino IDE 2.3.2

Operating System

Windows 11

Flash frequency

80 MHz

PSRAM enabled

yes

Upload speed

921600

Description

i have 2 Esp32 nodemcu, they connect each other with esp now that send 2 thins: The first is the heartbeat that check if the connection between the 2 esp exist and show a led status. The second is the weight scale data that send it from ethernet udp to the esp32 and the esp32 send it over esp32 to the second one. the program works really well, send all the data, and says the connection is stablished, but after 2 or more days the esp32 stops working, the led keep blinking like the connection exist, but the esp32 not response, i have a switch that you can change the esp32 to habilitate the OTA and wifi AP so you can program it. but the switch don't work is like it get stucked, the worst part is i put a Watchdog but i think it didin't work, i can't see the log of the problem because if i connect to usb start working normally, i change the power supply 3 times and i have a capacitor filter, all this in 5v in VIN

Sketch

/*
Transmisor
*/

#ifndef ETH_PHY_TYPE
#define ETH_PHY_TYPE ETH_PHY_W5500
#define ETH_PHY_ADDR 1
#define ETH_PHY_CS 15
#define ETH_PHY_IRQ 4
#define ETH_PHY_RST 5
#endif

// SPI pins
#define ETH_SPI_SCK 14
#define ETH_SPI_MISO 12
#define ETH_SPI_MOSI 13

#include <ETH.h>
#include <SPI.h>
#include <NetworkUdp.h>

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

#include <ezLED.h>  // ezLED library

// Definir pines para LEDs y switch
/*
led rojo: error
led verde: estado espnow
led amarillo: datos
*/

#define redLedPin 19
#define greenLedPin 23
#define activityLedPin 22

ezLED LED1(redLedPin);
ezLED LED2(greenLedPin);
ezLED LED3(activityLedPin);

#define switchPin 21  // Pin del interruptor

bool programmingMode = false;

static bool eth_connected = false;

// ESP NOW ------------------------------------------------------------------------------------------------------------------------------------------------------------
typedef struct struct_message {
  char data[250];
} struct_message;

struct_message payload;

// Global copy of peerInfo
#define CHANNEL 6

esp_now_peer_info_t peerInfo;

//Transmisor c8:f0:9e:52:78:94
byte mac[] = { 0xc8, 0xf0, 0x9e, 0x52, 0x78, 0x94 };

//Receptor c8:f0:9e:52:e9:6c
uint8_t broadcastAddress[] = { 0xc8, 0xf0, 0x9e, 0x52, 0xe9, 0x6c };  // MAC del segundo ESP32

// ESP-NOW Hearthbeat--------------------------------------------------------------------------------------------------------------------------------------------
#define HEARTBEAT_INTERVAL 5000   // Send heartbeat every 5 seconds
#define CONNECTION_TIMEOUT 10000  // Consider disconnected if no heartbeat for 15 seconds

unsigned long lastHeartbeatSent = 0;
unsigned long lastHeartbeatReceived = 0;
bool isConnected = false;

typedef struct struct_heartbeat {
  uint8_t flag;
} struct_heartbeat;

// Function to send heartbeat
void sendHeartbeat() {
  if (esp_now_is_peer_exist(broadcastAddress) == false) {
    Serial.println("Peer not found, re-adding...");
    esp_now_peer_info_t peerInfo;
    memcpy(peerInfo.peer_addr, broadcastAddress, 6);
    peerInfo.channel = 0;
    peerInfo.encrypt = false;
    esp_now_add_peer(&peerInfo);
  }

  struct_heartbeat heartbeat;
  heartbeat.timestamp = millis();
  esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&heartbeat, sizeof(struct_heartbeat));
  if (result == ESP_OK) {
    Serial.println("Heartbeat sent to Receiver");
  } else {
    Serial.print("Error sending heartbeat to Receiver: ");
    Serial.println(esp_err_to_name(result));
    LED1.blink(500, 500);
    LED2.turnOFF();
  }
}

void checkConnectionStatus() {
  if (millis() - lastHeartbeatReceived > CONNECTION_TIMEOUT) {
    if (isConnected) {
      isConnected = false;
      Serial.println("Connection to Receiver lost");
      LED1.blink(500, 500);
      LED2.turnOFF();
    }
  } else {
    if (!isConnected) {
      isConnected = true;
      Serial.println("Connection to Receiver established");
      LED2.blink(100, 500);
      LED1.turnOFF();
    }
  }
}

// ESP-NOW DATASEND and DATARECIVE --------------------------------------------------------------------------------------------------------------------------------------------------------------------
// callback when data is sent
void onDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("\r\nEstado del último paquete enviado:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Envío exitoso" : "Fallo en el envío");
}
// callback when data is recived
void onDataReceive(const esp_now_recv_info *info, const uint8_t *incomingData, int len) {
  if (len == sizeof(struct_heartbeat)) {
    lastHeartbeatReceived = millis();
    Serial.println("Heartbeat received from Receiver");
  }
}

// Setup -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void setup() {
  Serial.begin(115200);
  LED1.turnOFF();
  LED2.turnOFF();
  LED3.turnOFF();
  pinMode(switchPin, INPUT_PULLUP);  // Configurar el pin del interruptor

  SPI.begin(ETH_SPI_SCK, ETH_SPI_MISO, ETH_SPI_MOSI);
  ETH.begin(ETH_PHY_TYPE, ETH_PHY_ADDR, ETH_PHY_CS, ETH_PHY_IRQ, ETH_PHY_RST, SPI);
  ETH.config(local_ip, gateway, subnet, dns1);  // Static IP, leave without this line to get IP via DHCP
  Udp.begin(local_ip, localUdpPort);  // Enable UDP listening to receive data
  delay(2000);

   initEspNow();
}

// Loop ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void loop() {
  // Loop variables
  LED1.loop();
  LED2.loop();
  LED3.loop();
  checkSwitch();
  unsigned long currentMillis = millis();
   // Heartbeat Watchdog
    if (currentMillis - lastHeartbeatSent >= HEARTBEAT_INTERVAL) {
    sendHeartbeat();
    lastHeartbeatSent = currentMillis;
    }
  checkConnectionStatus();
}

void initEspNow() {
  WiFi.mode(WIFI_STA);
  esp_wifi_set_protocol(WIFI_IF_STA  , WIFI_PROTOCOL_LR);
  esp_wifi_set_channel(CHANNEL, WIFI_SECOND_CHAN_NONE);
  delay(1000);
  // This is the mac address of the Master in Station Mode
  Serial.print("STA MAC: ");
  Serial.println(WiFi.macAddress());
  Serial.print("STA CHANNEL ");
  Serial.println(WiFi.channel());

  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    LED1.blink(100, 100);  // Blink red LED to indicate error
    LED2.turnOFF();
    return;
  }

  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");
    LED1.blink(200, 200);
    LED2.turnOFF();
    return;
  } else{
    LED2.blink(250, 750);  // Blink green LED to indicate ESP-NOW is paired
    LED1.turnOFF();
  }

  esp_now_register_send_cb(onDataSent);
  esp_now_register_recv_cb(onDataReceive);
  Serial.println("ESP-NOW initialized");
}

Debug Message

rst:0x1 (POWERON_RESET),boot:0x17 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1288
load:0x40078000,len:13872
load:0x40080400,len:4
ho 8 tail 4 room 4
load:0x40080404,len:3048
entry 0x40080590
[     4][D][esp32-hal-cpu.c:264] setCpuFrequencyMhz(): PLL: 480 / 2 = 240 Mhz, APB: 80000000 Hz
=========== Before Setup Start ===========
Chip Info:
------------------------------------------
  Model             : ESP32
  Package           : D0WD-Q5
  Revision          : 1.44
  Cores             : 2
  CPU Frequency     : 240 MHz
  XTAL Frequency    : 40 MHz
  Embedded Flash    : No
  Embedded PSRAM    : No
  2.4GHz WiFi       : Yes
  Classic BT        : Yes
  BT Low Energy     : Yes
  IEEE 802.15.4     : No
------------------------------------------
INTERNAL Memory Info:
------------------------------------------
  Total Size        :   332948 B ( 325.1 KB)
  Free Bytes        :   302608 B ( 295.5 KB)
  Allocated Bytes   :    23276 B (  22.7 KB)
  Minimum Free Bytes:   297228 B ( 290.3 KB)
  Largest Free Block:   110580 B ( 108.0 KB)
------------------------------------------
Flash Info:
------------------------------------------
  Chip Size         :  4194304 B (4 MB)
  Block Size        :    65536 B (  64.0 KB)
  Sector Size       :     4096 B (   4.0 KB)
  Page Size         :      256 B (   0.2 KB)
  Bus Speed         : 80 MHz
  Bus Mode          : DIO
------------------------------------------
Partitions Info:
------------------------------------------
                nvs : addr: 0x00009000, size:    20.0 KB, type: DATA, subtype: NVS
            otadata : addr: 0x0000E000, size:     8.0 KB, type: DATA, subtype: OTA
               app0 : addr: 0x00010000, size:  1280.0 KB, type:  APP, subtype: OTA_0
               app1 : addr: 0x00150000, size:  1280.0 KB, type:  APP, subtype: OTA_1
             spiffs : addr: 0x00290000, size:  1408.0 KB, type: DATA, subtype: SPIFFS
           coredump : addr: 0x003F0000, size:    64.0 KB, type: DATA, subtype: COREDUMP
------------------------------------------
Software Info:
------------------------------------------
  Compile Date/Time : Jul 23 2024 15:14:11
  Compile Host OS   : windows
  ESP-IDF Version   : v5.1.4-497-gdc859c1e67-dirty
  Arduino Version   : 3.0.3
------------------------------------------
Board Info:
------------------------------------------
  Arduino Board     : NODEMCU_32S
  Arduino Variant   : nodemcu-32s
  Arduino FQBN      : esp32:esp32:nodemcu-32s:UploadSpeed=921600,FlashFreq=80,DebugLevel=debug,EraseFlash=all
============ Before Setup End ============
ETH Started
WiFi interface ready
WiFi STA client started
STA MAC: C8:F0:9E:52:78:94
STA CHANNEL 6
ESP-NOW initialized
=========== After Setup Start ============
INTERNAL Memory Info:
------------------------------------------
  Total Size        :   332948 B ( 325.1 KB)
  Free Bytes        :   245024 B ( 239.3 KB)
  Allocated Bytes   :    77396 B (  75.6 KB)
  Minimum Free Bytes:   244900 B ( 239.2 KB)
  Largest Free Block:   110580 B ( 108.0 KB)
------------------------------------------
GPIO Info:
------------------------------------------
  GPIO : BUS_TYPE[bus/unit][chan]
  --------------------------------------  
     1 : UART_TX[0]
     3 : UART_RX[0]
     4 : ETH_IRQ[0]
     5 : ETH_RST[0]
    12 : SPI_MASTER_MISO[3]
    13 : SPI_MASTER_MOSI[3]
    14 : SPI_MASTER_SCK[3]
    15 : ETH_CS[0]
    19 : GPIO
    21 : GPIO
    22 : GPIO
    23 : GPIO
============ After Setup End =============
Heartbeat sent to Receiver
Connection to Receiver established

Other Steps to Reproduce

No response

I have checked existing issues, online documentation and the Troubleshooting Guide

me-no-dev commented 3 weeks ago

@Armagedon13 we have our own ESP_NOW library for Arduino. It seems you are using IDF directly. Also your sketch needs to be minimized to only what is necessary to replicate the issue. Code above is too large.

@P-R-O-C-H-Y PTAL

Armagedon13 commented 3 weeks ago

@me-no-dev ok, im gonna edit it

Armagedon13 commented 3 weeks ago

we have our own ESP_NOW library for Arduino

the one i made is wrong? and there is no way to know if they are connected each other, thats why i made the heartbeat for that reason, to get a feedback with leds. I see the ESP example, and it's new, it's not too easy to set up.

Jason2866 commented 3 weeks ago

I had sometimes hangs when using the W5500 with Interrupt. Since changed to use the W5500 without Interrupt it works fine

seansimmons74 commented 3 weeks ago

Forgive me if this is unrelated but I noticed you are seeing a ~50k drop in free bytes/min free bytes. I am also having this issue and it never seems to recover (eventually leading to the board crashing/hanging). The first drop is 50k and then the rest are much smaller but it eventually causes my ESP32 to hang/perform slowly due to the continued drop in free heap. I am making http POST requests and I noticed that SOMEWHERE (still trying to narrow it down) in the HTTPClient.cpp file around this area: if(!_client->connect(_host.c_str(), _port, _connectTimeout)) { something happens causing my free heap to drop. If this is irrelevant, please disregard.

me-no-dev commented 3 weeks ago

@seansimmons74 it is irrelevant and should be fixed in 3.0.4

Armagedon13 commented 3 weeks ago

Is there any way to know the ESP NOW overflow? I tried sending more than the limit, the protocol stops working until the Esp32 is restarted, the size of the weight scale data never exceeds 70 bytes. I changed the heartbeat to only send one recognition byte, it does this every 5 seconds, maybe this overflows the protocol? I was testing if there are memory overflows but I don't see any errors.

me-no-dev commented 3 weeks ago

It is very hard to say, given that you do not provide any logs :) why not look into our library and try to use that instead.

Armagedon13 commented 3 weeks ago

@me-no-dev well... i see the examples but i don't understand how to use it, to make this i search over internet and see a good tutorial this, i just wanna make a bidirectional communication like i made, but im gonna try to make it.

me-no-dev commented 3 weeks ago

@P-R-O-C-H-Y will help you next week

lucasssvaz commented 3 weeks ago

@Armagedon13 Maybe this helps: https://developer.espressif.com/blog/arduino-esp-now-lib/

seansimmons74 commented 2 weeks ago

@seansimmons74 it is irrelevant and should be fixed in 3.0.4

@me-no-dev I'm still pretty new to all this but are you saying Arduino Core v3.0.4? I'm using platform IO and I'm a bit confused on how to upgrade to that. I see that even the latest espressif32 platform version is v6.8.0 and that only supports v2.0.17 of Arduino. Can you point me in the right direction to get this stuff updated to the proper version, please? Also, can you drop a link to the patch that you say fixes the problem in 3.0.4, please? Thank you for your help.

Jason2866 commented 2 weeks ago

@seansimmons74 The community fork pioarduino supports actual core 3.0.4 with Platformio https://github.com/pioarduino/platform-espressif32

seansimmons74 commented 2 weeks ago

@seansimmons74 The community fork pioarduino supports actual core 3.0.4 with Platformio https://github.com/pioarduino/platform-espressif32

@Jason2866 Ok I managed to update and am running 3.0.4. Also verified that the HTTPClient and WiFi libraries updated along with it (Build shows dependencies @ 3.0.4). I am still having the issue I mentioned before. Any other advice would be appreciated. If I need to create a proper issue somewhere, can you let me know where the right place might be?

me-no-dev commented 2 weeks ago

@seansimmons74 please open a new issue with minimal example to reproduce and good explanation on what and how it's happening.