Unreliable millis timer

Hello, I'm working on a project which plays a certain mp3 file at a certain time for a certain time length in which the user may select some menu items for volume control and exit while playing.

I apologize for not sharing the code as it's more than 5000 lines and will take too much of your precious time.

To cut a long story short, I use the typical millis routine to stop a playing (typically 3 minutes) file according to its length and it gives me different results on each use. e.g. exits before (interval) time

The old millis routine works fine in many other projects when used to trigger something on a certain interval.

So I was wondering if there is another timer routine that is reliable.

Thank you in advance.

p.s. I'm using mega 2560 with all its interrupts for a keypad.

Definitely no interest in seeing that. But you could post an MRE. That's the smallest possible complete code that compiles and demonstrates the problem. Leave out anything unrelated as it's just clutter.

We need much more information.

Show us a scaled down version that still exhibits the same problem.

Which hardware are the files played on? Could it be that it sends a signal you could intercept when the file has finished? Considered using a RTC instead of millis()?

EDIT: Ooops...

Also, how is the MP3 being played?

//This is an islamic prayer player based on Arduino Mega
//1. Calculate prayer times according to time-zone & location
//2. Activate amplifire
//3. play call for prayer at appropiate time
//4. shut-off amplifire
#include <time.h>
#include "Wire.h"
#include <EEPROM.h>
#include <LiquidCrystalTr_I2C.h>
#include <math.h>
#include <string.h>
using namespace std;
#include "RTClib.h"
LiquidCrystal_I2C lcd(0x27,20,4);
#define DS1307_I2C_ADDRESS 0x68  // This is the I2C address
//#include <DS3232RTC.sh>
#include "DFRobotDFPlayerMini.h"
//button vars

byte lockTR[] = {B00100,B01010,B01010,B11111,B10001,B10101,B10001,B11111}; //lock sign
byte sTR[] = {B00000,B01110,B10000,B01110,B00001,B01110,B00000,B00100};

const int commonPin = 2;
const int buttonPins[] = {4,6,3,5}; 
const int amfipin = 7;
const int role1pin = 8; //minare lamps
const int role2pin = 9; //internal lamps
const int LCDPin = 10;
const int beeppin = 11;
unsigned long lastFire = 0;
int activekey = 0;
boolean bitti, bitti1, ezantrap;
int newhour=0;
int newminute=0;

int hareket = 0;
bool guvence=false;
int sayacim=0;
float tempo;
RTC_DS3231 rtc;
boolean tick = false;
boolean manual = false;
boolean ekran = true;
boolean interlace = true;
unsigned long previousMillis = 0;        // update time
unsigned long previousMillis1 = 0;        // conversion
unsigned long previousMillis3 = 0;        // ezan
unsigned long pselamillis = 0;        // for SELA
unsigned long pezanmillis = 0;        // for EZAN
unsigned long previousswap = 0;        // mainb loop screen swap
unsigned long interval = 10000;// 10 seconds
unsigned long interval1 = 21600000; //conversion 6 hrs
unsigned long interval2 = 0;//ezan delay 346 seconds
unsigned long selainterval = 296000;
unsigned long intervalswap = 7000;//screen flip
//unsigned long currentMillis3;
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
int newhours, newminutes;
//old ezan vars.
byte sabahhour,sabahminute,fajrhour,fajrminute,guneshour, gunesminute, oglehour,ogleminute,ikindihour,ikindiminute,aksamhour,aksamminute,yatsihour,yatsiminute;
byte sabahezanhour, sabahezanminute,oglehourSela,ogleminuteSela,timezone;
int il = 0;
byte selaokunsun; // Cuma günü sela okunsun
byte ilkodu, persembeselaokunsun,cumavakitsabitle,cumavakitzamansaat,cumavakitzamandakika,ezantercihi,amfigecikme,sabahezangecikme,ezansuresi,cumaseladakika,persembeseladakika,persembeselahour,persembeselaminute;
byte gunestemkinsaat,gunestemkindakika,sabahtemkinsaat,sabahtemkindakika,ogletemkinsaat,ogletemkindakika,ikinditemkinsaat,ikinditemkindakika,aksamtemkinsaat,aksamtemkindakika,yatsitemkinsaat,yatsitemkindakika,ramazanayi;
byte role1startsaat,role1startdakika,role1stopsaat,role1stopdakika,role2startsaat,role2startdakika,role2stopsaat,role2stopdakika;
byte role1=0, role2=0, role3=0,lcdgecis=7;
byte parolavarmi=0;byte parolanedir=0;
byte sabahdiff, sabahmajmo, gunesdiff, gunesmajmo, oglediff, oglemajmo, ikindidiff, ikindimajmo, aksamdiff, aksammajmo, yatsidiff, yatsimajmo;
int calculatedsabah = 0, calculatedgunes=0,calculatedogle=0,calculatedikindi=0,calculatedaksam=0,calculatedyatsi=0;
// new ezan vars.
double dhuhr_minutes;
const int NUM_ITERATIONS = 1;   // number of iterations needed to compute times
double julian_date;
double latitude;  
double longitude;   
double Time_Zone = 3;
char ch;
static const char* TimeName[] = {"Fajr","Sunrise","Dhuhr","Asr","Sunset","Maghrib","Isha"};
enum JuristicMethod {Shafi, Hanafi};
enum TimeID{Fajr, Sunrise, Dhuhr, Asr, Sunset, Maghrib, Isha, TimesCount};
enum CalculationMethod{
  MWL,      // Muslim World League (MWL)
  Karachi,  // University of Islamic Sciences, Karachi
  ISNA,     // Islamic Society of North America (ISNA)
  Makkah,   // Umm al-Qura, Makkah
  Egypt,    // Egyptian General Authority of Survey
  Jafari,   // Jafari
  Tehran,   // Tehran
  CalculationMethodsCount
};
enum AdjustingMethod{     // Adjusting Methods for Higher Latitudes
  None,       // No adjustment
  MidNight,   // middle of night
  OneSeventh, // 1/7th of night
  AngleBased, // angle/60th of night
};
struct MethodConfig{
  double fajr_angle;
  bool   maghrib_is_minutes;
  double maghrib_value;   // angle or minutes
  bool   isha_is_minutes;
  double isha_value;    // angle or minutes
 MethodConfig(){
    fajr_angle = 18.0;
    maghrib_is_minutes = true;
    maghrib_value = 0.0;    // angle or minutes
    isha_is_minutes = false;
    isha_value = 18.0;    // angle or minutes
  }
 MethodConfig(double fajr_angle,
        bool maghrib_is_minutes,
        double maghrib_value,
        bool isha_is_minutes,
        double isha_value)
    : fajr_angle(fajr_angle)
    , maghrib_is_minutes(maghrib_is_minutes)
    , maghrib_value(maghrib_value)
    , isha_is_minutes(isha_is_minutes)
    , isha_value(isha_value)
    {
    }
};
  
MethodConfig method_params[CalculationMethodsCount];
unsigned int calc_method ;
unsigned int asr_juristic;
AdjustingMethod adjust_high_lats;
String two_digits_format(int num);
static String int_to_string(int num);
static double fix_hour(double a);
static void get_float_time_parts(double time, int& hours, int& minutes);
String float_time_to_time24(double Time);
String float_time_to_time12(double Time, bool no_suffix = false);
double deg2rad(double d);
double rad2deg(double r);
static double dsin(double d);
static double dcos(double d);
static double dtan(double d);
static double darcsin(double x);
static double darccos(double x);
static double darctan(double x);
static double darctan2(double y, double x);
static double darccot(double x);
static double fix_angle(double a);
static double time_diff(double time1, double time2);
void sun_position(double jd, double &D, double &Eq_t);
double equation_of_time(double jd);
double sun_declination(double jd);
double compute_mid_day(double _t);
double compute_time(double g, double t);
void day_portion(double times[]);
double compute_asr(int Step, double t);
void compute_times(double times[]);
double night_portion(double angle);
void adjust_high_lat_times(double times[]);
void adjust_times(double times[]);
void compute_day_times(double times[]);
double get_julian_date(int Year, int Month, int Day);  
void get_prayer_times(int Year, int Month, int Day, double _latitude, double _longitude, double _timezo, double times[]);
void get_prayer_times(time_t date, double latitude, double longitude, double Tzone, double times[]);
int fdvolume=20, fdeq=3; 
byte ezanfile;
byte imam = 0;
String hadise ="";
int zero = 0;
int hours, minutes;
int kalansaat; //byte
int kalandakika; //byte
double fajr, gunes, ogle, ikindi, aksam, yatsi;
char weynstring[54]; //global string
//mp3
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);
// end of mp3

byte decToBcd(byte val)
{
                              return ( (val / 10 * 16) + (val % 10) );
}

// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
                              return ( (val / 16 * 10) + (val % 16) );
}

// Gets the date and time from the ds1307 and prints result
void getDateDs1307()
{
                            Wire.beginTransmission(DS1307_I2C_ADDRESS);
                            Wire.write(zero);
                            Wire.endTransmission();
                            Wire.requestFrom(DS1307_I2C_ADDRESS, 7);
                            second     = bcdToDec(Wire.read() & 0x7f);
                            minute     = bcdToDec(Wire.read());
                            hour       = bcdToDec(Wire.read() & 0x3f);
                            dayOfWeek  = bcdToDec(Wire.read());
                            dayOfMonth = bcdToDec(Wire.read());
                            month      = bcdToDec(Wire.read());
                            year       = bcdToDec(Wire.read());
}

void setDateDs1307() //set date (removed)
{
                            
}

void printTime()
{
                            char s[12];
                            lcd.setCursor(6, 0);
                            lcd.print("        ");
                            lcd.setCursor(6, 0);
                            lcd.print(char(dayOfMonth / 10 + 0x30));
                            lcd.print(char(dayOfMonth % 10 + 0x30));
                            lcd.print("/");
                            lcd.print(char(month / 10 + 0x30));
                            lcd.print(char(month % 10 + 0x30));
                            lcd.print("/");
                            lcd.print(char(year / 10 + 0x30));
                            lcd.print(char(year % 10 + 0x30));
                            lcd.setCursor(15, 0);
                            lcd.print("     ");
                            lcd.setCursor(15, 0);  
                            lcd.print( char( hour / 10 + 0x30) );
                            lcd.print( char( hour % 10 + 0x30) );
                            lcd.print(":");
                            lcd.print( char(minute / 10 + 0x30));
                            lcd.print( char(minute % 10 + 0x30));
                            //lcd.print(":");
                            //lcd.print(char (second / 10 + 0x30));
                            //lcd.print(char (second % 10 + 0x30));
}                            

