Hello
I realised that I installed verry noisy switch on my analog button setup. My code do find the proper switch but onnce in a while not the proper one is decode
I did installed a debounce time of 400 ms to prevent multiple iteractions of the same button press. If I press the same button ten time, I may not received the same button number EX: switc 2 was pressed
2
2
3
2.
Actually, I'm reading the analog value every 400ms. If the switch is in transition, when the reading is done, I may get false reading. Is it the proper way to debounce an analog reading?
void loop()
{
if(Debouncetimer.done()){
ReadKeyPress();{
if (SW>0){
Serial.println(SW);
Debouncetimer.start();
}
}
}
}
Any input appreciated.
Martin
Complete code
#include <neotimer.h>
Neotimer SW_timer = Neotimer(300);
Neotimer Debouncetimer = Neotimer(400);
const unsigned long shortPress = 500;
const unsigned long longPress = 1000;
#define ANALOG_PIN A0
int SW = 0; //Switch value
int SW_Prev = 0; //Previous switch
int SW1 = 1024; //Analog read values
int SW2 = 280;
int SW3 = 74;
int SW4 = 22;
int SW0 = 12;
int T0 = 0;
int T1 = 0;
int T2 = 0;
int T3 = 0;
int T4 = 0;
int count_Rebounce = 0;
bool FirstClick = true;
bool WaitForUnclick = false;
bool Cycle_Complete = false; //A complete cycle is done : A click followed by unclick
bool LongPress = false;
bool IN_Debounce_Click = false;
bool IN_Debounce_Unclick = false;
bool Valid_Button = false;
bool S1_Click = false;
bool S2_Click = false;
bool S3_Click = false;
bool S4_Click = false;
bool S1_LongP = false;
bool S2_LongP = false;
bool S3_LongP = false;
bool S4_LongP = false;
int Debounce_Count = 0;
int Debounce_Count_Unclick = 0;
const int Debounce_Count_Target = 50; //Same value read target
const int Debounce_Count_Unclick_Target = 20;
const int LongPressTime = 1000; //If switch is pressed for more then 1 second LongPress = true
void setup()
{
Serial.begin(9600);
SW_timer.start();
Debouncetimer.start();
}
void loop()
{
if(Debouncetimer.done()){
ReadKeyPress();{
if (SW>0){
Serial.println(SW);
Debouncetimer.start();
}
}
}
}
void ReadKeyPress()
{
DecodeKey();
}
void DecodeKey(){
int value = 0;
value = (analogRead(ANALOG_PIN));
T0 = abs(value-SW0);
T1 = abs(value-SW1);
T2 = abs(value-SW2);
T3 = abs(value-SW3);
T4 = abs(value-SW4);
if (value <20) {
SW=0;
}
else if (T1 < T2){ SW = 1;}
else if (T2 < T3){ SW = 2;}
else if (T3 <T4){ SW = 3;}
else {SW=4;}
}