// https://wokwi.com/projects/366355145922817025
// for https://forum.arduino.cc/t/loop-count-0-100-and-then-100-0/1133580
// based on
// 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
// See also https://forum.arduino.cc/t/wokwi-simulations-for-arduino-built-in-examples/1304754/14?u=davex
const byte potentiometerPin = A0; // the pin that the potentiometer is attached to
// 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("Act analog potentiometer changes with hysteresis");
}
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);
// hysteresis by adjusting sensed value:
if(abs(potentiometerState - lastPotentiometerState) < 3){
potentiometerState = lastPotentiometerState;
}
// compare the buttonState to its previous state
if (potentiometerState != lastPotentiometerState)
{
// On potentiometer change:
Serial.print("Pot:");
Serial.print(potentiometerState);
Serial.print(' ');
}
// save the current state as the last state,
//for next time through the loop
lastPotentiometerState = potentiometerState;
}
}