grIMAG3
February 11, 2020, 2:45pm
1
I have this code
unsigned long timeTotal;
float timeTotalSec;
float timeTotalMin;
void setup()
{
Serial.begin(19200);
}
void loop()
{
timeTotal = millis();
timeTotalSec = timeTotal/1000;
timeTotalMin = timeTotalSec/60;
Serial.println(timeTotalMin);
}
My problem is that the result will be like this:
0.00
0.02
0.03
0.05
Instead of:
0.00
0.01
0.02
0.03
In what part of the code should I change to get my wanted result of it incrementing by 0.01 everytime?
grIMAG3:
In what part of the code should I change to get my wanted result of it incrementing by 0.01 everytime?
Why would you assume it increments by 0.01 every time? That would assume each time through loop() takes EXACTLY 10ms, which you cannot guarantee.
The issue is your division by 60. At one second in, you will calculate 1/60 = 0.016666. To two decimal places that rounds to 0.02. I'm really not clear what you're trying to achieve.
as suggested by @ wildbill, your printout starts at 0.02 because of 2dp precision.
you can change that by specifiying the number of decimal points like this:
Serial.print(timeTotalMin, 4); //4dp precision
a better way to output elapsed times since start might be like this:
unsigned long timeTotal = 0;
unsigned long preTime = 0;
float timeTotalSec = 0;
float timeTotalMin = 0;
void setup()
{
Serial.begin(19200);
preTime = millis();
}
void loop()
{
timeTotal = millis() - preTime;
if (timeTotal >= 1000) { //has a second or more passed?
preTime = millis();
timeTotalSec = timeTotal / 1000;
timeTotalMin += (timeTotalSec / 60);
Serial.print(timeTotalMin, 4);
Serial.println("min");
}
}
but if you need accurate timing best used an RTC module .
hope that helps....
grIMAG3
February 11, 2020, 4:43pm
5
Thank you so much for your replies! I finally got the output I'm looking for.