// UNO SKETCH -- SMART BUTTON DEBOUNCE DEMO
// (c) 2024, RuntimeMicro.com, USA
// Pin Change Interrupt library
#include <EnableInterrupt.h>
#include <Keyboard.h>
// declare useful consts and variables
const long AgeExpiration = 25;
volatile unsigned long timeStamp;
volatile uint16_t buttonID;
volatile boolean newButtonEvent;
unsigned long Button_1_Count;
unsigned long Button_2_Count;
void ISR_BUTTON_1()
{
// tests True @1st contact, False on bounces
if ((millis() - timeStamp) > AgeExpiration)
{
// 1st contact --> overWrites timeStamp
timeStamp = millis();
buttonID = 1;
newButtonEvent = true;
}
// subsequent bounce Interrupts fail test (quick exit)
}
void ISR_BUTTON_2()
{
// tests True @1st contact, False on bounces
if ((millis() - timeStamp) > AgeExpiration)
{
// 1st contact --> overWrites timeStamp
timeStamp = millis();
buttonID = 2;
newButtonEvent = true;
}
// subsequent bounce Interrupts fail test (quick exit)
}
// 10 mSec Timer ISR
ISR(TIMER2_OVF_vect)
{
// Test timeStamp Age
if ((millis() - timeStamp) < AgeExpiration) // true=BounceBlock active
{
// Test for button Activity on port-C pins, mask-all except button-pins
if ((PINC & 0b00101000) != 0x28) // both pins HIGH, means no activity
{
// active -- EXTEND timeStamp 25 mSec
timeStamp = millis();
}
}
}
/////////////////////////////// S E T U P ///////////////////////////
void setup()
{
Serial.begin(115200); // reports button actions, keep at 115200 baud!
// associate button-pins with ISR's
enableInterrupt(A5, ISR_BUTTON_1, FALLING);
enableInterrupt(A3, ISR_BUTTON_2, FALLING);
//--- Pull-up button pins
pinMode(A5, INPUT_PULLUP); // ADC pin, PortC-5
pinMode(A3, INPUT_PULLUP); // ADC pin, PortC-3
// Timer-2, 8-bit, Mode-7 Fast, Top=OCRa
// 9.984 mSec Interval, Clock is 16 MHz
// RTM_TimerCalc 1.40
TCCR2B = 0x08; // 0000 1000, Disable Timer
TCCR2A = 0x03; // 0000 0011
OCR2A = 156-1;
TCNT2=0x0;
// Set Overflow Interrupt Mask Bit
TIMSK2 |= 1;
TCCR2B |= 7; // Prescale=1024, Enable Timer
Keyboard.begin();
}
////////////////////////////// L O O P //////////////////////////
void loop()
{
// Button Input Processing
if (newButtonEvent)
{
// identify button
switch (buttonID)
{
case 1:
{
Button_1_Count ++;
Serial.print("Button-1 =");
Serial.println(Button_1_Count);
Keyboard.press(91);
}
break;
case 2:
{
Button_2_Count ++;
Serial.print("Button-2 =");
Serial.println(Button_2_Count);
Keyboard.press(93);
}
break;
} // end switch
// clear button-event Flag
newButtonEvent = false;
} // end newbuttonEvent
// Your main code here
}