How can I detect when a button is pressed using an analog pin instead of a digital pin

This my second time making a topic because I put it in the wrong area.

5 posts were split to a new topic: New users can't flag? WTF?


In the diagram, move the connection from pin 2 to pin A0

void setup() {
  pinMode(A0, INPUT);
}
void loop() {
//if button is tied down to ground
if (analogRead(A0) == 1023) {
  //if button pressed, do code...
}
else {
  //if not pressed, do code...
}
}
1 Like

If you're talking about using an analog input for the same purpose as you would a digital-only input pin then know the analog inputs A0-A5 on an UNO also function as digital inputs. You set them up and read them just like the other digital pins except substitute Ax for the pin number.

If you mean two or more buttons on an analog input that's a different matter.

1 Like

No need for an external resistor if you use internal pull up.
Leo..

void setup() {
  pinMode (A0, INPUT_PULLUP); // switch between pin and ground, NO resistor
}
void loop() {
  if (!digitalRead(A0)) {
    //if button pressed, do code...
  } else {
    //if not pressed, do code...
  }
}

Hi, @drksoulk

What model Arduino, if its a Nano, A6 and A7 do not have internal pullups installed.

Thanks.. Tom... :smiley: :+1: :coffee: :australia:

As already mentioned, the correct way is to use digitalRead() and an internal pullup, if available.

If, for some reason, you chose to use analogRead(), this is quite risky:

Depending on your connections, the analog value for a button pressed can easily be a bit lower, so it'd be much safer to test against some threshold value:

if (analogRead(A0) > 512) {

Yeah, I didn't think about that. That should work better.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.