How to use a Buttonpress Class

so I am building an arduino clock with multiple alarms and only 3 buttons.

in order to build this I decided to create a class that allows me to set the hour and minute for each alarm and use switch cases to allow me to toggle between the alarms. The class ultimately looks like this: Alarm1.set_hour(), Alarm1.set_minute(), Alarm2.set_hour(), Alarm2.set_minute() etc. Each method increments an int representing the hour or minute (see example code below).

int SetTime::set_time()
{
  int _buttonpress=digitalRead(_pin);
  int _lastbuttonstate;
  if(_buttonpress!=_lastbuttonstate){
    if(_buttonpress>_lastbuttonstate){
      _mytime++;
    }
  }
  if(_mytime==60)
  {
    _mytime=0;
  }
  return _mytime;

the problem occurs when I try to display the results on an lcd. this is because I have to call the methods several time in order to display them in the format I like.

void loop{
  if (Alarm1.set_hour()<10){
    lcd.setCursor(0,0);
    lcd.print("0");
    lcd.setCursor(1,0);
    lcd.print(Alarm1.set_hour());
  }.
  .
  etc.
}

When i run this in a loop, each time I press the button the relevant hour or minute increments by 2. I think this is because the loop calls the methods twice whilst I am still pressing the button.

I think it might be possible to fix this by messing around with debounce and timings, but I was wondering whether it's possible to assign the output of each method to a static int. Of course just using int Alarm1.set_hour() doesn't work...

Anyone have any ideas?

Here is a library that does something similar, maybe there is something there that might be useful:

See the examples that come withe the zip.

Two suggestions:

  1. you should make _lastbuttonstate a static local variable so the button state is remembered between calls.

  2. it is bad style to call a function named "...set..." to just READ a value. Implement an additional "...read" or "...get" method

thanks guys! i ain't a programmer so it's hard to figure things out when you go beyond the standard arduino tutorials and are faced with a million and one different aspects of c++.

i will check out the read and get method..