void setup()  {
  adjust_high_lats = None;
  dhuhr_minutes = 0;
  Time_Zone  = 3;     
  //latitude  = 38.41885;
  //longitude = 27.12872;   

                      pinMode(amfipin, OUTPUT);
                      pinMode(role1pin, OUTPUT);
                      pinMode(role2pin, OUTPUT);
                      pinMode(LCDPin, OUTPUT);
                      digitalWrite(amfipin, HIGH);//amfi is OFF
                      digitalWrite(role1pin, HIGH);//lights 1
                      digitalWrite(role2pin, HIGH);//lights 2
                      Wire.begin();
                      Serial.begin(9600); //console
                      Serial1.begin(9600); //df player
if (lcdgecis < 3) {intervalswap=3;}
else if (lcdgecis > 20) {intervalswap=20;}
else intervalswap = lcdgecis*1000;
                      configureCommon(); // Setup pins for interrupt keys
                      attachInterrupt(digitalPinToInterrupt(commonPin), pressInterrupt, FALLING);
                          if (! rtc.begin()) {
                          Serial.println("Couldn't find RTC");
                          Serial.flush();
                          while (1) delay(10);
                        }
                                              lcd.begin();
                                              lcd.backlight();
                                              lcd.clear();
                                              lcd.setCursor(0, 0);
                                              lcd.print("*******************");
                                              lcd.setCursor(0, 3);
                                              lcd.print("*******************");
                                              delay(2000);
                                              lcd.setCursor(0, 2);
                                              lcd.print("1..");
                                              if (!myDFPlayer.begin(Serial1)) {Serial.println(F("Unable to begin DF"));while(true);}
                                            Serial.println(F("DFPlayer Mini online."));
                                            myDFPlayer.setTimeOut(500); //Set serial communictaion time out 500ms
                                            myDFPlayer.volume(fdvolume);
                                                  if (fdeq==1) {myDFPlayer.EQ(DFPLAYER_EQ_NORMAL);}
                                                  if (fdeq==2) {myDFPlayer.EQ(DFPLAYER_EQ_POP);}
                                                  if (fdeq==3) {myDFPlayer.EQ(DFPLAYER_EQ_ROCK);}
                                                  if (fdeq==4) {myDFPlayer.EQ(DFPLAYER_EQ_JAZZ);}
                                                  if (fdeq==5) {myDFPlayer.EQ(DFPLAYER_EQ_CLASSIC);}
                                                  if (fdeq==6) {myDFPlayer.EQ(DFPLAYER_EQ_BASS);}
                                            myDFPlayer.outputDevice(DFPLAYER_DEVICE_SD);
                                            myDFPlayer.disableLoop(); //disable loop.
                                            myDFPlayer.enableDAC();  //Enable On-chip DAC
                                            delay(1000);
                                            myDFPlayer.playFolder(8, 4);//welcome tone
                                              roledevrede(); //relay control
                                              delay(1000);
                                              roledevredisi(); //all relays off
                                              getDateDs1307(); //get time/date
                                              loadtape(); //load default values from eeprom
                                              lcd.clear();
                                              calculatetimes(); //1'st run

myDFPlayer.pause();
delay(1000);
beep();beep();beep();
}
void loadtape()
{
                      for(int bisse=1; bisse<54; bisse++) 
                          {
                                weynstring[bisse]=EEPROM.read(bisse);
                          }      
                                ilkodu = weynstring[1];Serial.print("ilkodu        :");Serial.println(ilkodu);
                                selaokunsun=weynstring[2];Serial.print("Sela okunsun  :");Serial.println(selaokunsun);
                                persembeselaokunsun=weynstring[3];Serial.print("Persembe sela :");Serial.println(persembeselaokunsun);
                                cumavakitsabitle = weynstring[4];Serial.print("Cuma Sabit    :");Serial.println(cumavakitsabitle);
                                cumavakitzamansaat = weynstring[5];Serial.print("Cuma sabitle  :");Serial.println(cumavakitzamansaat);
                                cumavakitzamandakika = weynstring[6];Serial.print("Cuma sabit vkt:");Serial.println(cumavakitzamandakika);
                                imam=weynstring[17];Serial.print("imam  :");Serial.println(imam);
                                amfigecikme=weynstring[18];Serial.print("Amfi Gecikme  :");Serial.println(amfigecikme);
                                sabahezangecikme=weynstring[19];Serial.print("Sabah Gecikme :");Serial.println(sabahezangecikme);
                                //gunestemkinsaat=weynstring[20];Serial.print("gns tmkn ort  :");Serial.println(gunestemkinsaat);
                                //gunestemkindakika=weynstring[21];Serial.print("gns tmkn dak  :");Serial.println(gunestemkindakika);
                                fdvolume=weynstring[22];Serial.print("Volume        :");Serial.println(fdvolume);
                                fdeq=weynstring[23];Serial.print("Fdeq          :");Serial.println(fdeq);
                                ramazanayi=weynstring[24];Serial.print("Ramazan ayi   :");Serial.println(ramazanayi);
                                timezone=weynstring[25]; Time_Zone=timezone;Serial.print("Time zone     :");Serial.println(timezone);
                                parolavarmi=weynstring[26];Serial.print("Parola varmi  :");Serial.println(parolavarmi);
                                cumaseladakika=weynstring[28];Serial.print("Cuma Sela dak :");Serial.println(cumaseladakika);
                                persembeseladakika=weynstring[29];Serial.print("Persembe sela :");Serial.println(persembeseladakika);
                                role1=weynstring[30];Serial.print("Role 1        :");Serial.println(role1);
                                role2=weynstring[31];Serial.print("Role 2        :");Serial.println(role2);
                                role1startsaat=weynstring[33];Serial.print("Role 1 start/saat  :");Serial.println(role1startsaat);
                                role1startdakika=weynstring[34];Serial.print("Role 1 start/dak   :");Serial.println(role1startdakika);
                                role1stopsaat=weynstring[35];Serial.print("Role 1 stop/saat  :");Serial.println(role1stopsaat);
                                role1stopdakika=weynstring[36];Serial.print("Role 1 stop/dak   :");Serial.println(role1stopdakika);                                
                                role2startsaat=weynstring[37];Serial.print("Role 2 start/saat  :");Serial.println(role2startsaat);
                                role2startdakika=weynstring[38];Serial.print("Role 2 start/dak   :");Serial.println(role2startdakika);
                                role2stopsaat=weynstring[39];Serial.print("Role 2 stop/saat  :");Serial.println(role2stopsaat);
                                role2stopdakika=weynstring[40];Serial.print("Role 2 stop/dak   :");Serial.println(role2stopdakika);                                
                                lcdgecis=weynstring[41];Serial.print("LCD gecis hizi    :");Serial.println(lcdgecis);                                
 sabahdiff = weynstring[42];
 sabahmajmo = weynstring[43];
 gunesdiff = weynstring[44];
 gunesmajmo = weynstring[45];
 oglediff = weynstring[46];
 oglemajmo = weynstring[47];
 ikindidiff = weynstring[48];
 ikindimajmo = weynstring[49];
 aksamdiff = weynstring[50];
 aksammajmo = weynstring[51];
 yatsidiff = weynstring[52];
 yatsimajmo = weynstring[53];

 }                              
 
void savetape() //save defaults when setup is complete
{
                          for(int bisse=1; bisse<54; bisse++) 
                              {
                                  EEPROM.write(bisse, weynstring[bisse]);
                                  Serial.print("\t");
                                  Serial.print(weynstring[bisse], DEC);
                                  Serial.println();
                              } 
}

void erasetape() // load defaults on request
{
                          for(int bisse=1; bisse<54; bisse++) 
                              {
                                    EEPROM.write(bisse, 0);
                              }     EEPROM.write(1, 35);
                                    EEPROM.write(2, 0);
                                    EEPROM.write(3, 0);
                                    EEPROM.write(4, 0);
                                    EEPROM.write(5, 0);
                                    EEPROM.write(6, 0);
                                    EEPROM.write(17, 3);
                                    EEPROM.write(18, 3);
                                    EEPROM.write(19, 55);
                                    EEPROM.write(22, 10);
                                    EEPROM.write(23, 0);
                                    EEPROM.write(24, 0);
                                    EEPROM.write(25, 3);
                                    EEPROM.write(26, 0);
                                    EEPROM.write(27, 0);
                                    EEPROM.write(28, 0);
                                    EEPROM.write(29, 0);
                                    EEPROM.write(30, 0);
                                    EEPROM.write(31, 0);
                                    EEPROM.write(33, 0);
                                    EEPROM.write(34, 0);
                                    EEPROM.write(35, 0);
                                    EEPROM.write(36, 0);
                                    EEPROM.write(37, 0);
                                    EEPROM.write(38, 0);
                                    EEPROM.write(39, 0);
                                    EEPROM.write(40, 0);
                                    EEPROM.write(41, 7);
Serial.print("eeprom erased...");
}
void loop() 
{
                        unsigned long currentswap = millis();  //screen swapper
                        if (currentswap - previousswap > intervalswap) 
                        {
                                    previousswap = currentswap;
                                    if (ekran==true) {ekran=false;} 
                                    else {ekran=true;}
                              if (ekran==true) 
                                {
                                      if (manual == false) {ticker1();}
                                      else {ticker1a();}

                        unsigned long currentMillis = millis();  //set to 10 sec. THIS IS THE REAL DEAL
                        if (currentMillis - previousMillis > interval) 
                        {
                              previousMillis = currentMillis;
                              getDateDs1307();
                              printTime();
                              calculatetimes();
                              kalansure(); //calculate and display time left for next prayer time
                              ezanperiod(); //calculate mp3 files period
                              isitezantime(); //check if time has come to announce call for prayer
                        }                                  
                                }
                              else {fujitsu2();}
                        }

if (manual == false)
                 {
                                                            if (activekey == 1)
                                                                  {
                                                                    manual = true;
                                                                    beep();
                                                                    activekey=0;
                                                                  }
                                                            if (activekey == 2)
                                                                  {
                                                                    beep();
                                                                    guven();
                                                                    activekey=0;
                                                                  }
                                                            if (activekey == 3) //free
                                                                  {

                                                                    beep();
                                                                    activekey=0;
                                                                  }
                                                            if (activekey == 4)
                                                                  {
                                                                   // setdateabi();
                                                                    beep();
                                                                    activekey=0;
                                                                  }                    
      }
if ((manual == true) && (guvence==false))
                                  {
                                                            ticker1a();
                                                            if (activekey == 1)
                                                                  {
                                                                    //roledevrede();
                                                                    beep();
                                                                    manual = false;
                                                                    ticker1();
                                                                    activekey=0;
                                                                  }
                                                            if (activekey == 2)
                                                                  {
                                                                    beep();
                                                                    selamiezan();
                                                                    activekey=0;
                                                                  }
                                                            if (activekey == 3)
                                                                  {
                                                                    beep();
                                                                    rolekurulum();
                                                                    activekey=0;
                                                                  }
                                                            if (activekey == 4)
                                                                  {
                                                                    beep();
                                                                    setkurulum();
                                                                    activekey=0;
                                                                  }                                                                                                                        
                                }

while (guvence==true) //if keypad locked continue duty
           {             
                        // key logo on top
                        unsigned long currentMillis = millis();  //set to 10 sec.
                        if (currentMillis - previousMillis > interval) 
                        {
                              previousMillis = currentMillis;
                              getDateDs1307();
                              printTime();
                              kalansure();
                              if (tick==true) {tickermain();} else {ticker1();}
                        
                        }
                        unsigned long currentMillis1 = millis();  //set to 6 Hrs.
                        if (currentMillis1 - previousMillis1 > interval1) 
                        {
                              previousMillis1 = currentMillis1;
                              calculatetimes();
                        }

                                                            if (activekey == 1)
                                                                  {
                                                                   
                                                                   sayacim=sayacim+1;
                                                                   activekey=0;
                                                                  }
                                                            if (activekey == 2)
                                                                  {
                                                                   
                                                                   sayacim=sayacim+2;
                                                                   activekey=0;
                                                                  }
                                                            if (activekey == 3)
                                                                  {
                                                                   sayacim=sayacim+3;
                                                                   activekey=0;
                                                                  }
                                                            if (activekey == 4)
                                                                  {
                                                                   if (sayacim ==8) {sayacim=0;activekey=0;lcd.setCursor(0,0);lcd.print("     ");guvence=false;break;}
                                                                    sayacim=0;
                                                                    activekey=0;
                                                                  }
          Serial.println(sayacim);
          }

}

