Button bounce tester -- test your button.

When debouncing, debounce time is the time since the last bounce, not the first.
You can see for your own button what the longest bounce your button makes to
set debounce time longer than that. It is the time you want the pin state to be stable
before you trust no more bounces will happen. This sketch will help you with that.

// button_tester free for use, written by arduino.cc forum member GoForSmoke 8-21-17
// -- catch button press and release events in detail and print after recording.
// Once the button pin changes state this sketch captures changes in state until the
// time and state arrays are full of the 100ms timeout passes then reports the event.
// This sketch uses a button between pin 7 and ground, pin state 0 is button down.
// The report is bounce detected, micros from first change and pin state.

#include "Arduino.h"

const uint8_t buttonPin = 7; // PD7 on the pin map, chip pin 13 
volatile uint8_t* buttonPinReg = &PIND;
const uint8_t buttonMask = 0x80;
uint8_t buttonState, prevButtonState = 1;

uint16_t micArrIdx, micTime16, micStart16;
const uint16_t arrSize = 100;
uint16_t microsArray[ arrSize ];
uint8_t pinState[ arrSize ]; // RAM spent here for speed
uint8_t prevPinState = 1;

unsigned long debounceTimerStart, debounceTimeout = 100000UL; // micros

uint8_t collectState = 0;

void setup()
{
  Serial.begin( 115200 ); // if you can run faster with your IDE then do!
  Serial.println( F( "\n\nStartup!\n" ));
  pinMode( buttonPin, INPUT_PULLUP );
}

void loop()
{
  micTime16 = ( micros() & 0xFFFFUL );
  buttonState = *buttonPinReg >> 7;

  if ( collectState > 0 )
  {
    switch ( collectState )
    {
    case 1 : // collect data
      if ( micArrIdx < arrSize )
      {
        if ( prevPinState != buttonState )
        {
          microsArray[ micArrIdx ] = micTime16 - micStart16;
          pinState[ micArrIdx++ ] = buttonState;
          prevPinState = buttonState;
        }
      }
      else
      {
        collectState = 100;
      }
      break;
    case 100 : // print report and re-init
      Serial.println( F( " \nReport\n" ));
      for ( uint8_t i = 0; i < micArrIdx; i++ )
      {
        Serial.print( i );
        Serial.print( F( "  " ));
        Serial.print( microsArray[ i ] );
        Serial.print( F( "  " ));
        Serial.println( pinState[ i ] );
      }
      collectState = 0;
      micArrIdx = 0;
      break;
    }
  }
  else 
  {
    if ( buttonState != prevButtonState )
    {
      micStart16 = micTime16;
      microsArray[ micArrIdx ] = 0;
      pinState[ micArrIdx++ ] = buttonState;
      micStart16 = micTime16;
      collectState = 1;
      prevButtonState = buttonState;
      prevPinState = buttonState;
      debounceTimerStart = micros();
    }
  }

  if (( micros() - debounceTimerStart >= debounceTimeout ) && collectState == 1 )
  {
    collectState = 100;
  }
}
1 Like