Arduino Mega doesn't reload program after power off

Adriuno mega is unable to reload the program after being turned off... In my project i am using dot matrix display along with 7 segment displays to display various times...Everything runs perfectly well without dot matrix... when i call dot matrix function it runs well only up-to power supply is on.. Once power supply is turned off , My code is unable to reload unless i open serial monitor or press the reset button... What is the solution for this?
Below is the code im using for running dot matrix.... THe remaining prtion of code is too big ...Problem of reloading arises only when i add this dot matrix code

// Including the required Arduino libraries
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include "JF_Font_Data.h"
#include <SPI.h>
#include <Wire.h>
#include <ErriezDS3231.h>

ErriezDS3231 rtc;//date time
//#define DATE_STRING_SHORT           3
//// Month names in flash
//const char monthNames_P[] PROGMEM = "JanFebMarAprMayJunJulAugSepOctNovDec";
//// Day of the week names in flash
//const char dayNames_P[] PROGMEM= "SunMonTueWedThuFriSat";
//char name[DATE_STRING_SHORT + 1];
    uint8_t hour;
    uint8_t min;
    uint8_t sec;
    uint8_t mday;
    uint8_t mon;
    uint16_t year;
    uint8_t wday;
// Uncomment according to your hardware type
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
//#define HARDWARE_TYPE MD_MAX72XX::GENERIC_HW

// Defining size, and output pins
#define MAX_DEVICES 8
#define CS_PIN 53
#define DIN_PIN 51
#define CLK_PIN 52 

int HijYear, HijMonth, HijDay;

// Create a new instance of the MD_Parola class with hardware SPI connection
MD_Parola myDisplay = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
#define SPEED_TIME 200 // speed of the transition
#define PAUSE_TIME  0 

#define MAX_MESG  20

// Global variables
char szMnt[10];    // mm:ss\0
char szMesg[MAX_MESG+1] = "";
char szFrac[MAX_MESG+1] = "";
char szNext[MAX_MESG+1] = "";
String Hijri_Month;
String Eng_Month;
uint8_t degC[] = { 6, 3, 3, 56, 68, 68, 68 }; // Deg C
//uint8_t degF[] = { 6, 3, 3, 124, 20, 20, 4 }; // Deg F

void getNxtPrayer(char *psz)
  {
    const char *strFjr = "Fajir";
    
    strcpy(psz, strFjr);
  }
String getEngMonthName(long int mnth)
    {
     switch (mnth)
     {
      case 1:
       return "January";
      case 2:
       return "February";
      case 3:
       return "March";
      case 4:
       return "April";
      case 5:
       return "May";
      case 6:
       return "June";
      case 7:
       return "July";
      case 8:
       return "August";
      case 9:
       return "Sptmbr";
      case 10:
       return "October";
      case 11:
       return "November";
      case 12:
       return "December";
     }
     return "";
    } 
void getEngMonth(char *psz, long int eng_mon)

{
 String En_Mon;
 

  En_Mon  = getEngMonthName(eng_mon);
  const char *strHM = En_Mon.c_str(); 
  strcpy(szMesg, strHM);
}

// Code for English to Hijri conversion


long int LastDayOfGregorianMonth(long int mon, long int year) {
    // Compute the last date of the month for the Gregorian calendar.
    
      switch (mon) {
      case 2:
        if ((((year % 4) == 0) && ((year % 100) != 0))
            || ((year % 400) == 0))
          return 29;
        else
          return 28;
      case 4:
      case 6:
      case 9:
      case 11: return 30;
      default: return 31;
      }
    }
    
long int calcAbsGregorianDays(long int d, long int m, long int y) {
     long int N = d;
     for (long int i = m - 1; i > 0; i--)
      N += LastDayOfGregorianMonth(i, y);
    
     return N + (y - 1) * 365
        + (y - 1) / 4
        - (y - 1) / 100
        + (y - 1) / 400;
    }
    
    bool IsIslamicLeapYear(long int year) {
    // True if year is an Islamic leap year
      
      if ((((11 * year) + 14) % 30) < 11)
        return true;
      else
        return false;
    }
    