void fujitsu2()
{
  printTime();
  tickermain();
}

void guven()
{
  if ((parolavarmi == 1) && (guvence == false)) {lcd.setCursor(0,0);    lcd.print("kilit"); guvence=true;}
  else if ((parolavarmi == 1) && (guvence == true)) {lcd.setCursor(0,0);lcd.print("     "); guvence=false;}
  activekey=0;
}
void selamiezan()////////////////////////////////////////////// Manual selection for pray time or sela
{
                          activekey=0;
                          lcd.clear();
                          ticker7();
                          lcd.setCursor(0,0);
                          lcd.print("seçiniz");
                          activekey=0;bitti1=false;
                          while (bitti1==false) 
                            {
                              if (activekey==1) {activekey=0;beep();selaoku();bitti1=true;}
                              else if (activekey==2) {activekey=0;beep();ezanoku();bitti1=true;} //kalan sure required for manual ezan          
                              else if (activekey==3) {activekey=0;beep();digitalWrite(amfipin, !digitalRead(amfipin));bitti1=true;} //amfi aç/kapa
                              else if (activekey==4) {activekey=0;beep();bitti1=true;}
                              else {activekey=0;}
                            }
                          lcd.clear();
}
void isitezantime()
  {
                    int timeinminutes = ((hour * 60) + minute);
                    int sabezantotalmin=(sabahezanhour * 60) + sabahezanminute;
                    int ogletotalminutes=(oglehour * 60) + ogleminute;
                    int ikinditotalminutes=(ikindihour * 60) + ikindiminute;
                    int aksamtotalminutes=(aksamhour * 60) + aksamminute;
                    int yatsitotalminutes=(yatsihour * 60) + yatsiminute;
         //           kalansaat = 0; kalandakika = 0;  
                    //------------------------------------------------------------------EZAN ACTION-----------------------------------------------------------------------------
                     if (ezantrap == false) //to avoid repetition in case  ezan returns earlier than expected
                          {
                                     if ((hour==sabahezanhour) && (minute==sabahezanminute) && (ramazanayi==0)) {ezanfile=1;Serial.println("aroma 1");ezanoku();} 
                               else      if ((hour==sabahhour) && (minute==sabahminute) && (ramazanayi==1)) {ezanfile=1;Serial.println("aroma 2");ezanoku();} //ramazan sabah ezanı
                               else      if ((hour==cumavakitzamansaat) && (minute==abs(cumavakitzamandakika)) && (cumavakitsabitle==1) && (dayOfWeek==5)) //Cuma ozel ezanı--note that time was replaced somewhere else with new hour and minute
                                              {
                                                  ezanfile=2;Serial.println("aroma 3");ezanoku();
                                              }
                               else     if ((hour==oglehour) && (minute==abs(ogleminute)) && (cumavakitsabitle==0)) //normal ogle vakti
                                              {
                                                  ezanfile=2;Serial.println("aroma 4");ezanoku();
                                              }                            
                               else     if ((hour==oglehour) && (minute==abs(ogleminute)) && (cumavakitsabitle==1) && (dayOfWeek!=5)) //ogle vakti ve Cuma degil
                                              {
                                                  ezanfile=2;Serial.println("aroma 5");ezanoku();
                                              }  
                               else     if ((hour==ikindihour) && (minute==abs(ikindiminute))) {ezanfile=3;Serial.println("aroma 6");ezanoku();}
                               else     if ((hour==aksamhour) && (minute==abs(aksamminute))) {ezanfile=4;Serial.println("aroma 7");ezanoku();}
                               else     if ((hour==yatsihour) && (minute==abs(yatsiminute))) {ezanfile=5;Serial.println("aroma 8");ezanoku();}
                                    //-------------------------------------------------------------------sela ACTION----------------------------------------------------------------------------
                               else     if ((ramazanayi==0) && (dayOfWeek==5) && (selaokunsun == 1) && (cumavakitsabitle = 0) && (hour==oglehourSela) && (minute=ogleminuteSela)) {ezanfile=2;Serial.println("aroma 9");selaoku();}
                               else     if ((ramazanayi==0) && (dayOfWeek==4) && (persembeselaokunsun == 1) && (hour==persembeselahour) && (minute==persembeselaminute)) {ezanfile=2;Serial.println("aroma 10");selaoku();}
                               else     if ((ramazanayi==1) && ((hour*60)==yatsitotalminutes-45)) {ezanfile=2;Serial.println("aroma 11");selaoku();} //daily sela in Ramazan
                        }
  
  }

void isitroletime() //activate lights automa. in Ramadan month
  {

    if (role1 == 0) {role1devredisi();}
        else if (role2 == 0) {role2devredisi();}
        else if (role1 == 1) {role1devrede();}
        else if (role2 == 1) {role2devrede();}
    if ((role1 == 2) && (role1startsaat==hour) && (role1startdakika==minute)) {role1devrede();}
        else if ((role2 == 2) && (role2startsaat==hour) && (role2startdakika==minute)) {role2devrede();}
        else if ((role1 == 2) && (role1stopsaat==hour) && (role1stopdakika==minute)) {role1devredisi();}
        else if ((role1 == 2) && (role2stopsaat==hour) && (role2stopdakika==minute)) {role2devredisi();}
    if ((ramazanayi == 1) && (hour==aksamhour) && (minute==aksamminute)) {role1devrede();role2devrede();} //relay 1+2 on
        else if ((ramazanayi == 1) && (hour==aksamhour) && (minute==(aksamminute)+15)) {role2devredisi();} //relay 1 off
        else if ((ramazanayi == 1) && (hour==role1stopsaat) && (minute ==role1stopdakika)) {role1devredisi();}// relay 1 timer off
        else if ((ramazanayi == 1) && (hour==sabahhour) && (minute==sabahminute)) {role1devredisi();role2devredisi();} // relay 1 & 2 OFF
        else if ((ramazanayi == 1) && (hour==role2stopsaat) && (minute ==role2stopdakika)) {role2devredisi();}
//Serial.println("module: end isitroletime");                   
}
void kalansure() //used only by manual ezan to determine timing of prayer
  {
//Serial.println("module: start kalansure");
                   // ezanperiod(); //hangi ezan ne kadar sürer DF player için
                    int timeinminutes = ((hour * 60) + minute);
                    int sabezantotalmin=(sabahezanhour * 60) + sabahezanminute;
                    int ogletotalminutes=(oglehour * 60) + ogleminute;
                    int ikinditotalminutes=(ikindihour * 60) + ikindiminute;
                    int aksamtotalminutes=(aksamhour * 60) + aksamminute;
                    int yatsitotalminutes=(yatsihour * 60) + yatsiminute;
                    kalansaat = 0; kalandakika = 0;                    
                    // -----------------------------------------------------------------KALAN ZAMAN -----------------------------------------------------
                    if ((timeinminutes > sabezantotalmin) && (timeinminutes < ogletotalminutes))  
                          {
                            hadise="öğle ye   ";
                            kalandakika = (ogletotalminutes - timeinminutes);
                            kalansaat = int(kalandakika/60);kalandakika = kalandakika - (kalansaat*60);
                            ezanfile = 1;

                          }
                    else if ((timeinminutes > ogletotalminutes) && (timeinminutes < ikinditotalminutes))  
                          {
                            hadise="ikindi ye ";
                            kalandakika = (ikinditotalminutes - timeinminutes);
                            kalansaat = int(kalandakika/60);kalandakika = kalandakika - (kalansaat*60);
                            ezanfile = 2;

                          }                            
                   else if((timeinminutes > ikinditotalminutes) && (timeinminutes < aksamtotalminutes))  
                          {
                            hadise="akşam a   ";
                            kalandakika = (aksamtotalminutes - timeinminutes);
                            kalansaat = int(kalandakika/60);kalandakika = kalandakika - (kalansaat*60);
                            ezanfile = 3;

                          }
                    else if ((timeinminutes > aksamtotalminutes) && (timeinminutes < yatsitotalminutes))
                          {
                            hadise="yatsı ya  ";
                            kalandakika = (yatsitotalminutes - timeinminutes);
                            kalansaat = int(kalandakika/60);kalandakika = kalandakika - (kalansaat*60); 
                            ezanfile = 4;

                          }
                    else
                           {
                            hadise="sabah a   ";
                            if ((timeinminutes > yatsitotalminutes) && (timeinminutes < 1439)) {kalandakika = ((1439-timeinminutes)+sabezantotalmin);Serial.println("<1439=");Serial.println(kalandakika);}//adjusted bug before 23:59
                            else {kalandakika = (sabezantotalmin - timeinminutes);Serial.println(">1439=");Serial.println(kalandakika);}
                            kalansaat = int(kalandakika/60);kalandakika = kalandakika - (kalansaat*60); 
                            ezanfile = 5;

                           }                          
//Serial.println("module: end kalansure");
  }

