I am new into Arduino building a simple timer.
I need to calculate seconds into hh:mm:ss for sending the hh:mm:ss to LCD.
When counting down to zero "18" is not displayed.
why is "18" ignored and replaced for "17"?
void setup() {
Serial.begin(9600);
double Timer;
double ss;
int xx;
Timer = 18;
ss = ((((Timer/3600)-0)*60-0)*60);
xx = int(ss);
This means that your calculation of ss results in a value just smaller than 18.0F and that printing to 2 decimal places it is rounded to 18.00. int(ss) does not round, it truncates so the result is 17. If you want to round rather than truncate then you can used int(ss+0.5) .
Just some hard-earned advice from a professional programmer here: never use floating point for time, currency, or anything lse that has to be counted. Use an integer (short, long. byte) and keep your value as an integer number of your smallest unit.
I make useage of float for the following reason:
In case Timer > 1hour (= > 3600 secs) I devide the Timervalue to achive hh mm and ss.
Division of figures mostly results in floating point figures.
hh = int (Timer/3600);
mm = int (((Timer/3600)-hh)*60);
ss = ((((Timer/3600)-hh)*60-mm)*60);
I make useage of float for the following reason:
In case Timer > 1hour (= > 3600 secs) I devide the Timervalue to achive hh mm and ss.
Division of figures mostly results in floating point figures.
hh = int (Timer/3600);
mm = int (((Timer/3600)-hh)*60);
ss = ((((Timer/3600)-hh)*60-mm)*60);
Use the round operator, if you want rounding.
There are 3 float -> int operators, round (to nearest), floor (towards negative) and ceil
(towards positive). The default conversion is truncate (towards zero)
Paul, AWOL and guix are correct. Use the type [b]long[/b] for your variable Timer, and [b]int[/b] for hours, minutes and seconds. Then use divide ([b]/[/b]) and modulo ([b]%[/b]) to take Timer apart into its parts. The code snippet guix pointed to works fine.
[bit of a rant:]
sowtie and Mark are also right, but if you never learn floating point, you won't be tempted to abuse use it. Realize that you are getting two different answers in this thread. One is to use floating point correctly, and the other is to ditch floating point in favor of integer math.
Even if this floating point section is small and relatively fast, using floats in a loop or for repeating calculations can lead to sluggishness in your sketch. Unfortunately floating point blocking is internal and you can't fix it. There is very little that floating point calculations (especially on a machine that is not built specifically to perform them) can do that can't be done much faster and more efficiently (admittedly, with a bit more programming involved) with integers.