0

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?

asked Jun 16, 2016 at 15:18

1 Answer 1

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.

answered Jun 16, 2016 at 15:28
2
  • 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. Commented Jun 16, 2016 at 15:36
  • LOL, that should be inside the if statement, and initialized in setup. Commented Jun 16, 2016 at 15:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.