void ezanperiod() //calculated period of each ezan according to time and muezzin
{
                if      (ezanfile == 1) {interval2=377140;}
                else if (ezanfile == 2) {interval2=239800;}
                else if (ezanfile == 3) {interval2=362970;}
                else if (ezanfile == 4) {interval2=179850;}
                else if (ezanfile == 5) {interval2=359700;}
                
                else  //default if not selected
                      {
                       interval2 = 379999;
                      }
}      
void ezanoku() 
{
Serial.println("ezanoku::::: start   ");
                  ezantrap=true;
                  roledevrede();
                  Serial.println("relay on");
                  boolean stillplaying = true;
                  lcd.clear();activekey=0; lcd.setCursor(0,0); lcd.print("*Amfi*");delay(int(amfigecikme)*1000);//wait for amp
                  int tiktok = 5;int menuoption =0; ticker5();
                  lcd.setCursor(0,0); lcd.print("*ezan*"); 
                  fdvolume=EEPROM.read(22); weynstring[23]=EEPROM.read(23);
                  if (fdvolume > 30) {fdvolume=30;} else if (fdvolume < 0) {fdvolume=0;}
                  fdeq=weynstring[23];
                  myDFPlayer.playFolder(imam, ezanfile); // start playing till millis routine decides its over
                  unsigned long intervalx = interval2;
                  Serial.println("intervalx=");Serial.println(intervalx); //correct info
                  
  while (stillplaying == true)
  {
                        unsigned long currentMillis3=millis();
                        Serial.println("currentMillis3=");Serial.println(currentMillis3);
                        Serial.println("previousMillis3=");Serial.println(previousMillis3);
                        Serial.println("ezanmodule::::: formula=");Serial.println(currentMillis3 - previousMillis3);
                        if (currentMillis3 - previousMillis3 >= intervalx) //ezan period timer 
                          {
                            previousMillis3 = currentMillis3;
                            Serial.println("ezan::::exiting timer...");
                            stillplaying=false;
                          }


                                                            if ((activekey == 1) && (tiktok==5))  {beep();menuoption=1;tiktok=6;ticker6();activekey=0;} //trigger ses ayarı
                                                            if ((activekey == 2) && (tiktok==5))  {beep();menuoption=2;tiktok=6;ticker6();activekey=0;} //trigger eko ayarı
                                                            if ((activekey == 1) && (menuoption==1))// vol vol vol
                                                              {
                                                                //----- ses  
                                                                beep();ticker6();myDFPlayer.volumeDown();fdvolume=fdvolume - 1;if (fdvolume < 0) {fdvolume=0;}activekey=0;
                                                                lcd.setCursor(13,3); lcd.print("  "); lcd.setCursor(13,3); lcd.print(fdvolume); tiktok==6; activekey=0;
                                                              }
  
                                                            if ((activekey == 2) && (menuoption==1))
                                                              {
                                                                //+++++ ses
                                                                beep();ticker6(); myDFPlayer.volumeUp(); fdvolume=fdvolume + 1;if (fdvolume > 30) {fdvolume=30;} if (fdvolume < 0) {fdvolume=0;}
                                                                lcd.setCursor(13,3); lcd.print("  "); lcd.setCursor(13,3); lcd.print(fdvolume); tiktok=6; activekey=0;
                                                              }
                                                            if (activekey == 3)
                                                              {
                                                                beep();
                                                                activekey=0;
                                                              }
                                                            if ((activekey == 4) && (menuoption==1))
                                                              {
                                                                beep();menuoption=0; tiktok=5; ticker5(); activekey=0;
                                                             }
                                                            if ((activekey == 1) && (menuoption==2))// eko eko eko eko
                                                                      {
                                                                              //-----   
                                                                       beep();
                                                                              ticker6();
                                                                              fdeq=fdeq - 1;
                                                                              if (fdeq<1) {fdeq=6;}
                                                                              if (fdeq>6) {fdeq=1;}
                                                                              if (fdeq==1) {myDFPlayer.EQ(DFPLAYER_EQ_NORMAL);}
                                                                              if (fdeq==2) {myDFPlayer.EQ(DFPLAYER_EQ_POP);}
                                                                              if (fdeq==3) {myDFPlayer.EQ(DFPLAYER_EQ_ROCK);}
                                                                              if (fdeq==4) {myDFPlayer.EQ(DFPLAYER_EQ_JAZZ);}
                                                                              if (fdeq==5) {myDFPlayer.EQ(DFPLAYER_EQ_CLASSIC);}
                                                                              if (fdeq==6) {myDFPlayer.EQ(DFPLAYER_EQ_BASS);}
                                                                              activekey=0; lcd.setCursor(13,3); lcd.print("  "); lcd.setCursor(13,3);
                                                                              lcd.print(fdeq); tiktok==6; activekey=0;
                                                                      }
            
                                                                      if ((activekey == 2) && (menuoption==2))
                                                                      {
                                                                                //+++++ 
                                                                              beep();
                                                                              ticker6();
                                                                              fdeq=fdeq + 1;
                                                                              if (fdeq<1) {fdeq=6;}
                                                                              if (fdeq>6) {fdeq=1;}
                                                                              if (fdeq==1) {myDFPlayer.EQ(DFPLAYER_EQ_NORMAL);}
                                                                              if (fdeq==2) {myDFPlayer.EQ(DFPLAYER_EQ_POP);}
                                                                              if (fdeq==3) {myDFPlayer.EQ(DFPLAYER_EQ_ROCK);}
                                                                              if (fdeq==4) {myDFPlayer.EQ(DFPLAYER_EQ_JAZZ);}
                                                                              if (fdeq==5) {myDFPlayer.EQ(DFPLAYER_EQ_CLASSIC);}
                                                                              if (fdeq==6) {myDFPlayer.EQ(DFPLAYER_EQ_BASS);}
                                                                                lcd.setCursor(13,3); lcd.print("  "); lcd.setCursor(13,3); lcd.print(fdeq);
                                                                                tiktok=6; activekey=0;
                                                                      }
                                                                      if (activekey == 3)
                                                                      {
                                                                                beep();activekey=0;
                                                                      }
                                                                      if ((activekey == 4) && (menuoption==2))
                                                                      {
                                                                                beep();menuoption=0; tiktok=5; ticker5(); activekey=0;
                                                                      }                                                            
                                                                      if ((activekey == 4) && (menuoption==0))
                                                                       {
                                                                              //stop
                                                                              beep();myDFPlayer.pause(); activekey=0; stillplaying=false;
                                                                       }  
}
                  activekey=0;
                  if ((fdvolume) != (EEPROM.read(22))) {EEPROM.write(22, fdvolume);} //compare if changed and update eeprom
                  if ((fdeq) != (EEPROM.read(23))) {EEPROM.write(23, fdeq);}
                  lcd.setCursor(0,0);lcd.print("      "); ticker1a();
                  myDFPlayer.pause();
                  Serial.println("relay off");
                  roledevredisi();
                  getDateDs1307(); 
                  printTime();
            //      kalansure();
                  calculatetimes();
                  ezantrap=false;                    
Serial.println("ezanoku:::::end of loop");
}

void selaoku() //same as ezan but different file
{
                  boolean stillplaying;
                  stillplaying = true;
                  roledevrede();
                  lcd.clear();lcd.setCursor(0,0); lcd.print("*Amfi*"); delay(int(amfigecikme)*1000);//wait for amp  
                  activekey=0; int tiktok = 5;int menuoption =0; ticker5();lcd.setCursor(0,0);lcd.print("*sela*");
                  fdvolume=EEPROM.read(22); weynstring[23]=EEPROM.read(23); fdeq=weynstring[23];
                  if (fdvolume > 30) {fdvolume=30;} 
                  else if (fdvolume < 0) {fdvolume=0;}
                  myDFPlayer.playFolder(1, 6);
                  Serial.println("sela interval is");Serial.println(selainterval);
    while (stillplaying == true)  
  {
                        unsigned long cselamillis = millis();
                        if (cselamillis - pselamillis > selainterval)
                          {pselamillis = cselamillis; Serial.println("exiting sela condition with pselamillis=");Serial.println(pselamillis);stillplaying=false;}
                                                            if ((activekey == 1) && (tiktok==5))  {beep();menuoption=1;tiktok=6;ticker6();activekey=0;} //trigger ses ayarı
                                                            if ((activekey == 2) && (tiktok==5))  {beep();menuoption=2;tiktok=6;ticker6();activekey=0;} //trigger eko ayarı
                                                            if ((activekey == 1) && (menuoption==1))// vol vol vol
                                                            {
                                                                //----- ses  
                                                                beep();ticker6(); myDFPlayer.volumeDown();fdvolume=fdvolume - 1;activekey=0;if (fdvolume < 0) {fdvolume=0;}
                                                                lcd.setCursor(13,3); lcd.print("  "); lcd.setCursor(13,3); lcd.print(fdvolume); tiktok==6; activekey=0;
                                                            }
  
                                                            if ((activekey == 2) && (menuoption==1))
                                                            {
                                                                //+++++ ses
                                                                beep();ticker6(); myDFPlayer.volumeUp(); fdvolume=fdvolume + 1; lcd.setCursor(13,3); lcd.print("  "); if (fdvolume > 30) {fdvolume=30;} 
                                                                lcd.setCursor(13,3); lcd.print(fdvolume); tiktok=6; activekey=0;
                                                            }
                                                            if (activekey == 3)
                                                            {
                                                                beep();activekey=0;
                                                            }
                                                            if ((activekey == 4) && (menuoption==1))
                                                            {
                                                                beep();menuoption=0; tiktok=5; ticker5(); activekey=0;
                                                            }
                                                            
                                                                      if ((activekey == 1) && (menuoption==2))// eko eko eko eko
                                                                      {
                                                                              //-----   
                                                                       beep();
                                                                              ticker6();
                                                                              fdeq=fdeq - 1;
                                                                              if (fdeq<1) {fdeq=6;}
                                                                              if (fdeq>6) {fdeq=1;}
                                                                              if (fdeq==1) {myDFPlayer.EQ(DFPLAYER_EQ_NORMAL);}
                                                                              if (fdeq==2) {myDFPlayer.EQ(DFPLAYER_EQ_POP);}
                                                                              if (fdeq==3) {myDFPlayer.EQ(DFPLAYER_EQ_ROCK);}
                                                                              if (fdeq==4) {myDFPlayer.EQ(DFPLAYER_EQ_JAZZ);}
                                                                              if (fdeq==5) {myDFPlayer.EQ(DFPLAYER_EQ_CLASSIC);}
                                                                              if (fdeq==6) {myDFPlayer.EQ(DFPLAYER_EQ_BASS);}
                                                                              activekey=0; lcd.setCursor(13,3); lcd.print("  "); lcd.setCursor(13,3);
                                                                              lcd.print(fdeq); tiktok==6; activekey=0;
                                                                      }
            
                                                                      if ((activekey == 2) && (menuoption==2))
                                                                      {
                                                                                //+++++ 
                                                                              beep();
                                                                              ticker6();
                                                                              fdeq=fdeq + 1;
                                                                              if (fdeq<1) {fdeq=6;}
                                                                              if (fdeq>6) {fdeq=1;}
                                                                              if (fdeq==1) {myDFPlayer.EQ(DFPLAYER_EQ_NORMAL);}
                                                                              if (fdeq==2) {myDFPlayer.EQ(DFPLAYER_EQ_POP);}
                                                                              if (fdeq==3) {myDFPlayer.EQ(DFPLAYER_EQ_ROCK);}
                                                                              if (fdeq==4) {myDFPlayer.EQ(DFPLAYER_EQ_JAZZ);}
                                                                              if (fdeq==5) {myDFPlayer.EQ(DFPLAYER_EQ_CLASSIC);}
                                                                              if (fdeq==6) {myDFPlayer.EQ(DFPLAYER_EQ_BASS);}
                                                                                lcd.setCursor(13,3); lcd.print("  "); lcd.setCursor(13,3);
                                                                                lcd.print(fdeq); tiktok=6; activekey=0;
                                                                      }
                                                                      if (activekey == 3)
                                                                      {
                                                                                beep();activekey=0;
                                                                      }
                                                                      if ((activekey == 4) && (menuoption==2))
                                                                      {
                                                                                beep();menuoption=0; tiktok=5; ticker5(); activekey=0;
                                                                      }                                                            
                                                                      if ((activekey == 4) && (menuoption==0))
                                                                      {
                                                                             beep(); myDFPlayer.pause(); activekey=0;stillplaying=false;
                                                                      }  
}
                  activekey=0; lcd.setCursor(0,0);lcd.print("      "); ticker1a();
                  if ((fdvolume) != (EEPROM.read(22))) {EEPROM.write(22, fdvolume);} //compare if changed and update eeprom
                  if ((fdeq) != (EEPROM.read(23))) {EEPROM.write(23, fdeq);}
                  myDFPlayer.pause();
                  roledevredisi();
                  getDateDs1307(); 
                  printTime();
    //              kalansure();
                  calculatetimes();  
}
void ticker1() //manual
{
                        lcd.setCursor(0,3);
                        lcd.print("elle                ");
}
void ticker1a() //oto prayer relay setup
{
                        lcd.setCursor(0,3);
                        lcd.print("oto sela  röle  ayar");
}
void ticker2() //son=done
{
                        lcd.setCursor(0,3);
                        lcd.print("---- +++++       son");
}
void ticker3()
{
                        lcd.setCursor(0,3);
                        lcd.print("evet hayir       son");
}
void ticker4() //volume up down stop
{
                        lcd.setCursor(0,3);
                        lcd.print("ses- ses+        dur");
}

