// https://forum.arduino.cc/t/reading-switch-with-resistors-to-analog-input-break-before-make-issue/1265837
// https://wokwi.com/projects/399305157246238721
void setup()
{
Serial.begin(115200);
Serial.println("Jello Whirled!\n");
}
unsigned long now;
void loop() {
now = millis();
static unsigned long timer;
static int oldReading = -1;
static int stableValue;
static int oldStableValue = -1;
// debounce
int newReading = getVal();
if (newReading && newReading != oldReading) {
timer = now;
oldReading = newReading;
}
if (now - timer > 500)
stableValue = newReading;
// transition detect
if (stableValue && stableValue != oldStableValue) {
Serial.print("switch has become ");
Serial.println(stableValue);
oldStableValue = stableValue;
}
}
int getVal()
{
int val = analogRead(A0);
switch (val) {
case 0 ... 150 :
val = 1;
break;
case 200 ... 350 :
val = 2;
break;
case 400 ... 550 :
val = 3;
break;
case 600 ... 750 :
val = 4;
break;
case 800 ... 950 :
val = 5;
break;
default :
val = 0;
break;
}
return val;
}