[SOLVED] Arduino MEGA with RTC / LCD - Unexpected crash in 20 minutes running

Hello everybody. I'm having unexpected crashes with Arduino MEGA 2560, usually after 20 or 30 minutes of the program running. I'm Brazilian with problems friends.

It is a program for aquarium, controls 02 channels of led strips 12 white, these with slow ignition via MOSFET IFR450N via PWM.

Project already on the electrical panel. I have a 12V 10A hive supply, which feeds the arduino and the entire project. I have 02 smaller sources step down 12v to 5v and 3.3v.

It has 20x4 LCD, RTC DS 1307, a DS18B20 probe. The RTCDS 1307 being a controversial and problematic device, it was exchanged, not solving it.

04 relay channels in operation: A led strip (is this an inductive load??? I do not have a snubber, I will turn off this relay as soon as possible to see if it solves, I find it difficult because it also locks with this load off). It has a solenoid for CO2, a relay for an electrical panel fan. The esp01 binding is done, but I took the ESP out of the code and it keeps freezing.

02 channels of addressable led tape 2815 12v, these manipulated via the data, managing to use BRIGHTNESS++.


#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include "RTClib.h"
#include <FastLED.h>

#include <OneWire.h>
#include <DallasTemperature.h>
#define DS1307_ADDRESS 0x68

//LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

//As linhas de codigo a seguir devem ser comentadas, ou descomentadas, de acordo com o modelo de RTC utilizado (DS1307 ou DS3132)
RTC_DS1307 rtc; //Objeto rtc da classe DS1307
//RTC_DS3231 rtc; //Objeto rtc da classe DS3132


#define Pin 24

OneWire ourWire(Pin);
DallasTemperature sensors(&ourWire);



byte led = 13;      //cria uma variável inteira cchamada led com o numero do pino

const unsigned long eventInterval = 30; //intervalo de cada incremento de rpm do amanhanhecer e entardedecer que não fica preso em delay, compara em m_illis
const unsigned long eventIntervaltwo = 60; //intervalo que preciso para acionamentos manuais que não fica preso em delay, compara em m_illis. Cresce em multiplos dele mesmo
unsigned long eventIntervaladd = 0;
unsigned long previousTime = 0;
//const unsigned long eventInterva2 = 5000;
//unsigned long previousTime2 = 0;
byte ledwhite1 = 2;
byte ledwhite2 = 3;
//int ledcolor1 = 4;
//int ledcolor2 = 5;
byte ledlcd = 8;
const int buttonPin = 52;//Define buttonPin no pino digital 52
int buttonState = 0;//Variável responsável por armazenar o estado do botão (ligado/desligado)
byte valorBotao;      // salva valor do botao
boolean luztemporaria;
int countbotao = 0;

int percent;
int percentman;
unsigned long PWMvalue = 0;
boolean luz;
int tempori = 0;
int botaominute = 0;
int multplicmax = 15;
int timepressed = 0;
int contador = 1;
int minutoparadisplay = 0;
int luzman = 0;
bool rampaacend = 0;



byte rele1 = 30;
byte rele2 = 31;
byte rele3 = 32;
byte rele4 = 33;
byte rele5 = 34;
byte rele6 = 35;


boolean estadoco2 = 0;
boolean tubular = 0;
boolean fitaledtotal = 0;
boolean fullwhite = 0;

boolean ventilador = 0;

byte fan1 = 4;
byte fan2 = 5;

const byte buzzer = 26; //buzzer to arduino pin 9



#define NUM_LED_STRIP_1 61
#define NUM_LED_STRIP_2 60
#define NUM_LEDS_TOTAL  121
//#define BRIGHTNESS

#define LED_PIN_A 6
#define LED_PIN_B 7
#define UPDATES_PER_SECOND 100   // Set Speed 
#define LED_TYPE    WS2812B

CRGB ledsA[NUM_LED_STRIP_1];
CRGB ledsB[NUM_LED_STRIP_2];