void ticker5()
{
                        lcd.setCursor(0,3);
                        lcd.print("ses  eko         dur");
}

void ticker6() //volume up down back
{
                        lcd.setCursor(0,3);
                        lcd.print("---- +++++      geri");
}
void ticker7()
{
                        lcd.setCursor(0,3);
                        lcd.print("Sela Ezan Amfi  geri");
}
void tickermain()
{
                        kalansure();
lcd.setCursor(0, 1);
lcd.print("                    ");
lcd.setCursor(0, 2);
lcd.print("                    ");
                        lcd.setCursor(0,2);
                        lcd.print(hadise);
                        lcd.setCursor(10,2);
                        lcd.print( char( kalansaat / 10 + 0x30) );
                        lcd.print( char( kalansaat % 10 + 0x30) );
                        lcd.print(":");
                        lcd.print( char(kalandakika / 10 + 0x30));
                        lcd.print( char(kalandakika % 10 + 0x30));
}

void rolekurulum() //display and adjust relays to on/off/auto
{
                          lcd.clear();
                          lcd.setCursor(0,0);
                          lcd.print(" R1   R2   LCD");
                          lcd.setCursor(0,1);
                          lcd.print(" OT   OT   30  ");
                          lcd.setCursor(0,2);
                          lcd.print(" AÇ   AÇ   60  ");
                          lcd.setCursor(0,3);
                          lcd.print(" KA   KA   99    son");                          
                          activekey=0;bitti=0;
                          rolegoster();roleaction();
                          int amfisayac=0, role2sayac=0,role3sayac=0;activekey=0;
                          while (bitti==false) 
                            {
                              if (activekey==1) {beep();amfisayac = amfisayac + 1; if (amfisayac<0){amfisayac=2;} if (amfisayac>2){amfisayac=0;}role1=amfisayac;rolegoster();roleaction();activekey=0;}
                           else   if (activekey==2) {beep();role2sayac = role2sayac + 1; if (role2sayac<0){role2sayac=2;} if (role2sayac>2){role2sayac=0;}role2=role2sayac;rolegoster();roleaction();activekey=0;}           
                           else   if (activekey==3) {beep();role3sayac = role3sayac + 1; if (role3sayac<0){role3sayac=2;} if (role3sayac>2){role3sayac=0;}role3=role3sayac;rolegoster();roleaction();activekey=0;}           
                           else   if (activekey==4) {beep();activekey=0;bitti=true;}
                              else {activekey=0;}
                            }

EEPROM.write(role1, weynstring[30]);
EEPROM.write(role2, weynstring[31]);

lcd.clear();
calculatetimes();
//check difference then update eeprom
}

void roleaction()
{
  if ((role1 == 0) or (role1 == 2)) {digitalWrite(role1pin, HIGH);}
  if (role1 == 1) {digitalWrite(role1pin, LOW);}
  if ((role2 == 0) or (role2 ==2)) {digitalWrite(role2pin, HIGH);}
  if (role2 == 1) {digitalWrite(role2pin, LOW);}
  if (role3 == 0) {analogWrite(LCDPin, 255);}
  if (role3 == 1) {analogWrite(LCDPin, 170);}
  if (role3 == 2) {analogWrite(LCDPin, 85);}
}

