Button not working correctly. Static bool, Potentiometer. uno

this is confusing. the middle wire of a pot is typically the wiper that travels from the left to righ tterminals

if the middle is 5V and the right is ground, what happens if the wiper is turned all the way to the right connecting 5V to ground?

it's not really clear how you expect to use this circuit. it would make more sense to connect the wiper to A1, the right terminal to ground and wire the switch between the right terminal and 5V.

the input, A1 always be 0V if the button is not pressed. when the button is pressed, an analogRead (A1) would measure the setting of the wiper from 0-5V.

with the above approach, conditional could be executed while the button is pressed (no need for ledflag)

    if (digitalRead(button) == HIGH)  {
        int myDelay = analogRead(A1);
        int Led     = random (2 , 13);

        digitalWrite(Led, HIGH) ;     // turn on the random LED
        delay(myDelay);
        digitalWrite(Led, LOW);       // turn off that led
        delay(myDelay) ;              // delay off for amount of time it was on
    }

each iteration thru loop() where the button is HIGH toggles ledflag.

the following demonstrates recognizing a button state change and that it was pressed


const byte butPin = A1;
const byte ledPin = 13;

byte butLst;

void setup ()
{
    pinMode (ledPin, OUTPUT);
    digitalWrite (ledPin, HIGH);

    pinMode (butPin, INPUT_PULLUP);
    butLst = digitalRead (butPin);
}

void loop  ()
{
    byte but = digitalRead (butPin);
    if (butLst != but)  {
        butLst = but;
        delay (20);         // debounce

        if (LOW == but)
            digitalWrite (ledPin, ! digitalRead (ledPin));
    }
}
1 Like