//uint8_t brightness = 255;


int BRIGHTNESS = 0;



char diasDaSemana[7][12] = {"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"}; //Dias da semana






void setup() {



  pinMode(led, OUTPUT);     // inicaliza pino do led como saída digital

  sensors.begin();
  Serial.begin(9600);                          //Inicializa a comunicacao serial
  lcd.begin(20, 4);



  FastLED.addLeds<LED_TYPE, LED_PIN_A, RGB>(ledsA, NUM_LED_STRIP_1);
  FastLED.addLeds<LED_TYPE, LED_PIN_B, RGB>(ledsB, NUM_LED_STRIP_2);
  FastLED.setBrightness(BRIGHTNESS);


  ledsA[0 - 61] = CRGB::Black;
  ledsB[0 - 60] = CRGB::Black;

  FastLED.show();


  //pinMode (13, OUTPUT); //só para apagar o ledwhite1 L da placa
  //digitalWrite(13, LOW); //só para apagar o ledwhite1 L da placa
  pinMode(buttonPin , INPUT);//Define buttonPin (pino 2) como entrada

  pinMode (ledwhite1, OUTPUT);
  pinMode (ledwhite2, OUTPUT);


  if (! rtc.begin()) {                         //Se o RTC nao for inicializado, faz
    //Serial.println("RTC NAO INICIALIZADO");    //Imprime o texto
    //while (1);                                 //Trava o programa

  }

  digitalWrite(ledwhite1, LOW);
  digitalWrite(ledwhite2, LOW);


  //rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // ajusta para data e hora de compilacao
  //rtc.adjust(DateTime(2022, 6, 16, 11, 01, 15));   //Ajusta o tempo do RTC para a data e hora definida pelo usuario.



  analogWrite(ledlcd, 100);




  pinMode (rele1, OUTPUT);
  pinMode (rele2, OUTPUT);
  pinMode (rele3, OUTPUT);
  pinMode (rele4, OUTPUT);
  pinMode (rele5, OUTPUT);
  pinMode (rele6, OUTPUT);

  digitalWrite (rele1, HIGH); // 02 TUBULAR
  digitalWrite (rele2, LOW); // VENTOINHA QUADRO
  digitalWrite (rele3, HIGH); // CO2
  digitalWrite (rele4, HIGH); // FAN 01 & FAN 02
  digitalWrite (rele5, HIGH); //
  digitalWrite (rele6, HIGH); //

  pinMode (fan1, OUTPUT);
  pinMode (fan2, OUTPUT);

  analogWrite (fan1, 0);
  analogWrite (fan2, 0);


  delay(2000); // power-up safety delay





}

