/*
Forum: https://forum.arduino.cc/t/button-and-potentiometer-detection-together/1417103
Wokwi: https://wokwi.com/projects/449056937416410113
Original code taken from the forum
2025/11/30
ec2021
*/
// Code for Arduino Uno
// Pin definitions
const int POT_PIN = A0; // Potentiometer connected to analog pin A0
const int BUTTON_PIN = 2; // Button connected to digital pin 2
// Variables
int potValue = 0; // Variable to store potentiometer value
int buttonState = 0; // Variable to store button state
int lastButtonState = 0; // Previous button state for detecting changes
// Timing variables
unsigned long lastPotRead = 0;
const int POT_READ_INTERVAL = 50; // Read potentiometer every 50ms
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set button pin as input with internal pull-up resistor
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.println("Arduino Ready!");
Serial.println("Reading potentiometer and button...");
}
void loop() {
// CHECK BUTTON FIRST (fast and frequent)
buttonState = digitalRead(BUTTON_PIN);
// Display button state immediately when it changes
if (buttonState != lastButtonState) {
if (buttonState == LOW) {
Serial.println(">>> BUTTON PRESSED! <<<");
} else {
Serial.println(">>> BUTTON RELEASED <<<");
}
lastButtonState = buttonState;
}
// Read potentiometer LESS FREQUENTLY (analogRead is slow!)
unsigned long currentTime = millis();
if (currentTime - lastPotRead >= POT_READ_INTERVAL) {
potValue = analogRead(POT_PIN);
Serial.print("Pot Value: ");
Serial.print(potValue);
Serial.print(" | Button: ");
Serial.println(buttonState == LOW ? "PRESSED" : "NOT PRESSED");
lastPotRead = currentTime;
}
// NO DELAY - this was blocking button detection!
}
// btw if the comments are a bit weird its because at first i was trying to fix this with ai, didnt work