// by groundfungus in https://forum.arduino.cc/t/a-multifunction-button/1131935/6
// DaveX modified to demonstrate using similar logic on change in an analog signal
// Simulation demo at https://wokwi.com/projects/365991099114946561
const byte potentiometerPin = A0; // the pin that the potentiometer is attached to
const int Hysteresis = 2;
// switch wired to ground and input
// Variables will change:
int buttonPushCounter = 0; // counter for the number of zeros detected presses
void setup()
{
// initialize the button pin as a input, enable the internal pullup resistor:
pinMode(potentiometerPin, INPUT);
// initialize serial communication:
Serial.begin(9600);
Serial.println("Use analog potentiometer at 0 as switch to cycle through 4 color choices");
Serial.println(" (using state-change detection on the analog signal)");
}
void loop()
{
static int lastPotentiometerState = 0; // previous state of the button
static unsigned long timer = 0;
unsigned long interval = 50;
if (millis() - timer >= interval)
{
timer = millis();
// read the potentiometer input pin:
int potentiometerState = analogRead(potentiometerPin);
// compare the buttonState to its previous state
if (abs(potentiometerState - lastPotentiometerState) > Hysteresis)
{
// On potentiometer change:
Serial.print("Pot:");
Serial.print(potentiometerState);
Serial.print(' ');
if (potentiometerState == 0) // treat as button push
{
// if the current state is LOW then the button
// went from off to on:
buttonPushCounter++; // add one to counter
if (buttonPushCounter > 3) // if couter over 3 reset the counter to 0 all off
{
buttonPushCounter = 0;
}
Serial.print("Button Push Counter = ");
Serial.println(buttonPushCounter);
Serial.print("color = ");
switch (buttonPushCounter)
{
case 0:
Serial.println("Black");
break;
case 1:
Serial.println("Red");
break;
case 2:
Serial.println("Green");
break;
case 3:
Serial.println("Blue");
break;
}
}
}
// save the current state as the last state,
//for next time through the loop
lastPotentiometerState = potentiometerState;
}
}