# Code not working as expected,

**URL:** <https://forum.arduino.cc/t/code-not-working-as-expected/1071086>\
**Category:** Programming\
**Created:** [December 30, 2022, 3:25am UTC](https://forum.arduino.cc/t/code-not-working-as-expected/1071086 "2022-12-30T03:25:41Z")\
**Posts on this page:** 1\
**Showing post:** 20

<div class="post-metadata">

**Author:** ![StefanL38](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/stefanl38/32/713548_2.png) [@StefanL38](https://forum.arduino.cc/u/StefanL38)\
**Post date:** [January 1, 2023, 10:42am UTC](https://forum.arduino.cc/t/code-not-working-as-expected/1071086/20 "2023-01-01T10:42:49Z")

</div>

Hi @arshath786

you put the if-condition into the function TimePeriodIsOver

```arduino
// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
  unsigned long currentMillis = millis();
  if ( currentMillis - startOfPeriod >= TimePeriod ) {
    // more time than TimePeriod has elapsed since last time if-condition was true
    startOfPeriod = currentMillis; // a new period starts right here so set new starttime
    return true;
  }
  else return false; // actual TimePeriod is NOT yet over
  if ("minuteOfDay" == 0) {
    digitalWrite(12, HIGH);
  }
}

```

There is a spelling-error  
you wrote minuteofDay  
but it has to be  
minute **O** fDay

CAPITAL "O"

What was the reason for you to put it inside this function?

The condition that you defined itself does not work

```arduino
  if ("minuteOfDay" == 0) {

```

what your condition is  
compare if fixed string with charactersequence **minuteofDay** is the same as number zero  
which of course is **never** true

the double-hyphen make the characters a string  
"minuteOfDay"  
it works if you code it without the double-hyphen

```arduino
  if ("minuteOfDay" == 0) { // double-hyphen is WRONG

```

```arduino
  if (minuteOfDay == 0) { // WITHOUT double-hyphen it works

```

but you should **not** put it into the function TimePeriodIsOver  
This would counteract **massively** on the concept that each function does **one** thing  
The function **TimePeriodIsOver** does what its name says:

check if a certain period of time is over

The name says absolutely nothing about:

"and if its midnight switch on a LED!"

You would have almost hidden away the LED-switching and you and everybody else would have to analyse the code very very carefully to detect ah ! here the LED is switched on !

You should use self-explaining names for everything  
for two reasons

- 
  1. it makes the code easier to read

- 
  1. if you change the value that is represented by this name there is exactly **one place** to change the value

example: you want to change the LED from IO-pin 12 to IO-pin 8

With a self-explaining name you **can't** forget the third place where you have coded " **12**" to change it to "8" because there is only **one** place to change it

```arduino
...
  pinMode(12, OUTPUT);
...
  digitalWrite(12,LOW);
...
  if (minuteOfDay == 0) { 
    digitalWrite(12,HIGH);
  }

```

changes to  
.

```arduino
...
  pinMode(8, OUTPUT);
...
  digitalWrite(8,LOW);
...
  if (minuteOfDay == 0) { 
    digitalWrite(8,HIGH);
  }

```

.  
.

```arduino
const byte LED_Pin = 12; // define constants ofr IO-pin numbers

```

in combination with

```arduino
...
  pinMode(LED_Pin, OUTPUT);
...
  digitalWrite(LED_Pin,LOW);
...
  if (minuteOfDay == 0) { 
    digitalWrite(LED_Pin,HIGH);
  }

```

changes to

```arduino
const byte LED_Pin = 8; // define constants ofr IO-pin numbers

```

and you are done !  
Because at all other places in your code the **name**  **LED\_Pin** is used  
.  
.  
I defined to new constants

```arduino
const int MOD_to_Switch_On = 0 * 60; // M)inutes-O)f-D)ay

const long SOD_to_switch_off = 1 * 60 + 10; // S)econds-Of-D)ay at 00:01:10

```

which are used to switch on / off the LED at the bottom of loop

```arduino
  if (minuteOfDay == MOD_to_Switch_On) {
    digitalWrite(LED_Pin, HIGH);
  }  

  if (secondsOfDay == SOD_to_switch_off) { 
    digitalWrite(LED_Pin, LOW);
  }    

```

The **self** -explaining names make commenting obsolete  
The code explains itself

> [@arshath786](#):
>
> he first being, the time printed, instead of being 22/1/13 (Sunday) 23:59:50, is 81/13/7 (Tuesday) 19:50:0. It fixes after a few resets on the board, but this error pops up randomly.

if it does **not** occur regular but only from time to time I suspect this is a **bad signal** problem or a wrong RTC-type problem

the constructor has anoption for a second parameter  
define explicitly the your RTC-type

This name " **URTCLIB\_MODEL\_DS1307**" is defined in the uRTC.h-file of the library

```arduino
// uRTCLib rtc; // URTCLIB_MODEL_DS1307
//uRTCLib rtc(0x68);
uRTCLib rtc(0x68,URTCLIB_MODEL_DS1307); // define EXPLICIT the model

```

Does the RTC-module have pullup-resistors?  
On the I2C-bus do all pins have **secure** contact?

So here is a version with the modifications like describes above

```arduino
/*structure (= function-call hierachry) of the code
   setup()
    - calls setRTC_Time()

   loop()
    - calls UpDateTime()
            - calls rtc.year() etc.
    - calls TimePeriodIsOver()
       - conditionally calls PrintTime()
*/

#include "Arduino.h"
#include "uRTCLib.h"

// uRTCLib rtc; // URTCLIB_MODEL_DS1307
//uRTCLib rtc(0x68);
uRTCLib rtc(0x68,URTCLIB_MODEL_DS1307); // define EXPLICIT the model

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

int myYear;
int myMonth;
int myDay;
int myDayOfWeek;
int myHour;
int myMinute;
int mySecond;
int minuteOfDay;
// 23*3600+59*60+59 = 86399 which is a to big number for int
long secondsOfDay;

const int MinOfDay_9OClock = 9 * 60;
const int MOD_to_Switch_On = 0 * 60; // M)inutes-O)f-D)ay

const long SOD_to_switch_off = 1 * 60 + 10; // S)econds-Of-D)ay at 00:01:00

unsigned long myTimer;

const byte LED_Pin = 12; // define constants ofr IO-pin numbers

void setup() {
  Serial.begin(9600);
  delay(3000); // wait for console opening
  pinMode(LED_Pin, OUTPUT);
  URTCLIB_WIRE.begin();
  setRTC_Time();
}

void loop() {
  UpDateTime();
  // check if more than 1000 milliseconds have passed by
  // since last time the 1000-ms-period-was-over
  if ( TimePeriodIsOver(myTimer, 1000) ) {
    // if REALLY 1000 milliseconds have passed by
    PrintTime();
  } 
  
  if (minuteOfDay == MOD_to_Switch_On) {
    digitalWrite(LED_Pin, HIGH);
  }  

  if (secondsOfDay == SOD_to_switch_off) { 
    digitalWrite(LED_Pin, LOW);
  }    
}

void setRTC_Time() {
  // Comment out below line once you set the date & time.
  // Following line sets the RTC with an explicit date & time
  // for example to set January 13 2022 at 12:56 you would call:
  myYear = 22;
  myMonth = 1;
  myDay = 13;
  myDayOfWeek = 7;
  myHour = 23;
  myMinute = 59;
  mySecond = 50;
  // using variables makes comments obsolete
  //void uRTCLib::set(const uint8_t second, const uint8_t minute, const uint8_t hour, const uint8_t dayOfWeek, const uint8_t dayOfMonth, const uint8_t month, const uint8_t year) {
  //rtc.set( mySecond, myMinute, myHour, myDayOfWeek, myDay, myMonth, myYear) ;
  rtc.set(mySecond, myMinute, myHour, myDayOfWeek, myDay, myMonth, myYear) ;
  // set day of week (1=Sunday, 7=Saturday)
}

void UpDateTime() {
  rtc.refresh();

  myYear = rtc.year();
  myMonth = rtc.month();
  myDay = rtc.day();

  myHour = rtc.hour();
  myMinute = rtc.minute();
  mySecond = rtc.second();

  minuteOfDay = myHour * 60 + myMinute;
  secondsOfDay = myHour * 3600 + myMinute * 60 + mySecond;
}

void PrintTime() {
  Serial.print("Current Date & Time: ");
  Serial.print(myYear);
  Serial.print('/');
  Serial.print(myMonth);
  Serial.print('/');
  Serial.print(myDay);

  Serial.print(" (");
  Serial.print(daysOfTheWeek[rtc.dayOfWeek() - 1]);
  Serial.print(") ");

  Serial.print(myHour);
  Serial.print(':');
  Serial.print(myMinute);
  Serial.print(':');
  Serial.print(mySecond);
  Serial.println();

  Serial.print("minuteOfDay:");
  Serial.print(minuteOfDay);

  Serial.print(" secondsOfDay:");
  Serial.println(secondsOfDay);

}

// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
  unsigned long currentMillis = millis();
  if ( currentMillis - startOfPeriod >= TimePeriod ) {
    // more time than TimePeriod has elapsed since last time if-condition was true
    startOfPeriod = currentMillis; // a new period starts right here so set new starttime
    return true;
  }
  else return false; // actual TimePeriod is NOT yet over
}
```

If you want to understand the function TimePeriodIsOver you can read this tutorial about non-blocking timing

> [@Example-code for timing based on millis() easier to understand through the use of example-numbers / avoiding delay()](https://forum.arduino.cc/t/example-code-for-timing-based-on-millis-easier-to-understand-through-the-use-of-example-numbers-avoiding-delay/974017):
>
> non-blocking timing. Execute code only from time to time. There are a lot of different ways to learn programming. This thread wants to add another approach that is different to the yet existing ones. UPDATE 06.01.2023 if you are mainly interested in applying non-blocking timing you can do a quick read of this short tutorial / demonstration If you are intersted in understanding the details how it works go on reading here. I use an everyday analogon in this post to explain the basic principle …

---

_[View the full topic](https://forum.arduino.cc/t/code-not-working-as-expected/1071086)._
