Arduino Button Debounce

I’m currently working on a project to hack my daughter’s “Stars” tortoise.  It uses the shell of the tortoise as a mask to project stars on to the ceiling.  It can project 3 different colours – selected by buttons on it’s back.

I plan to replace the internals with a simple Arduino based circuit that has one (or more) RGB LEDs and can offer colour cycling options as well as static colours.

As part of this I need to manage button presses etc.. so I abstracted a simple button handler that also copes with debounce.

struct button {
  byte pin;
  byte debounce;
  byte released;
};
 
#define NOTPRESSED 0
#define PRESSED 1
#define DEBOUNCE 2
#define RELEASED 3
 
// Debounce delay in approx millisecs
#define BOUNCE 200
 
// Main loop delay in millisecs (used by delay)
#define DELAY 10
 
/ Two example buttons
struct button modebutton = { modepin, 0, 0 };
struct button selectbutton = { selectpin, 0, 0 };
 
// Button Handler
int buttonHandler(struct button * b) {
  if ( b->debounce ) {        // Debounce delay
    b->debounce--;
    return( DEBOUNCE );
  } else {
    if ( digitalRead(b->pin) == HIGH ) {
      if ( ! b->released ) {  // Button has been released
        b->debounce = BOUNCE / DELAY;
        b->released = 1;
        return( PRESSED );
      }
    } else {                 // Button released
      b->released = 0;
      return( RELEASED );
    }
  }
  return( NOTPRESSED );
}
 
// example usage
if ( buttonHandler( &modebutton ) == PRESSED ) {
  mode = (mode + 1) & 3;

It’s not object oriented – that would be overkill and I rarely use OOP on what are essentially simple programs with an enforced small footprint.