From a319e70d06d946b81a2ba3d10d5a9a08e426de1a Mon Sep 17 00:00:00 2001 From: KaraBun Date: Thu, 22 Dec 2022 15:37:01 -0500 Subject: [PATCH] Added Debounce timers and logic. --- Lanes.ino | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/Lanes.ino b/Lanes.ino index c5d04d2..03da2c9 100644 --- a/Lanes.ino +++ b/Lanes.ino @@ -12,6 +12,7 @@ const int Enc1Btn = 16; //Encoder 1 Button const int Enc2Btn = 17; //Encoder 2 Button const int ClockIn = 4; //Clock In const int ClockDetect = 7; //Detect clock jack +const int DebounceTime = 10; //Debounce time in ms Encoder LeftEnc( Enc1P1, Enc1P2); Encoder RightEnc( Enc2P1, Enc2P2); @@ -21,7 +22,8 @@ int E2 = 0; bool E1Btn = false; bool E2Btn = false; bool ClockState = false; -bool E1Prev, E2Prev, CDPrev = false; +bool E1Prev, E2Prev, CDPrev, E1Click, E2Click, CDIn = false; +unsigned int E1Bounce, E2Bounce, CDBounce = 0; unsigned long ClockPrev = 0; byte Input = 0; int PpQN = 24; @@ -56,7 +58,7 @@ void setup() { ClockState = digitalRead(ClockIn); CDPrev = digitalRead(ClockDetect); - //Clear the Lanes + //Initialize the Lanes for(int i = 0; i < 16; i++){ Lane1[0][i] = random(0, 96); Lane1[1][i] = random(0, 255); @@ -75,28 +77,46 @@ void setup() { analogWrite( Lane1Pin, Lane1[1][0]); analogWrite( Lane2Pin, Lane2[1][0]); analogWrite( Lane3Pin, Lane3[1][0]); + + // Timer0 is already used for millis() - we'll just interrupt somewhere + // in the middle and call the "Compare A" function below + OCR0A = 0xAF; + TIMSK0 |= _BV(OCIE0A); + } void loop() { - //delay(1); long newLEnc = LeftEnc.read(); long newREnc = RightEnc.read(); if (digitalRead(Enc1Btn) != E1Btn){ + if (E1Bounce == 0 & E1Click == false){ Serial.println("E1Btn State Change"); E1Btn = !E1Btn; + E1Bounce = DebounceTime; + E1Click = true; + } } if (digitalRead(Enc2Btn) != E2Btn){ + if (E2Bounce == 0 & E2Click == false){ Serial.println("E2Btn State Change"); E2Btn = !E2Btn; + E2Bounce = DebounceTime; + E1Click = true; + } } - if (digitalRead(ClockDetect) != CDPrev){ - Serial.println("Clock Detect Change"); - CDPrev = !CDPrev; + bool newCD = digitalRead(ClockDetect); + + if (newCD != CDPrev){ + if (CDBounce == 0){ + Serial.println("Clock Jack Status Change"); + CDPrev = CDIn = newCD; + CDBounce = DebounceTime << 4; + } } if ( digitalRead(ClockIn) != ClockState){ @@ -167,4 +187,12 @@ void loop() { Lane3Time = ClockTime; analogWrite(Lane3Pin, Lane3[1][Lane3Pos]); } +} + +// Interrupt is called once a millisecond, +SIGNAL(TIMER0_COMPA_vect) +{ + E1Bounce = (E1Bounce - 1) & 0b10000000; + E2Bounce = (E2Bounce - 1) & 0b10000000; + CDBounce = (CDBounce - 1) & 0b10000000; } \ No newline at end of file