// https://wokwi.com/projects/427234882861614081
// for https://forum.arduino.cc/t/button-project-is-voltage-necessary/1369536/47
// See also:
// https://forum.arduino.cc/t/how-to-wire-and-program-a-button/1196000
// https://forum.arduino.cc/t/best-first-5-topics-to-read-to-reach-trust-level-1/1287592
// https://forum.arduino.cc/t/wokwi-simulations-for-arduino-built-in-examples/1304754
//
// Periodically poll the inputs to avoid bouncing
// Also do state-change detection on the polled inputs
//
const int SwitchPin = 2;
const int PotPin = A0;
int potVal = -1, lastPotVal = -1;
int switchVal = -1, lastSwitchVal = -1;
uint32_t now;
void setup() {
Serial.begin(115200);
pinMode(SwitchPin, INPUT_PULLUP);
}
void loop() {
now = millis();
if (pollIO()) {
if (switchVal != lastSwitchVal) {
Serial.print("Switch:");
Serial.println(switchVal);
lastSwitchVal = switchVal;
}
if (abs(potVal - lastPotVal) > 2) {
Serial.print("Pot:");
Serial.println(potVal);
lastPotVal = potVal;
}
}
}
bool pollIO() {
// Periodically poll the IO and store results
// return true if polled
const uint32_t PollInterval = 50;
static uint32_t lastIoMs = -PollInterval; // backdate for initialization
bool polled = false;
if (now - lastIoMs > PollInterval) {
lastIoMs = now;
switchVal = digitalRead(SwitchPin);
potVal = analogRead(PotPin);
//...
polled = true;
}
return polled;
}