void rolegoster()
{
                          if (role1 == 2) {lcd.setCursor(0,1);lcd.print(">");lcd.setCursor(0,2);lcd.print(" ");lcd.setCursor(0,3);lcd.print(" ");}
                          if (role1 == 1) {lcd.setCursor(0,1);lcd.print(" ");lcd.setCursor(0,2);lcd.print(">");lcd.setCursor(0,3);lcd.print(" ");}
                          if (role1 == 0) {lcd.setCursor(0,1);lcd.print(" ");lcd.setCursor(0,2);lcd.print(" ");lcd.setCursor(0,3);lcd.print(">");}
                          if (role2 == 2){lcd.setCursor(5,1);lcd.print(">");lcd.setCursor(5,2);lcd.print(" ");lcd.setCursor(5,3);lcd.print(" ");}
                          if (role2 == 1){lcd.setCursor(5,1);lcd.print(" ");lcd.setCursor(5,2);lcd.print(">");lcd.setCursor(5,3);lcd.print(" ");}
                          if (role2 == 0){lcd.setCursor(5,1);lcd.print(" ");lcd.setCursor(5,2);lcd.print(" ");lcd.setCursor(5,3);lcd.print(">");}
                          if (role3 == 2){lcd.setCursor(10,1);lcd.print(">");lcd.setCursor(10,2);lcd.print(" ");lcd.setCursor(10,3);lcd.print(" ");}
                          if (role3 == 1){lcd.setCursor(10,1);lcd.print(" ");lcd.setCursor(10,2);lcd.print(">");lcd.setCursor(10,3);lcd.print(" ");}
                          if (role3 == 0){lcd.setCursor(10,1);lcd.print(" ");lcd.setCursor(10,2);lcd.print(" ");lcd.setCursor(10,3);lcd.print(">");}
}
void setkurulum() //setup menu (deleted)
{

}
void setdateabi() {} //n/o
void calculatetimes()
{
ilkoordinat();
int g=3;
ch='0';
int deli = 0;
  calc_method = ch & 0x0F;
  method_params[0] = MethodConfig(18.0, true,  0.0, false, 17.0); // MWL
  method_params[1] = MethodConfig(18.0, true,  0.0, false, 18.0); // Karachi
  method_params[2] = MethodConfig(15.0, true,  0.0, false, 15.0); // ISNA
  method_params[3] = MethodConfig(18.5, true,  0.0, true,  90.0); // Makkah
  method_params[4] = MethodConfig(19.5, true,  0.0, false, 17.5); // Egypt
  method_params[5] = MethodConfig(16.0, false, 4.0, false, 14.0); // Jafari
  method_params[6] = MethodConfig(17.7, false, 0.0, false, 14.0); // Tehranch = '1';
  asr_juristic = ch & 0x0F;
  struct tm current_date;
// copy,ng current date into variables prayer_times uses
  current_date.tm_sec   = second;           /** < seconds after the minute - [ 0 to 59 ] */
  current_date.tm_min   = minute;           /** < minutes after the hour   - [ 0 to 59 ] */
  current_date.tm_hour  = hour;           /** < hours since midnight     - [ 0 to 23 ] */
  current_date.tm_mday  = dayOfMonth;           /** < day of the month         - [ 1 to 31 ] */
  current_date.tm_wday  = dayOfWeek;           /** < days since Sunday        - [ 0 to  6 ] */
  current_date.tm_mon   = month;           /** < months since January     - [ 0 to 11 ] */
  current_date.tm_year  = (((year)+2000) - 1900);  /** < years since 1900 +++year - 1900; */   
  time_t date = mktime(&current_date);
  double times[TimesCount];

get_prayer_times(date, latitude, longitude, 3, times);

//***************************************************************************************morning prayer calculations------------------------

String hour1 = (float_time_to_time24(times[0]).c_str()); 
String hr=String((hour1).charAt(0))+String((hour1).charAt(1));String mn=String((hour1).charAt(3))+String((hour1).charAt(4));
newhour=hr.toInt(); newminute=mn.toInt();
calculatedsabah = (newhour*60)+newminute; tempo=0;
if (sabahdiff == 1) //fix time +++++++++++++
     {   
            deli = calculatedsabah + sabahmajmo;
            sabahhour = int((deli)/60); sabahminute = deli - (sabahhour*60);
     }
else if (sabahdiff == 2)
     {   
            deli = calculatedsabah - sabahmajmo;
            sabahhour = int((deli)/60); sabahminute = deli - (sabahhour*60);
     }
else {sabahhour=newhour;sabahminute=newminute;}

hr="";mn="";newhour=0;newminute=0;deli=0;
//***************************************************************************************prayer calculations------------------------
hour1 = (float_time_to_time24(times[1]).c_str()); 
hr=String((hour1).charAt(0))+String((hour1).charAt(1));mn=String((hour1).charAt(3))+String((hour1).charAt(4));
newhour=hr.toInt(); newminute=mn.toInt();
calculatedgunes = (newhour*60)+newminute; tempo=0;
if (gunesdiff == 1) //fix time +++++++++++++
     {   
            deli = calculatedgunes + gunesmajmo;
            guneshour = int((deli)/60); gunesminute = deli - (guneshour*60);
     }
else if (gunesdiff == 2)
     {   
            deli = calculatedgunes - gunesmajmo;
            guneshour = int((deli)/60); gunesminute = deli - (guneshour*60);
     }
else {guneshour=newhour;gunesminute=newminute;}
hr="";mn="";newhour=0;newminute=0;deli=0;
//***************************************************************************************prayer calculations------------------------
hour1 = (float_time_to_time24(times[2]).c_str()); 
hr=String((hour1).charAt(0))+String((hour1).charAt(1));mn=String((hour1).charAt(3))+String((hour1).charAt(4));
newhour=hr.toInt(); newminute=mn.toInt();
calculatedogle = (newhour*60)+newminute; tempo=0;
if (oglediff == 1) //fix time +++++++++++++
     {   
            deli = calculatedogle + oglemajmo;
            oglehour = int((deli)/60); ogleminute = deli - (oglehour*60);
     }
else if (oglediff == 2)
     {   
            deli = calculatedogle - oglemajmo;
            oglehour = int((deli)/60); ogleminute = deli - (oglehour*60);
     }
else {oglehour=newhour;ogleminute=newminute;}
hr="";mn="";newhour=0;newminute=0;deli=0;
//*****************************************careful asr/sunset are different use asr******prayer calculations------------------------
hour1 = (float_time_to_time24(times[3]).c_str()); 
hr=String((hour1).charAt(0))+String((hour1).charAt(1));mn=String((hour1).charAt(3))+String((hour1).charAt(4));
newhour=hr.toInt(); newminute=mn.toInt();
calculatedikindi = (newhour*60)+newminute; tempo=0;
if (ikindidiff == 1) //fix time +++++++++++++
     {   
            deli = calculatedikindi + ikindimajmo;
            ikindihour = int((deli)/60); ikindiminute = deli - (ikindihour*60);
     }
else if (ikindidiff == 2)
     {   
            deli = calculatedikindi - ikindimajmo;
            ikindihour = int((deli)/60); ikindiminute = deli - (ikindihour*60);
     }
else {ikindihour=newhour;ikindiminute=newminute;}
hr="";mn="";newhour=0;newminute=0;deli=0;
//***************************************************************************************prayer calculations------------------------
hour1 = (float_time_to_time24(times[5]).c_str()); 
hr=String((hour1).charAt(0))+String((hour1).charAt(1));mn=String((hour1).charAt(3))+String((hour1).charAt(4));
newhour=hr.toInt(); newminute=mn.toInt();
calculatedaksam = (newhour*60)+newminute; tempo=0;
if (aksamdiff == 1) //fix time +++++++++++++
     {   
            deli = calculatedaksam + aksammajmo;
            aksamhour = int((deli)/60); aksamminute = deli - (aksamhour*60);
     }
else if (aksamdiff == 2)
     {   
            deli = calculatedaksam - aksammajmo;
            aksamhour = int((deli)/60); aksamminute = deli - (aksamhour*60);
     }
else {aksamhour=newhour;aksamminute=newminute;}
hr="";mn="";newhour=0;newminute=0;deli=0;
//***************************************************************************************prayer calculations------------------------
hour1 = (float_time_to_time24(times[6]).c_str()); 
hr=String((hour1).charAt(0))+String((hour1).charAt(1));mn=String((hour1).charAt(3))+String((hour1).charAt(4));
newhour=hr.toInt(); newminute=mn.toInt();
calculatedyatsi = (newhour*60)+newminute; tempo=0;

if (yatsidiff == 1) //fix time +++++++++++++
     {   
            deli = calculatedyatsi + yatsimajmo;
            yatsihour = int((deli)/60); yatsiminute = deli - (yatsihour*60);
     }
else if (yatsidiff == 2)
     {   
            deli = calculatedyatsi - yatsimajmo;
            yatsihour = int((deli)/60); yatsiminute = deli - (yatsihour*60);
     }
else {yatsihour=newhour;yatsiminute=newminute;}
hr="";mn="";newhour=0;newminute=0;deli=0;

if ((cumavakitsabitle==1) && (dayOfWeek==5))
{
  oglehour = cumavakitzamansaat;
  ogleminute = cumavakitzamandakika;
}

//--------------------------------------------------------------------------------- display time                           
lcd.setCursor(0, 1);
lcd.print("                    ");
lcd.setCursor(0, 2);
lcd.print("                    ");
                            lcd.setCursor(0, 1);
                            lcd.print("İ");
                            lcd.setCursor(1, 1);
                            lcd.print( char( sabahhour / 10 + 0x30) );
                            lcd.print( char( sabahhour % 10 + 0x30) );
                            //lcd.print(sabahhour);
                            lcd.setCursor(3, 1);
                            lcd.print(":");
                            lcd.setCursor(4, 1);
                            //lcd.print(sabahminute); 
                            lcd.print( char( sabahminute / 10 + 0x30) );
                            lcd.print( char( sabahminute % 10 + 0x30) );

                            lcd.setCursor(7, 1);
                            lcd.print("G");
                            lcd.setCursor(8, 1);
                            lcd.print( char( guneshour / 10 + 0x30) );
                            lcd.print( char( guneshour % 10 + 0x30) );
                            //lcd.print(guneshour);
                            lcd.setCursor(10, 1);
                            lcd.print(":");
                            lcd.setCursor(11, 1);
                            //lcd.print(gunesminute); 
                            lcd.print( char( gunesminute / 10 + 0x30) );
                            lcd.print( char( gunesminute % 10 + 0x30) );

                            lcd.setCursor(14, 1);
                            lcd.print("Ö");
                            lcd.setCursor(15, 1);
                            lcd.print( char( oglehour / 10 + 0x30) );
                            lcd.print( char( oglehour % 10 + 0x30) );
                            //lcd.print(oglehour);
                            lcd.setCursor(17, 1);
                            lcd.print(":");
                            lcd.setCursor(18, 1);
                            //lcd.print(ogleminute); 
                            lcd.print( char( ogleminute / 10 + 0x30) );
                            lcd.print( char( ogleminute % 10 + 0x30) );

                            lcd.setCursor(0, 2);
                            lcd.print("İ");
                            lcd.setCursor(1, 2);
                            //lcd.print(ikindihour);
                            lcd.print( char( ikindihour / 10 + 0x30) );
                            lcd.print( char( ikindihour % 10 + 0x30) );
                            lcd.setCursor(3, 2);
                            lcd.print(":");
                            lcd.setCursor(4, 2);
                            //lcd.print(ikindiminute); 
                            lcd.print( char( ikindiminute / 10 + 0x30) );
                            lcd.print( char( ikindiminute % 10 + 0x30) );
                        
                            
                            lcd.setCursor(7, 2);
                            lcd.print("A");
                            lcd.setCursor(8, 2);
                            //lcd.print(aksamhour);
                            lcd.print( char( aksamhour / 10 + 0x30) );
                            lcd.print( char( aksamhour % 10 + 0x30) );
                            lcd.setCursor(10, 2);
                            lcd.print(":");
                            lcd.setCursor(11, 2);
                            //lcd.print(aksamminute); 
                            lcd.print( char( aksamminute / 10 + 0x30) );
                            lcd.print( char( aksamminute % 10 + 0x30) );
                         
                                                        
                            lcd.setCursor(14, 2);
                            lcd.print("Y");
                            lcd.setCursor(15, 2);
                            //lcd.print(yatsihour);
                            lcd.print( char( yatsihour / 10 + 0x30) );
                            lcd.print( char( yatsihour % 10 + 0x30) );
                            lcd.setCursor(17, 2);
                            lcd.print(":");
                            lcd.setCursor(18, 2);
                            //lcd.print(yatsiminute);                            
                            lcd.print( char( yatsiminute / 10 + 0x30) );
                            lcd.print( char( yatsiminute % 10 + 0x30) );
}
/*-------------------------------------------------------------------------------------*/
String two_digits_format(int num){
    char tmp[16];
    tmp[0] = '\0';
    sprintf(tmp, "%2.2d", num);
    return String(tmp);
}
static String int_to_string(int num)
{
    char tmp[16];
    tmp[0] = '\0';
    if (num>=0 && num<=9) sprintf(tmp, "0%d", num);
    else sprintf(tmp, "%d", num);
    return String(tmp);
}

static double fix_hour(double a){
    a = a - 24.0 * floor(a / 24.0);
    a = a < 0.0 ? a + 24.0 : a;
    return a;
}
static void get_float_time_parts(double time, int& hours, int& minutes){
    time = fix_hour(time + 0.5 / 60);   // add 0.5 minutes to round
    hours = floor(time);
    minutes = floor((time - hours) * 60);
}
String float_time_to_time24(double Time){
    if(isnan(Time))
      return String();
    int hours, minutes;
    get_float_time_parts(Time, hours, minutes);
    return two_digits_format(hours) + ':' + two_digits_format(minutes);
}