long int LastDayOfIslamicMonth(long int mon, long int year) {
    // Last day in month during year on the Islamic calendar.
    
      if (((mon % 2) == 1) || ((mon == 12) && IsIslamicLeapYear(year)))
        return 30;
      else
        return 29;
    }
    
    const float IslamicEpoch = 227014; // Absolute date of start of Islamic calendar
    
    long int IslamicDate(long int mon, long int day, long int year) {
     return (day                      // days so far this month
                + 29 * (mon - 1)       // days so far...
                + mon/2                //            ...this year
                + 354 * (year - 1)       // non-leap days in prior years
                + (3 + (11 * year)) / 30 // leap days in prior years
                + IslamicEpoch);                // days before start of calendar
    }
    
    String getMonthName(long int mnt)
    {
     switch (mnt)
     {
      case 1:
       return "Muharram";
      case 2:
       return "Safar";
      case 3:
       return "Rabi-Ul-Awwal";
      case 4:
       return "Rabi-Us-Sani";
      case 5:
       return "Jamadi-Ul-Awl";
      case 6:
       return "Jamadi-Us-Sani";
      case 7:
       return "Rajab";
      case 8:
       return "Shaban";
      case 9:
       return "Ramadan";
      case 10:
       return "Shawal";
      case 11:
       return "Zil-Qadah";
      case 12:
       return "Zul-Hijah";
     }
     return "";
}


 String Goergian2hijri(char* psz, long int d, long int m, long int y)
 {
 d = calcAbsGregorianDays(d, m, y);
 
 long  int mon, day, year;
 String mnth;

 // Search forward year by year from approximate year
 year = (d - IslamicEpoch) / 355;
 
 while (d >= IslamicDate(1, 1, year))
  year++;
 
 year--;
 // Search forward month by month from Muharram
 mon = 1;
 while (d > IslamicDate(mon, LastDayOfIslamicMonth(mon, year), year))
  mon++;
 
 day = d - IslamicDate(mon, 1, year) + 1;  
  HijYear = year;
  HijMonth = mon;
  HijDay = day;
 mnth = getMonthName(mon);
 const char *strHM = mnth.c_str(); 
 strcpy(szMesg, strHM);
 return mnth;
 //system("pause");
}

//end of conversion


void setup() {
//  clock.begin();
  // Initialize I2C
    Wire.begin();
    Wire.setClock(100000);

    // Initialize RTC
    while (!rtc.begin()) {
        Serial.println(F("RTC not found"));
        delay(3000);
    }

    // Set date/time: 12:34:56 31 December 2020 Sunday
    if (!rtc.setDateTime(10, 39, 56,  8, 9, 2022, 4)) {
        Serial.println(F("Set date/time failed"));
        return;
    }


  // Intialize the object
  myDisplay.begin(2);
  myDisplay.setInvert(false);
  // Set the intensity (brightness) of the display (0-15)
  myDisplay.setIntensity(15);
  // Clear the display
  //myDisplay.displayClear();
  myDisplay.setInvert(false); //we don't want to invert anything so it is set to false
  Wire.begin();
  
  //myDisplay.setZone(0,  MAX_DEVICES-4, MAX_DEVICES-1);
  myDisplay.setZone(0,  0, 3);
  
  //myDisplay.setZone(1, MAX_DEVICES-4, MAX_DEVICES-1);
  myDisplay.setZone(1,  4, 7);
  myDisplay.setFont(0, jF_Custom);
  myDisplay.setFont(1, jF_Custom);
  myDisplay.displayZoneText(1, szNext, PA_LEFT, SPEED_TIME, PAUSE_TIME, PA_PRINT, PA_NO_EFFECT);

  myDisplay.displayZoneText(0, szMesg, PA_CENTER, SPEED_TIME, 0, PA_PRINT , PA_NO_EFFECT);
  myDisplay.addChar('$', degC);
   //strcpy(szFrac, "Meqat");
   //sprintf(szFrac,"Meqat");
  
  //myDisplay.addChar('&', degF);
  
  
}

void loop() {
   !rtc.getDateTime(&hour, &min, &sec, &mday, &mon, &year, &wday);
   static uint8_t  display = 0;  // current display mode
   // dt = clock.getDateTime();
    long int m = mon;
    long int y = year;
    long int d = mday;
    long int h = hour;
    long int min = min;
    long int s = sec;

    int8_t temperature = 0;
    uint8_t fraction = 0;
    
    if (!rtc.getTemperature(&temperature, &fraction)) {
        Serial.println(F("Temp read failed"));
        return;
    }
   myDisplay.displayAnimate();


//   Hijri_Month =  Goergian2hijri( szMesg, d,  m ,  y);
//   Eng_Month = getEngMonthName(m);
//
//  
//   Serial.println(Hijri_Month);
//   Serial.print(HijDay );   Serial.print( " / ");  Serial.print (HijMonth);  Serial.print( " / ");  Serial.print(HijYear );
//   Serial.println(" ");
//   Serial.println(Eng_Month);
//   Serial.println(" ");

   if (myDisplay.getZoneStatus(0))
  {
    switch (display)
    { 

      case 0: /// Next Prayer
        myDisplay.setPause(0,5000);
        myDisplay.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT);
        getNxtPrayer(szNext);
        //strcpy(szNext, "As Salah Meeqat");
        delay(2000);
        display ++;
        break;
      case 1: // Temperature
        //clock.forceConversion();
        myDisplay.setPause(0,5000);
        myDisplay.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_UP);
        //myDisplay.setTextEffect(0, PA_MESH, PA_BLINDS);
        delay(2000);
        
        display ++;    
        dtostrf(temperature, 2,0, szMesg);
        strcat(szMesg , ".");
        dtostrf(fraction, 1,0, szFrac);
        strcat(szMesg, szFrac);
        strcat(szMesg, "$");  
        break;

     case 2: // English Month
        myDisplay.setTextEffect(0, PA_PRINT, PA_NO_EFFECT);
        myDisplay.setPause(0, 0);
        delay(2000);
        display++;
        getEngMonth(szMnt, m);
        myDisplay.setTextEffect(0, PA_PRINT, PA_WIPE_CURSOR);
        break;
        
        myDisplay.setTextEffect(0, PA_PRINT, PA_WIPE_CURSOR);
        break;  
       
      case 3: // Hijri Month
       
        myDisplay.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT);
         myDisplay.setPause(0,0);
        delay(2000);
        display ++ ;
        Hijri_Month =  Goergian2hijri(szMesg, d,  m ,  y);
        break;  
       case 4: 
        //myDisplay.setPause(1,5000);
        myDisplay.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT);
        strcpy(szMesg, "Masjid Ahl E Hadees");
         myDisplay.setPause(0, 5000);
        delay(2000);
        display ++;
        break;
      default: 
        myDisplay.setPause(0,5000);
        myDisplay.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT);
        strcpy(szMesg, "As Salah Meeqat");
        delay(2000);
        display = 0;
        break;
    }    
   myDisplay.displayReset(0); 
   myDisplay.displayReset(1); 
  }

}

