Basic Calculation Results Wrong Value

Hi guys, I need to make a very basic arithmetic calculation however the result is not correct.

Below code is just a small part of the whole code, everything works as expected in the rest of the code. I just added below calculation to code.

lightOnTime = H[9]*3600 + M[9]*60 + S[9];

I use serialprint before the calculation to make sure below values are correct.
H[9] = 16
M[9] = 45
S[9] = 0

H[10] = 20
M[10] = 15
S[10] = 0

So the lightOnTime calculation should result 60.300 but instead it results 8176.
lightOffTime calculation should result 72.900 however it results 4294959360

What is wrong here?

unsigned long currentTime = 0;
unsigned long lightOnTime = 0;
unsigned long lightOffTime = 0;

byte H[15];
byte M[15];
byte S[15];

void setup()
{
byte H[15] = {5, 2,  6, 11, 12, 14, 15, 17, 21, 16, 20,  0,  0,  0,  0};
byte M[15] = {0, 0, 30,  0, 30,  0, 30,  0, 30, 45, 15,  0,  0,  5,  0};
byte S[15] = {0, 0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 45,  0,  5};


         currentTime = hour()*3600 + minute()*60 + second();
         lightOnTime = H[9]*3600 + M[9]*60 + S[9];
         lightOffTime = H[10]*3600 + M[10]*60 + S[10];

}

Integer overflow. Use unsigned long for all time calculations, e.g.

      currentTime = hour()*3600UL + minute()*60UL + second();

H[9] = 16, x 3600 = 57600
M[9] = 45, x 60 = 2700
S[9] = 0,
Total = 60,300
Hmm, don't see how 8176 is coming out. Odd.

Maybe add UL after 3600 and 60, to force all math to be unsigned long. Or add that in the array definitions:
unsigned long H[15] = ...

Thanks a lot guys, solved it by adding UL after 3600 and 60.. Result working code is below for future reference;

currentTime = hour()*3600UL + minute()*60UL + second();
lightOnTime = H[9]*3600UL + M[9]*60UL + S[9];
lightOffTime = H[10]*3600UL + M[10]*60UL + S[10];

FYI on the ATmega microcontrollers the default integer size is 16 bit, so any expression not involving
long variables or constants will be evaluated as 16 bit, and overflow if the result is too big. If any of
the arguments to the operator involved are declared long, this will force the operator to be done as
32 bit.

This can surprize people as most C/C++ implementations are 32 bit for int.

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