DEV Community

Nicolatey
Nicolatey

Posted on

C++ Delay() in Timer: how to use correctly?

Hey there!

I'm a first semester software student and for a course I am exploring the world of C++ and Arduino (UNO in my case).

My assignment is to make a timer counting down from 10 minutes (shown on a 4 digit display).

The thing I struggled with is how to program a pause functionality on the same button (btnOne) that also starts the timer. When I finally discovered how, I noticed something buggy: the delay() might be causing some trouble. See my code for implementation.

When clicking on the start/pause button the button doesn't immediately register it. Possibly because the delay might be blocking the communication of user input to the button.

The delay (of 1 second) is used to limit the execution of the if-statement in timer() to once per second; like a timer.

My question is: how can I improve my code so that the clicks on btnOne are immediately registered?

Thanks so much in advance.

const int btnOne = 8;
const int btnTwo = 9;
int btnOn = LOW;
int btnOff = HIGH;
const int clockPin = 10;
const int dataPin = 11;
const int buzzer = 3;
int btnOneState = 0;
int btnTwoState = 0;
long time = 600000;
long timeValueState = time;
int timerDisplay = 1000;
bool pause = true;

void setup()
{
  Serial.begin(9600);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(btnOne, INPUT_PULLUP);
  pinMode(btnTwo, INPUT_PULLUP);
  pinMode(buzzer, OUTPUT);
}

void timer() {
    // Count down from 600000 to 0
    if (timeValueState >= 600 ) {
      timeValueState = timeValueState - 600;
      Display.show(--timerDisplay);
      // When reached last count, display is set to 0 and buzzer turns on for 5 seconds
      if (timeValueState == 600) {
        Display.show(timerDisplay == 0);
        tone(buzzer, 200);
        delay(5000);
        noTone(buzzer);
      }
      Serial.println("time:");
      Serial.println(timeValueState);
      delay(1000);
    }
}

void loop()
{
  btnOneState = digitalRead(btnOne);
  btnTwoState = digitalRead(btnTwo);

  // If button is on, change state of pause (true, false)
  if (btnOneState == btnOn) {
    Serial.println("btnOne pressed");
    pause = !pause;

  }
  // When button is off and pause is not true, activate the timer
  else if (btnOneState == btnOff && pause == false) {
    Serial.println("btnOne NOT pressed");
    timer();
  }

  // Reset time and timerDisplay back to 10 minutes. 
  if (btnTwoState == btnOn) {
    Serial.println("btnTwo pressed");
    timeValueState = time;
    Display.show(timerDisplay = 1000);
  }
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)