INPUT_PULLUP, button, debounce and custom counters

Check out “Example - Button with debounce” - available on the pattern site around page 6.

Example - Button w_ debounce.epe (3.5 KB)

/*
* Example to use one of the IO pins as a button with debounce logic.
* This example will increment a mode variable.
*/
buttonPin = 4
debounceTimer = 0
lastButtonState = HIGH
mode = 0
numModes = 3

//initialize the pin we're using as a button with a pull-up resistor
pinMode(buttonPin, INPUT_PULLUP)

export function beforeRender(delta) {
  //read the new button state
  var newState = digitalRead(buttonPin)
  //if its the same as the old state, reset the timer
  if (newState == lastButtonState) {
    debounceTimer = 0;
  } else {
    //otherwise add time to the timer
    debounceTimer += delta;
  }
  //if the timer crosses a threshold, then we're sure the state changed
  if (debounceTimer > 50) {
    lastButtonState = newState
    //do something when the new state is low (button pressed)
    if (newState == 0)
      mode = (mode + 1) % numModes
  }
}

export function render(index) {
  h = mode/numModes
  s = 1
  v = 1
  hsv(h, s, v)
}

BTW - millis() in Arduino rolls over about every 49 days (thats 4,294,967,296 milliseconds for anyone counting). It is a source of bugs that can be hard to track down. It can be used to measure periods of time, but requires a certain style and the use of unintuitive features of unsigned integer math. I’d avoid trying to recreate it in pixelblaze. Instead I’d recommend measuring time relatively with some bounds/limits so that it won’t accumulate past the value limits of variables.

2 Likes