void loop() {


  //unsigned long previousMillisRevWarBuzzerOn = millis();


  DateTime now = rtc.now();                             // Faz a leitura de dados de data e hora
  //Serial.print(diasDaSemana[now.dayOfTheWeek()]);       //Imprime dia da semana
  //  Serial.print(" - ");                             //Imprime texto





  if (now.second() == 1)
  {
    sensors.requestTemperatures();
    //float airTemp = sensors.getTempCByIndex(0);

  }

  digitalWrite(led, HIGH);   // liga led 
  delay(2);               // aguarda 0,1 segundo 
  digitalWrite(led, LOW);    //desliga led
  delay(40); //aguarda 0,1 segundo 

  








ledsA[0] = CRGB::DeepSkyBlue;
ledsA[2] = CRGB::DeepSkyBlue;
ledsA[4] = CRGB::DeepSkyBlue;
ledsA[6] = CRGB::DeepSkyBlue;
ledsA[8] = CRGB::DeepSkyBlue;
ledsA[10] = CRGB::DeepSkyBlue;
ledsA[12] = CRGB::DeepSkyBlue;
ledsA[14] = CRGB::DeepSkyBlue;
ledsA[16] = CRGB::DeepSkyBlue;
ledsA[18] = CRGB::DeepSkyBlue;
ledsA[20] = CRGB::DeepSkyBlue;
ledsA[22] = CRGB::DeepSkyBlue;
ledsA[24] = CRGB::DeepSkyBlue;
ledsA[26] = CRGB::DeepSkyBlue;
ledsA[28] = CRGB::DeepSkyBlue;
ledsA[30] = CRGB::DeepSkyBlue;
ledsA[32] = CRGB::DeepSkyBlue;
ledsA[34] = CRGB::DeepSkyBlue;
ledsA[36] = CRGB::DeepSkyBlue;
ledsA[38] = CRGB::DeepSkyBlue;
ledsA[40] = CRGB::DeepSkyBlue;
ledsA[42] = CRGB::DeepSkyBlue;
ledsA[44] = CRGB::DeepSkyBlue;
ledsA[46] = CRGB::DeepSkyBlue;
ledsA[48] = CRGB::DeepSkyBlue;
ledsA[50] = CRGB::DeepSkyBlue;
ledsA[52] = CRGB::DeepSkyBlue;
ledsA[54] = CRGB::DeepSkyBlue;
ledsA[56] = CRGB::DeepSkyBlue;
ledsA[58] = CRGB::DeepSkyBlue;
ledsA[60] = CRGB::DeepSkyBlue;





ledsA[1] = CRGB::White;
ledsA[3] = CRGB::White;
ledsA[5] = CRGB::White;
ledsA[7] = CRGB::White;
ledsA[9] = CRGB::White;
ledsA[11] = CRGB::White;
ledsA[13] = CRGB::White;
ledsA[15] = CRGB::White;
ledsA[17] = CRGB::White;
ledsA[19] = CRGB::White;
ledsA[21] = CRGB::White;
ledsA[23] = CRGB::White;
ledsA[25] = CRGB::White;
ledsA[27] = CRGB::White;
ledsA[29] = CRGB::White;
ledsA[31] = CRGB::White;
ledsA[33] = CRGB::White;
ledsA[35] = CRGB::White;
ledsA[37] = CRGB::White;
ledsA[39] = CRGB::White;
ledsA[41] = CRGB::White;
ledsA[43] = CRGB::White;
ledsA[45] = CRGB::White;
ledsA[47] = CRGB::White;
ledsA[49] = CRGB::White;
ledsA[51] = CRGB::White;
ledsA[53] = CRGB::White;
ledsA[55] = CRGB::White;
ledsA[57] = CRGB::White;
ledsA[59] = CRGB::White;





ledsB[0] = CRGB::DeepSkyBlue;
ledsB[2] = CRGB::DeepSkyBlue;
ledsB[4] = CRGB::DeepSkyBlue;
ledsB[6] = CRGB::DeepSkyBlue;
ledsB[8] = CRGB::DeepSkyBlue;
ledsB[10] = CRGB::DeepSkyBlue;
ledsB[12] = CRGB::DeepSkyBlue;
ledsB[14] = CRGB::DeepSkyBlue;
ledsB[16] = CRGB::DeepSkyBlue;
ledsB[18] = CRGB::DeepSkyBlue;
ledsB[20] = CRGB::DeepSkyBlue;
ledsB[22] = CRGB::DeepSkyBlue;
ledsB[24] = CRGB::DeepSkyBlue;
ledsB[26] = CRGB::DeepSkyBlue;
ledsB[28] = CRGB::DeepSkyBlue;
ledsB[30] = CRGB::DeepSkyBlue;
ledsB[32] = CRGB::DeepSkyBlue;
ledsB[34] = CRGB::DeepSkyBlue;
ledsB[36] = CRGB::DeepSkyBlue;
ledsB[38] = CRGB::DeepSkyBlue;
ledsB[40] = CRGB::DeepSkyBlue;
ledsB[42] = CRGB::DeepSkyBlue;
ledsB[44] = CRGB::DeepSkyBlue;
ledsB[46] = CRGB::DeepSkyBlue;
ledsB[48] = CRGB::DeepSkyBlue;
ledsB[50] = CRGB::DeepSkyBlue;
ledsB[52] = CRGB::DeepSkyBlue;
ledsB[54] = CRGB::DeepSkyBlue;
ledsB[56] = CRGB::DeepSkyBlue;
ledsB[58] = CRGB::DeepSkyBlue;
ledsB[60] = CRGB::DeepSkyBlue;





ledsB[1] = CRGB::White;
ledsB[3] = CRGB::White;
ledsB[5] = CRGB::White;
ledsB[7] = CRGB::White;
ledsB[9] = CRGB::White;
ledsB[11] = CRGB::White;
ledsB[13] = CRGB::White;
ledsB[15] = CRGB::White;
ledsB[17] = CRGB::White;
ledsB[19] = CRGB::White;
ledsB[21] = CRGB::White;
ledsB[23] = CRGB::White;
ledsB[25] = CRGB::White;
ledsB[27] = CRGB::White;
ledsB[29] = CRGB::White;
ledsB[31] = CRGB::White;
ledsB[33] = CRGB::White;
ledsB[35] = CRGB::White;
ledsB[37] = CRGB::White;
ledsB[39] = CRGB::White;
ledsB[41] = CRGB::White;
ledsB[43] = CRGB::White;
ledsB[45] = CRGB::White;
ledsB[47] = CRGB::White;
ledsB[49] = CRGB::White;
ledsB[51] = CRGB::White;
ledsB[53] = CRGB::White;
ledsB[55] = CRGB::White;
ledsB[57] = CRGB::White;
ledsB[59] = CRGB::White;
ledsB[61] = CRGB::White;






  percent = (PWMvalue * 100) / 255;
  //Serial.print(percent);
  //Serial.println("%");
  //lcd.setCursor(0, 0);
  //lcd.clear();
  //lcd.print(percent);
  //lcd.print(" %");
  //lcd.print(" - ");
  //lcd.print(luz);
  //lcd.setCursor(0, 1);
  //lcd.print(PWMvalue);
  //lcd.print(" PWM");

  /////////////////////////////////////////////////////////////////////////////////////////////////////////////

  unsigned long currentTime = millis();


  /////////////////////////////////////////////////////////////////////////////////////////////////////////////

  // RETIRAO AQUI EM BAIXO SERIAL.PRINT DE HORARIO NO SERIAL MONITOR




  //retirado aqui de baixo todos serial print das varaiveis de iluminação




  Serial.print(diasDaSemana[now.dayOfTheWeek()]);       //Imprime dia da semana
  Serial.print(" - ");                             //Imprime texto


  if(now.hour() <10) Serial.print("0");                   // já no apartamento resolvido aparecendo só 1 dígito
  Serial.print(now.hour());                        //Imprime hora
  Serial.print(':');                                      //Imprime dois pontos
  if(now.minute() <10) Serial.print("0");
  Serial.print(now.minute());                      //Imprime os minutos
  Serial.print(':');
  if(now.second() <10) Serial.print("0");//Imprime dois pontos
  Serial.print(now.second());                    //Imprime os segundos
  Serial.print(' ');


  Serial.print(" - ");                             //Imprime texto
  Serial.print(percent);
  Serial.print("%");
  Serial.print(" - ");                             //Imprime texto
  Serial.print(countbotao);
  Serial.print(" - ");                             //Imprime texto
  Serial.print(eventIntervaladd);
  Serial.print(" - ");                             //Imprime texto

  Serial.print(" - ");                             //Imprime texto
  Serial.print(minutoparadisplay); // multiplicador

  Serial.print(" - ");                             //Imprime texto
  Serial.print(botaominute);
  //Serial.print((eventIntervaladd-previousTime)/eventIntervaltwo);
  Serial.print(" mins");                             //Imprime texto
  Serial.print(" - ");                             //Imprime texto
  Serial.print(PWMvalue); // multiplicador
  Serial.print(" - ");                             //Imprime texto
  Serial.print(luzman); // multiplicador
  Serial.print(" - ");                             //Imprime texto
  Serial.print(percentman); // multiplicador
  Serial.println("%");


  
  lcd.setCursor(0, 0);
  lcd.print(now.day(), DEC);                         //Imprime dia
  lcd.print('/');                                      //Imprime barra
  if (now.month() < 10) lcd.print("0"); lcd.print(now.month(), DEC);                     //Imprime mes
  lcd.print(" ");
  lcd.print(diasDaSemana[now.dayOfTheWeek()]);
  lcd.print(',');
  lcd.print(' ');






  if(now.hour() <10) lcd.print("0");                   // já no apartamento resolvido aparecendo só 1 dígito
  lcd.print(now.hour());                        //Imprime hora
  lcd.print(':');                                      //Imprime dois pontos
  if(now.minute() <10) lcd.print("0");
  lcd.print(now.minute());                      //Imprime os minutos
  lcd.print(':');
  if(now.second() <10) lcd.print("0");//Imprime dois pontos
  lcd.print(now.second());                    //Imprime os segundos
  lcd.print(' ');



if (sensors.getTempCByIndex(0) > 20 && sensors.getTempCByIndex(0) < 40) {

  lcd.setCursor(0, 1);
  lcd.print("    Temp: ");
  lcd.print(sensors.getTempCByIndex(0));
  lcd.print(char(223));
  lcd.print("C  ");

  
}




  //lcd.setCursor(0, 1);
  //lcd.print("Temp: ");
  //lcd.print(sensors.getTempFByIndex(0));
  //lcd.print(" F");


  lcd.setCursor(0, 2);
  lcd.print("  AQUECER");
  lcd.print(" - ");
  lcd.print("13 min");


  lcd.setCursor(0, 3);
  lcd.print("       L");
  lcd.print(" - ");
  lcd.print(percent);
  //lcd.print("%");


  ////////////////////////////////////////////////////////////////////////////////////////





  if (now.hour() >= 16 && now.hour() < 21 && estadoco2 == 0) {     // liga o CO2 após lampadas 01 hora e lampada

    digitalWrite (rele3, LOW); // liga CO2
    estadoco2 = 1;

  }


  if (now.hour() >= 15 && now.hour() < 22 && tubular == 0)   {   // liga as 02 lamapadas tubulares

    digitalWrite (rele1, LOW); // liga 02 tubular
    tubular = 1;

  }





  if (currentTime - previousTime >= eventInterval) {


    if (now.hour() >= 15 && now.hour() <= 21 && PWMvalue < 255 && fitaledtotal == 0) { // ADICIONAR NESSE IF SE luz = 0; VISTO QUE LUZ SÓ SERÁ = 1 DEPOIS QUE CHEGAR A 255

      //if (now.hour() >= 12 && now.hour() <= 22  && now.minute() >00 && now.minute() <=10 && luztemporaria == 0) { // ADICIONAR NESSE IF SE luz = 0; VISTO QUE LUZ SÓ SERÁ = 1 DEPOIS QUE CHEGAR A 255

      //if (now.hour() >= 12 && now.hour() <= 22  && now.minute() >00 && now.minute() >=00 && luztemporaria == 0) { // ADICIONAR NESSE IF SE luz = 0; VISTO QUE LUZ SÓ SERÁ = 1 DEPOIS QUE CHEGAR A 255



      if (PWMvalue <= 254) {
        PWMvalue++;
        analogWrite(ledwhite1, PWMvalue);
        analogWrite(ledwhite2, PWMvalue);


        BRIGHTNESS++;

        //pwmprev = PWMvalue - 1;
        previousTime = currentTime;

        if (PWMvalue >= 1)  {
          luz = 1;

          if (PWMvalue == 255)  {
            fitaledtotal = 1;


          }

        }



      }


    }





    if (now.hour() >= 22 && now.hour() <= 23 && luz == 1 && fitaledtotal == 1)   {



      if (PWMvalue <= 255) {
        PWMvalue--;


        BRIGHTNESS--;


        //pwmprev = PWMvalue - 1;
        previousTime = currentTime;

        if (PWMvalue == 0)  {
          luz = 0;
          fitaledtotal == 0;
        }

      }



    }




    if (now.hour() >= 00 && now.hour() <= 14 && luz == 1 && fitaledtotal == 1) {



      if (PWMvalue <= 255) {
        PWMvalue--;


        BRIGHTNESS--;


        //pwmprev = PWMvalue - 1;
        previousTime = currentTime;

        if (PWMvalue == 0)  {
          luz = 0;
          fitaledtotal == 0;
        }

      }



    }


    

  }  //  encerra IF maior com current



  if (now.hour() >= 21 && estadoco2 == 1)  {


    digitalWrite (rele3, HIGH); // desliga CO2
    estadoco2 = 0;

  }

  if (now.hour() >= 22 && tubular == 1) {


    digitalWrite (rele1, HIGH); // desliga 02 TUBULAR
    tubular = 0;

  }






  if (now.hour() >= 00 && now.hour() <= 11 && estadoco2 == 1)  {


    digitalWrite (rele3, HIGH); // desliga CO2
    estadoco2 = 0;

  }

  if (now.hour() >= 00 && now.hour() <= 11 && tubular == 1)  {


    digitalWrite (rele1, HIGH); // desliga 02 TUBULAR
    tubular = 0;

  }


  




  //delay(10);

  buttonState = digitalRead(buttonPin);

  if (buttonState == HIGH && luz == 0) {//Se estadoButton for igual a HIGH ou 1
    rampaacend = 1;

    delay(50);

    previousTime = currentTime;
    luztemporaria = 1;
    countbotao = countbotao + 1;

    eventIntervaladd = eventIntervaltwo * countbotao;
    timepressed = previousTime + 60000;

    minutoparadisplay = eventIntervaltwo / 60000;
    botaominute = countbotao * minutoparadisplay;

  }

  if (luzman == 255) {
    rampaacend = 0;
  }



  if (luzman <= 254 && rampaacend == 1) {

    luzman++;
    analogWrite(ledwhite1, luzman);
    analogWrite(ledwhite2, luzman);

  }

  percentman = (luzman * 100) / 255;




  if (currentTime - previousTime >= eventIntervaladd && luz == 0) {  //simplesmente desliga o ledwhite1 ao ultrapassar o tempo total

    digitalWrite(ledwhite1, LOW);
    digitalWrite(ledwhite2, LOW);
    luztemporaria = 0;
    countbotao = 0;
    eventIntervaladd = 0;
    timepressed = 0;
    contador = 1;
    luzman = 0;
    rampaacend = 0;

  }

  if (eventIntervaladd > (eventIntervaltwo * multplicmax) && luz == 0) { //desliga o ledwhite1 caso eu aperte o botão mais que "multplicmax" vezes

    digitalWrite(ledwhite1, LOW);
    digitalWrite(ledwhite2, LOW);
    luztemporaria = 0;
    countbotao = 0;
    eventIntervaladd = 0;
    timepressed = 0;
    contador = 1;
    botaominute = 0;
    luzman = 0;
    rampaacend = 0;

  }

  if (millis() > previousTime + (60000 * contador)) { //RESOLVIDO: if ja ta reduzindo a cada 1 minuto e reduzindo em 1 unidade

    if (botaominute >= 1) {
      botaominute--;
      contador = contador + 1;
    }

  }



  FastLED.setBrightness(BRIGHTNESS);
  FastLED.show();






  if ((sensors.getTempCByIndex(0) >= 30) || (sensors.getTempCByIndex(0) >= 30.00 && ventilador == 0)) {


    analogWrite (fan1, 255);
    analogWrite (fan2, 255);
    digitalWrite (rele4, LOW); // FAN 01 & FAN 02

    ventilador = 1;

    tone(buzzer, 5000); // Send 1KHz sound signal...
    delay(100);        // ...for 1 sec
    noTone(buzzer);     // Stop sound...
    delay(100);        // ...for 1sec


  }




  if ((sensors.getTempCByIndex(0) <= 28) || (sensors.getTempCByIndex(0) <= 28.00 && ventilador == 1)) {



    analogWrite (fan1, 0);
    analogWrite (fan2, 0);
    digitalWrite (rele4, HIGH); // FAN 01 & FAN 02

    ventilador = 0;


  }


}



