I am making an arduino clock/alarm. I use an LCD screen to display the time.
void loop(){
static unsigned long timing=micros();
if (mode == 0) {//mode 0 is when the time should show
timing=countTime(timing);
writeTime(minutes, hours);//display time
}
}
unsigned long countTime(unsigned long timing){
if (micros() - timing >= 59946970) {
return timing += 59946970;//more precise because Arduino timing is not perfect
minutes++;
}
else{
return timing;
}
}
void writeTime(int minute, int hour) {
lcd.setCursor(6, 1);
if (minute >= 60) {
minute = 0;
hour++;
}
if (hour >= 24) {
hour = 0;
}
if (minute < 10) {
if (hour < 10) {
lcd.print(String("0") + hour + ":" + "0" + minute);
}
else {
lcd.print(hour + String(":") + "0" + minute);
}
}
else {
if (hour < 10) {
lcd.print(String("0") + hour + ":" + minute);
}
else {
lcd.print(hour + String(":") + minute); //possibly split if problems arise
}
}
}
I used to do all this within the loop, but decided to make it separate. Why isn't this code working?
1 Answer 1
This statement:
static unsigned long timing=micros();
...only gives it an initial value. It is not executed during loop
. These kinds of variables should be assigned an initial value in an executable section, perhaps when the alarm time is set.
This requires the definition to be pulled out, to the file scope:
static unsigned long timing;
void loop(){
if (mode == 0) {//mode 0 is when the time should show
timing=countTime(timing);
Here, the static
keyword has a different meaning, although I usually use it to reduce the chances of colliding with other global variable names.
Make sure to give it an initial value in executable code somewhere:
void setup()
{
...
timing = millis(); // Just once? When the alarm is set?
}
... and update it as you do in countTime
.
UPDATE It's not clear from your snippet as to when the
timing
variable should be initialized, so I originally avoided addressing that. If it is really initialized just once, at program startup, you can set it in setup
. Otherwise, it should be set when the initial timing
value is finally known.
-
Why have it static if you assign every loop? Also, as a matter of form, you should always assign a static variable with a default value.Majenko– Majenko2016年06月16日 15:36:40 +00:00Commented Jun 16, 2016 at 15:36
-
LOL, that should be inside the if statement, and initialized in
setup
.slash-dev– slash-dev2016年06月16日 15:42:22 +00:00Commented Jun 16, 2016 at 15:42