String float_time_to_time12(double Time, bool no_suffix = false){
  if (isnan(Time))
    return String();
  int hours, minutes;
  get_float_time_parts(Time, hours, minutes);
  const char* suffix = hours >= 12 ? " PM" : " AM";
  hours = (hours + 12 - 1) % 12 + 1;
  return int_to_string(hours) + ':' + two_digits_format(minutes) + (no_suffix ? "" : suffix);
}
double deg2rad(double d){
    return d * M_PI / 180.0;
}
double rad2deg(double r){
    return r * 180.0 / M_PI;
}
static double dsin(double d){
    return sin(deg2rad(d));
}
static double dcos(double d){
    return cos(deg2rad(d));
}
static double dtan(double d){
    return tan(deg2rad(d));
}
static double darcsin(double x){
    return rad2deg(asin(x));
}
static double darccos(double x){
    return rad2deg(acos(x));
}
static double darctan(double x){
    return rad2deg(atan(x));
}
static double darctan2(double y, double x){
    return rad2deg(atan2(y, x));
}
static double darccot(double x){
    return rad2deg(atan(1.0 / x));
}
static double fix_angle(double a){
    a = a - 360.0 * floor(a / 360.0);
    a = a < 0.0 ? a + 360.0 : a;
    return a;
}
static double time_diff(double time1, double time2){
    return fix_hour(time2 - time1);
}
void sun_position(double jd, double &D, double &Eq_t){
    double d = jd - 2451545.0;  // jd is the given Julian date 
    double g = fix_angle(357.529 + 0.98560028 * d);
    double q = fix_angle(280.459 + 0.98564736 * d);
    double L = fix_angle(q + 1.915 * dsin(g) + 0.020 * dsin(2 * g));
    double R = 1.00014 - 0.01671 * dcos(g) - 0.00014 * dcos(2 * g);
    double e = 23.439 - 0.00000036 * d;
    double RA = darctan2(dcos(e) * dsin(L), dcos(L)) / 15.0;
    D = darcsin(dsin(e) * dsin(L));  // declination of the Sun
    RA = fix_hour(RA);
    Eq_t = q / 15.0 - RA;      // equation of time
}
double equation_of_time(double jd){
    double D;
    double Eq_t;
    sun_position(jd, D, Eq_t);
    return Eq_t;
}
double sun_declination(double jd){
    double D;
    double Eq_t;
    sun_position(jd, D, Eq_t);
    return D;
}
double compute_mid_day(double _t){
    double t = equation_of_time(julian_date + _t);
    double z = fix_hour(12 - t);
    return z;
}
double compute_time(double g, double t){
    double d = sun_declination(julian_date + t);
    double z = compute_mid_day(t);
    double v = 1.0 / 15.0 * darccos((-dsin(g) - dsin(d) * dsin(latitude)) / (dcos(d) * dcos(latitude)));
    return z + (g > 90.0 ? - v :  v);
}
void day_portion(double times[]){
    for (int i = 0; i < TimesCount; ++i){
      times[i] /= 24.0;
    }
}
double compute_asr(int Step, double t){
    double d = sun_declination(julian_date + t);
    double g = -darccot(Step + dtan(fabs(latitude - d)));
    return compute_time(g, t);
}
void compute_times(double times[]){
    day_portion(times);
    times[Fajr]    = compute_time(180.0 - method_params[calc_method].fajr_angle, times[Fajr]);
    times[Sunrise] = compute_time(180.0 - 0.833, times[Sunrise]);
    times[Dhuhr]   = compute_mid_day(times[Dhuhr]);
    times[Asr]     = compute_asr(1 + asr_juristic, times[Asr]);
    times[Sunset]  = compute_time(0.833, times[Sunset]);
    times[Maghrib] = compute_time(method_params[calc_method].maghrib_value, times[Maghrib]);
    times[Isha]    = compute_time(method_params[calc_method].isha_value, times[Isha]);
}
double night_portion(double angle){
    switch (adjust_high_lats)
    {
      case AngleBased:
        return angle / 60.0;
      case MidNight:
        return 1.0 / 2.0;
      case OneSeventh:
        return 1.0 / 7.0;
      default:
        // Just to return something!
        // In original library nothing was returned
        // Maybe I should throw an exception
        // It must be impossible to reach here
        return 0;
    }
  }
void adjust_high_lat_times(double times[]){
    double night_time = time_diff(times[Sunset], times[Sunrise]);   // sunset to sunrise

    // Adjust Fajr
    double fajr_diff = night_portion(method_params[calc_method].fajr_angle) * night_time;
    if (isnan(times[Fajr]) || time_diff(times[Fajr], times[Sunrise]) > fajr_diff)
      times[Fajr] = times[Sunrise] - fajr_diff;

    // Adjust Isha
    double isha_angle = method_params[calc_method].isha_is_minutes ? 18.0 : method_params[calc_method].isha_value;
    double isha_diff = night_portion(isha_angle) * night_time;
    if (isnan(times[Isha]) || time_diff(times[Sunset], times[Isha]) > isha_diff)
      times[Isha] = times[Sunset] + isha_diff;

    // Adjust Maghrib
    double maghrib_angle = method_params[calc_method].maghrib_is_minutes ? 4.0 : method_params[calc_method].maghrib_value;
    double maghrib_diff = night_portion(maghrib_angle) * night_time;
    if (isnan(times[Maghrib]) || time_diff(times[Sunset], times[Maghrib]) > maghrib_diff)
      times[Maghrib] = times[Sunset] + maghrib_diff;
  }
void adjust_times(double times[]){
    for (int i = 0; i < TimesCount; ++i)
      times[i] += Time_Zone - longitude / 15.0;
    
    times[Dhuhr] += dhuhr_minutes / 60.0;   // Dhuhr
    
    if (method_params[calc_method].maghrib_is_minutes)    // Maghrib
      times[Maghrib] = times[Sunset] + method_params[calc_method].maghrib_value / 60.0;
    
    times[Isha];

    if (method_params[calc_method].isha_is_minutes)   // Isha
      times[Isha] = times[Maghrib] + method_params[calc_method].isha_value / 60.0;

    if (adjust_high_lats != None)
      adjust_high_lat_times(times);
  }
void compute_day_times(double times[]){
    double default_times[] = { 5, 6, 12, 13, 18, 18, 18 };    // default times
    for (int i = 0; i < TimesCount; ++i)
      times[i] = default_times[i];

    for (int i = 0; i < NUM_ITERATIONS; ++i)
      compute_times(times);

    adjust_times(times);
  }
double get_julian_date(int Year, int Month, int Day){
    if (Month <= 2)
    {
      Year -= 1;
      Month += 12;
    }

    double a = floor(Year / 100.0);
    double b = 2 - a + floor(a / 4.0);
    double c = floor(365.25 * (Year + 4716)) + floor(30.6001 * (Month + 1)) + Day + b - 1524.5;
    
    return c;
  }
  
void get_prayer_times(int Year, int Month, int Day, double _latitude, double _longitude, double _timezo, double times[]){
    latitude = _latitude;
    longitude = _longitude;
    Time_Zone = _timezo;
    julian_date = get_julian_date(Year, Month, Day);
    julian_date = julian_date - longitude / (double) (15 * 24);
    compute_day_times(times);
  }
void get_prayer_times(time_t date, double latitude, double longitude, double Tzone, double times[]){
    tm* t = localtime(&date);
    get_prayer_times((1900 + t->tm_year), (t->tm_mon + 1), (t->tm_mday), latitude, longitude, Tzone, times);
  }

void ilkoordinat()
{
// latitude;  
// longitude;   
switch (ilkodu)
  {
                case 1: //adana
                  latitude=37;longitude=35.321333;
                  break;
                case 2://adıyaman
                  latitude=37.764751;longitude=38.278561;
                  break;
                case 3://afyonkara
                  latitude=38.750714;longitude=30.556692;
                  break;
                case 4://ağrı
                  latitude=39.626922;longitude=43.021596;
                  break;
                case 68://aksaray
                  latitude=38.36869;longitude=34.03698;
                  break;
                case 5://amasya
                  latitude=40.64991;longitude=35.83532;
                  break;
                case 6://ankara
                  latitude=39.92077;longitude=32.85411;
                  break;
                case 7://antalya
                  latitude=36.88414;longitude=30.70563;
                  break;
                case 75://ardahan
                  latitude=41.110481;longitude=42.702171;
                  break;              
                case 8://artvin
                  latitude=41.18277;longitude=41.818292;
                  break;
                case 9://aydın
                  latitude=37.856041;longitude=27.841631;
                  break;
                case 10://balıkesir
                  latitude=39.648369;longitude=27.88261;
                  break;
                case 74://bartın
                  latitude=41.581051;longitude=32.460979;
                  break;
                case 72://batman
                  latitude=37.881168;longitude=41.13509;
                  break;
                case 69://bayburt
                  latitude=40.255169;longitude=40.22488;
                  break;
                case 11://bilecik
                  latitude=40.056656;longitude=30.066524;
                  break;
                case 12://bingol
                  latitude=39.062635;longitude=40.76961;
                  break;
                case 13://bitlis
                  latitude=38.393799;longitude=42.12318;
                  break;
                case 14://bolu
                  latitude=40.575977;longitude=31.578809;
                  break;
                case 15://burdur
                  latitude=37.461267;longitude=30.066524;
                  break;
                case 16://bursa
                  latitude=40.266864;longitude=29.063448;
                  break;
                case 17://çanakkale
                  latitude=40.155312;longitude=26.41416;
                  break;
                case 18://çankırı
                  latitude=40.601343;longitude=33.613421;
                  break;
                case 19://çorum
                  latitude=40.550556;longitude=34.955556;
                  break;
                case 20://denizli
                  latitude=37.77652;longitude=29.08639;
                  break;
                case 21://diyarbakır
                  latitude=37.91441;longitude=40.230629;
                  break;
                case 81://düzce
                  latitude=40.843849;longitude=31.15654;
                  break;
                case 22://edirne
                  latitude=41.681808;longitude=26.562269;
                  break;
                case 23://elazığ
                  latitude=38.680969;longitude=39.226398;
                  break;
                case 24://erzincan
                  latitude=39.75;longitude=39.5;
                  break;
                case 25://erzurum
                  latitude=39.9;longitude=41.27;
                  break;
                case 26://eskişehir
                  latitude=39.776667;longitude=30.520556;
                  break;
                case 27://gaziantep
                  latitude=37.06622;longitude=37.38332;
                  break;
                case 28://giresun
                  latitude=40.912811;longitude=38.38953;
                  break;
                case 29://gümüşhane
                  latitude=40.438588;longitude=39.508556;
                  break;
                case 30://hakkari
                  latitude=37.583333;longitude=73.733333;
                  break;
                case 31://hatay
                  latitude=36.401849;longitude=36.34981;
                  break;
                case 76://ığdır
                  latitude=39.887984;longitude=44.004836;
                  break;
                case 32://isparta
                  latitude=37.764771;longitude=30.556561;
                  break;
                case 34://istanbul
                  latitude=41.00527;longitude=28.97696;
                  break;
                case 35://izmir
                  latitude=38.41885;longitude=27.12872;
                  break;
                case 46://kahramanmaraş
                  latitude=37.585831;longitude=36.937149;
                  break;
                case 78://karabük
                  latitude=41.2061;longitude=32.62035;
                  break;
                case 70://karaman
                  latitude=37.17593;longitude=33.228748;
                  break;
                case 36://kars
                  latitude=40.616667;longitude=43.1;
                  break;
                case 37://kastamonu
                  latitude=41.38871;longitude=33.78273;
                  break;
                case 38://kayseri
                  latitude=38.73122;longitude=35.478729;
                  break;
                case 71://kırıkkale
                  latitude=39.846821;longitude=33.515251;
                  break;
                case 39://kırklareli
                  latitude=41.733333;longitude=27.216667;
                  break;
                case 40://kırşehir
                  latitude=39.14249;longitude=34.17091;
                  break;
                case 79://kilis
                  latitude=36.718399;longitude=37.12122;
                  break;
                case 41://kocaeli
                  latitude=40.85327;longitude=29.88152;
                  break;
                case 42://konya
                  latitude=37.866667;longitude=32.483333;
                  break;
                case 43://kütahya
                  latitude=39.416667;longitude=29.983333;
                  break;
                case 44://malatya
                  latitude=38.35519;longitude=38.30946;
                  break;
                case 45://manisa
                  latitude=38.619099;longitude=27.428921;
                  break;
                case 47://mardınvbo
                  latitude=37.321163;longitude=40.724477;
                  break;
                case 33://mersin
                  latitude=36.8;longitude=34.63333;
                  break;
                case 48://muğla
                  latitude=37.215789;longitude=28.363611;
                  break;
                case 49://muş
                  latitude=38.946189;longitude=41.753893;
                  break;
                case 50://nevşehir
                  latitude=38.69394;longitude=34.685651;
                  break;
                case 51://niğde
                  latitude=37.966667;longitude=34.683333;
                  break;
                case 52://ordu
                  latitude=40.983879;longitude=37.876411;
                  break;
                case 80://osmaniye
                  latitude=37.213026;longitude=36.176261;
                  break;
                case 53://rize
                  latitude=41.02005;longitude=40.523449;
                  break;
                case 54://sakarya
                  latitude=40.693997;longitude=30.435763;
                  break;
                case 55://samsun
                  latitude=41.292782;longitude=3.33128;
                  break;
                case 56://siirt
                  latitude=37.9333333;longitude=41.95;
                  break;
                case 57://sinop
                  latitude=42.02314;longitude=35.153069;
                  break;
                case 58://sıvas
                  latitude=39.747662;longitude=37.017879;
                  break;  
                case 63://şanlıurfa
                  latitude=37.159149;longitude=37.789909;
                  break;  
                case 73://şırnak
                  latitude=37.418748;longitude=42.491834;
                  break;
                case 59://tekirdağ
                  latitude=40.983333;longitude=27.516667;
                  break;  
                case 60://tokat
                  latitude=40.316667;longitude=36.55;
                  break;  
                case 61://trabzon
                  latitude=41.00145;longitude=39.7178;
                  break;  
                case 62://tunceli
                  latitude=39.307355;longitude=39.438778;
                  break;  
                case 64://uşak
                  latitude=38.682301;longitude=29.266667;
                  break;  
                case 65://van
                  latitude=38.48914;longitude=43.40889;
                  break;
                case 77://yalova
                  latitude=40.65;longitude=29.266667;
                  break;  
                case 66://yozgat
                  latitude=39.818081;longitude=34.81469;
                  break;
                case 67://zonguldak
                  latitude=41.456409;longitude=31.798731;
                  break;                         
                case 99://lefkoşa
                  latitude=35.10;longitude=32.21;
                  break;                                  
                default:
                  latitude=38.41885;longitude=27.12872;
                  break;
  }
}