int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);


}

In the same code at the end, I had the sending of data to Thingspeak with esp8266, I sent 01 to the site every minute, but because I had several Strings, I removed it for testing, it continues to crash.

The issue is that it crashes even with the loads and relays not activated when it is time for everything to be off and no true if.

I did the FreeRam (SRAM) function test and always with =+-6100 free.

The RTC sometimes behaves strangely, sometimes releasing a time of 43:05:20 or 165:165:85 (ATTACHED PHOTO), but within the same second the correct time comes.

One fine hour, everything stops. the routine of flashing the LED of pin 13 to accompany it alive is on. Seeu send the code again via USB, upload successfully and everything goes back to normal.

What could be happening?

I can safely say this does not do what you think it does and it is definitely a bug.

There's some trouble.

The behavior that you describe can be caused by reading or writing beyond the bounds of an array as in attempting to use memory that you do not "own". Examine all of the array operations to make sure that there are no bounds violations.

The excessive white space in the code makes it harder to read and follow. One blank line between sections or major parts is enough.

There may be a collision between Heap and Stack happening. But it's hard to get into where they are, mainly because I don't see a variable that could grow.

That is not a requirement for corrupting memory.

1 Like

If you defined an array
int myArray[60] // 60 elements from index 0 to 59

and you try to assign a value to
myArray[60] = 123;