Please show the code

Welcome to the forum

Please post your full code , using code tags when you do, and a schematic of your project. A picture of a hand drawn schematic is good enough

i have added the code snippet of dot matrix which causes the problem

As I said

sorry full code cant be posted... as i said problem arises when i upload this code portion to my project... it also runs well till i turn off power supply

Then forum members can only take a guess at what the cause might be.

On Mega, the program is stored in flash memory, which does not lose its contents until overwritten with a new program. The program is not loaded into RAM memory before it is executed, it is run directly from the flash memory. So your idea that the program is not being reloaded cannot be correct and there must be another explanation for what you see happening (or not happening :wink: ).

Your program is in fact running, but it is sometimes getting stuck during the execution of setup() or maybe during the first execution of loop(). This seems to be happening only on power-up but not after reset, which may indicate something is executed in setup() or loop() which is behaving differently in these two situations, and that could be because of a different signal received by the Mega from some part of the circuit.

As a test, try putting delay(5000) as the first line in setup().

Then an adequate answer probably can not be given.

already tried delay in setup... still not working... the problem is the code gets reloaded sometimes but otherwise it only works upon reset or turning on serial monitor

brother try to understand... the code is more than 15000 lines long.... which is running smoothly if i dont add the dot matrix portion... once i add the above snippet, if works fine only until power supply is on... if i turn off the device, it may or may not reload

Find the root cause.

This sounds like a power / timing problem; it takes too long for your power supply to give a stable voltage; so a number of connected devices might not work yet . Opening serial monitor resets the Mega (so effectively the same as pressing the reset button) and by that time the power supply is stable.

What is the power supply (voltage / amps)? Do you switch the power supply on or do you plug the power supply into the suitable connection of the Mega?

How many 7-segment displays?

Because you're blind without the serial monitor, I suggest that you blink a led once per second.

In other critical places, blink twice, three times etc per second so you know where your code is / goes.

1 Like

im using 73 7-segments in total and two 4 in 1 / 8x8 LED Dot Matrix. i am using a stable power supply which generates different voltage/ currents for different color/size 7 segments as per their requirement... For Arduino mega i m using 11.5 v/ 40 mA constant current... problem is with dot matrix code above because when i run it individually , even then the program is not reloaded after turning off power

adding full code wont help because if i run the above code alone ,, even then it doesnot reload after ardiuno mega being turnred off.

How much current does the Mega use ?
Surely it is more than 40mA ?

2 Likes

Ok circuit diagram then - there may be an issue here with power supplied to from the mega .
Otherwise you need to do some classic debugging , using print , cutting bits out etc to find where the issue actually lies and what that issue is .( size of any array , addressing outside of array size , nested loops that don’t return properly etc etc )
Try writing and running a simple sketch that just includes the problem area , run that - something you can post up .

-I’m sure you can see the issue with trying to give advice here if the sketch can’t be seen .

To say the truth i couldnt find the actual current requirement for ardiuno... i found some information from here: https://store.arduino.cc/products/arduino-mega-2560-rev3 but somehow i feel its inappropriate ... i tried to increase the current to 113mA still the problem is thre.. Above that im afraid of damaging my ardiuno board and connected devices... if you knw the current requirement please let me know

i have written down the code above.. you can check it and point out the actual problem...

Do you have a constant current source or a voltage source?

An Arduino draws what it needs; if you don't give it enough, it will not work un unreliably. You will not damage an Arduino by supply 11.5 and 100A. As long as you don't try to pull that 100A out of the 5V pin as that will blow it to pieces.

If you use USB, you have 500 mA available.

Do you power anything from the 5V pin of the Mega?

“ i have written down the code above.. you can check it and point out the actual problem...”

You need a full small sketch that shows the issue , in case that issue is elsewhere - snippets on their own are no use.
( imagine you set up an array early on , then address a cell outside of its range later on - that would be an issue , but we would not see it )

I don't think it's a snippet.

@rayeeslone, please provide links to all libraries that you use (this includes JF_Font_Data.h).