// all below is for key routine
void pressInterrupt() { // ISR
                                      if (millis() - lastFire < 50) { // default is 200
                                        return;
                    }
                    lastFire = millis();
                  
                    configureDistinct(); // Setup pins for testing individual buttons
                  
                    for (int i = 0; i < sizeof(buttonPins) / sizeof(int); i++) { // Test each button for press
                      if (!digitalRead(buttonPins[i])) {
                        press(i);
                      }
                    }
                  
                    configureCommon(); // Return to original state
}

void configureCommon() {
                      pinMode(commonPin, INPUT_PULLUP);
                      for (int i = 0; i < sizeof(buttonPins) / sizeof(int); i++) {
                      pinMode(buttonPins[i], OUTPUT);
                      digitalWrite(buttonPins[i], LOW);
                      }
}

void configureDistinct() {
                      pinMode(commonPin, OUTPUT);
                      digitalWrite(commonPin, LOW);
                    
                      for (int i = 0; i < sizeof(buttonPins) / sizeof(int); i++) {
                        pinMode(buttonPins[i], INPUT_PULLUP);
                      }
}

void press(int button) { // Our handler
                     activekey = (button + 1);
}
void roledevrede()
{
                  digitalWrite(amfipin, LOW);//off
}
void roledevredisi()
{
                  digitalWrite(amfipin, HIGH);//off
}
void role1devrede()
{
                  digitalWrite(role1pin, LOW);//off
}
void role1devredisi()
{
                  digitalWrite(role1pin, HIGH);//off
}
void role2devrede()
{
                  digitalWrite(role2pin, LOW);//off
}
void role2devredisi()
{
                  digitalWrite(role2pin, HIGH);//off
}

//mp3 routine
void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerUSBInserted:
      Serial.println("USB Inserted!");
      break;
    case DFPlayerUSBRemoved:
      Serial.println("USB Removed!");
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
}

void parolakontrol()
{
int hadipass=0;byte parolanedirtemp=0;
while (hadipass == 0)
          {
                                      lcd.setCursor(0,1);
                                      lcd.print("parola giriniz     ");
                                      lcd.setCursor(16,1);
                                      lcd.print(parolanedirtemp);
                                      bitti=0;
                                      while (bitti==false)
                                      {
                                          if (activekey==1) {parolanedirtemp= parolanedirtemp -1; if (parolanedirtemp==-1) {parolanedirtemp=255;}lcd.setCursor(16,1); lcd.print("   ");lcd.setCursor(16,1);lcd.print(parolanedirtemp);}
               else                           if (activekey==2) {parolanedirtemp= parolanedirtemp +1; if (parolanedirtemp>255) {parolanedirtemp=1;}lcd.setCursor(16,1); lcd.print("   ");lcd.setCursor(16,1);lcd.print(parolanedirtemp);}                            
               else                           if (activekey==4) {
                                                                activekey=0;
                                                                if ((parolanedir == parolanedirtemp) or (parolanedir == 129))
                                                                {
                                                                    hadipass=1;
                                                                    bitti=true;                                                                }  
                                                                else
                                                                {
                                                                   lcd.setCursor(16,1);
                                                                   lcd.print("olmaz");
                                                                   delay(30000);
                                                                   lcd.setCursor(16,1);
                                                                   lcd.print("     "); 
                                                                }
                                                            }
                                          else {activekey=0;}
                                        }
        }                       
                                      lcd.clear(); 
}
void beep()
{
                   tone(beeppin, 1000); delay(150); noTone(beeppin); delay (150);           
}

I have not fully read the code, but by skimming it I can see a lot of blocking code (both delay() and long-running while-loops) that would cause millis() timing to be poor.

Shalom vaxman

All these delay()´s will kill the expected realtime behaiviour of your sketch:

Line   53: unsigned long interval2 = 0;//ezan delay 346 seconds
	Line  265:     while (1) delay(10);
	Line  274:   delay(2000);
	Line  305:   delay(1000);
	Line  308:   delay(1000);
	Line  316:   delay(1000);
	Line  838:   lcd.clear(); activekey = 0; lcd.setCursor(0, 0); lcd.print("*Amfi*"); delay(int(amfigecikme) * 1000); //wait for amp
	Line 1013:   lcd.clear(); lcd.setCursor(0, 0); lcd.print("*Amfi*"); delay(int(amfigecikme) * 1000); //wait for amp
	Line 2298:           delay(30000);
	Line 2312:   tone(beeppin, 1000); delay(150); noTone(beeppin); delay (150);

Have a nice day and enjoy programming in C++ and learning.
Дайте миру шанс!

As you may have noticed, non of the delays are inside the troubled loop ezanoku() ... and almost most of them are in Setup.

since I'm using RTC with external xtall, perhaps there is a way to use it instead of millis.

I did not try to analyse your code so do not know if "intervalx" is cumulative or not.
However, Instead of

    if (currentMillis3 - previousMillis3 >= intervalx)  //ezan period timer
    {
      previousMillis3 = currentMillis3;

try

type or paste code here
    if (currentMillis3 - previousMillis3 >= intervalx)  //ezan period timer
    {
      previousMillis3 += intervalx;

Probably not your exact problem, but this is highly likely to be unnecessary.

:face_with_spiral_eyes:

As an alternative, I'm converting time to seconds and comparing it with the interval I have.

byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
                            second     = bcdToDec(Wire.read() & 0x7f);
                            minute     = bcdToDec(Wire.read());
                            hour       = bcdToDec(Wire.read() & 0x3f);
long instance1 = ((hour * 3600) + (minute * 60) + second);

when I print instance1, I get a negative value with the wrong result.

I'm sure its a conversion error but where ?

Did you try the suggestion of @Willem43 in #10? This is mostly the reason if millis() timing isn't exact enough in the long run - apart of the principal error of the clock generator.

Tried and failed. It's not only a timing problem. When millis compare to old value it just exits the routine even if it's illogical.

The code is really messy and you should try to auto-format it in the Arduino IDE (Ctrl+T or via the Tools menu). I cannot spot where "previousMillis3" is set in or prior to "ezanoku()".

I'd think about this line. I don't know what processor you're using, but if the native int is 16 bit, then won't (hour *3600) overflow? Same question for (minute * 60)? It doesn't matter what the target variable is (long or not), the data elements in the calculation also need to be type long, no?
C

Those values are bytes so they overflow above 255, if the compiler does not recognize that a long result is wanted. Better be safe and do:

long instance1 = ((long)hour * 3600) + ((long)minute * 60) + second;
1 Like

That did it. Once optimized, I'll share the routine for others to learn.
Thank you very much

In conclusion,

                  long simdi = ((long)hour * 3600) + ((long)minute * 60) + second;
                  long hedef=(simdi + (interval2/1000)); //interval is in millis so convert to seconds
  while (simdi < hedef)
  {
      getDateDs1307(); //refresh time
      simdi = ((long)hour * 3600) + ((long)minute * 60) + second;
      // do stuff
  }
I think I have an isolated problem in which millis routine failed me in this particular routine. However, I had the pleasure to get feed back from professionals. Thanks again.