you are already corrupting memory because you are storing data into RAM that was not reserved for this array. The RAM reserved for this array ends at index 59

best regards Stefan

RTC is definitely involved. Whether it's due to lack of memory for its operation, I don't know. I did a simple debig. The program always crashes at the same point, when it would update the clock parameters.

I need a code to test Heap memory, but it didn't compile here, only Freeram.

Whenever you want to share code or serial output

posting your actual complete sketch is very easy with this method

There is an automatic function for doing this in the Arduino-IDE
just three steps

  1. press Ctrl-T for autoformatting your code
  2. do a rightclick with the mouse and choose "copy for forum"
  3. paste clipboard into write-window of a posting

For posting serial output click into serial monitor
press Ctrl-A, Ctrl-C
change to forum click on insert code button </>
press Ctrl-V

downloading a picture for beeing able to zoom into the picture and not being able to search for keywords is uncomfortable

best regards Stefan

1 Like

array of ledsB ends at index 59

so ledsB[60] = CRGB::DeepSkyBlue; corrupts memory

array of ledsB ends at index 59
ledsB[61] = CRGB::White; corrupts memory

is the same as
ledsA[-61] = CRGB::Black;
ledsB[- 60] = CRGB::Black;

writing at index-position minus 61
writing at index-position minus 60
corrupts memory

SOLVED.

It's not the most optimized code in the world but I also know that I haven't made any gross mistakes when it comes to arrays or strings. There are no memory issues.
The problem was that I was sending a lot of data to the LCD thousands of times per second.
I read a little about I2C bus, without going too deep.

I was constantly updating the date, the clock seconds, temperature and also the percentage of my PWM.

I have conditioned when each variable will be sent. I conditioned the date to be sent only at 00:00:05 or 00:00:15 or when the program starts, since it is recorded in the RTC.
I also gave up the seconds, now only the minutes are sent, also updating only 1x every minute.
Also only update my PWM if it changes and put it inside the function.

So that was it, LCD data was obstructing communication at the end of the previous loop, and when rtc.now() was called at the beginning of the loop, the data range for LCD had already corrupted the communication with too much data at the end of the loop previous.

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