Adding Unsigned longs together gives the wrong answer

Hello everyone,

I have a bit of code that will take the hour and minute from an RTC on a Controllino and covert it to seconds so I can use it for timing calculations, but the math I am getting back is wrong, I am sure there is a simple fix but a nudge in the right direction would be appreciated.

when I try to add long start1 = MinToSec + hourToSec ; I get 55800 not 7200?

#include <SPI.h>
#include <Controllino.h>

int hour = 0;
int minute = 0;
unsigned long seconds = 0;
int day = 0;
int weekday = 0;
int month = 0;
int year = 0;
unsigned long current_time;
const long seconds_per_day = 24l * 60l * 60l;



void setup() {
  Serial.begin(9600);                       // initialise Serial monitor
  Controllino_RTC_init(0);                  // initialise the real time clock
  Controllino_SetTimeDateStrings(__DATE__, __TIME__);
  getDateTime();
}

void loop() {
  unsigned long h1 = (hour * 60l) * 60l;

  current_time = (hour * 60l) * 60l  + (minute * 60l) + seconds;
  getDateTime();
  Timer();



}

void Timer() {
  long s1 = 15;
  long m1 = 30;

  unsigned long hourToSec = (s1 * 60l) * 60l ; //5400
  unsigned long MinToSec = m1 * 60l;           //1800
  long start1 = MinToSec + hourToSec ;        
  long end1 = 7 * 60 * 60;
  long interval = (end1 - start1 + seconds_per_day) % seconds_per_day;
  Serial.println(start1);
  bool is_in_interval = ((current_time - start1 + seconds_per_day) % seconds_per_day) < interval;
  //if (is_in_interval)Serial.println("We are in the interval");
}



void getDateTime() {
  hour = Controllino_GetHour();
  minute = Controllino_GetMinute();
  seconds = Controllino_GetSecond();
  day = Controllino_GetDay();
  weekday = Controllino_GetWeekDay();
  month = Controllino_GetMonth();
  year = Controllino_GetYear();
}

15x60x60= 54000

That's 54000, not 5400.

15 * 60 = 900
900 * 60 = 54000

Sorry typo there that should have been //54000

Ho, my days I need Coffee, face plant

Thanks Hammy and johnwasser

is this resolved?

Hummmmm ????

minute * 60l ????? minute is int ----> int * long ????

You have to specify at least one of the numbers is a long or unsigned long, otherwise the compiler defaults to doing the math as int, then converts the answer to unsigned long, resulting in an overflow in the calculation.

This could have been the route to a cleaner solution, you were on the right track but veered off.
You could:

const long seconds_per_hour = 60L * 60;
const long seconds_per_day = 24 * seconds_per_hour;
...
  unsigned long hourToSec = s1 * seconds_per_hour;

...and I believe there are several places in your code where this would clean things up a lot.

I always use capital "L" for long because the "l" can look a lot like a "1".

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