All of my digital pins are occupied and I want to use the analog input pins of Arduino Nano for the push button, it is connected to GND and A6.
At first I have this code...
const int buttonPin = A6;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
int buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
Serial.println("Button pressed!");
} else {
Serial.println("Button not pressed.");
}
delay(50);
}
but since, Nano's analog input pins don't have a pull-up resistor, I can't use the PULL_UP, I also found that the analog input pins of Nano are for analog input only. Therefore I am having a hard time using these pins for the push button as it is having fluctuations.
Is there a way for this to work? or Is there any way around this?
You can use the Nano analogue pins A0 to A5 as digital pins, including using INPUT_PULLUP in pinMode() but pins A6 and A7 can only be used as analogue inputs, not digital
All of my analog pins are occupied for digitalWrite() and I only have A6 and A7 for my buttons. Is there a way that I can use analogRead() in a better way, so that I can use the push buttons without having floating issues.
yes! I scan up to 20 buttons without an issue on A7. I'll post a snippet scan routine later today, unless someone else beats me to it. It's not dead simple, but it can be made to work.
I use a 2.2kohm pullup, a 2.2 nF filter capacitor, and an array of 10% standard value resistors, a unique value for each button. In combination with the pullup, this results in a unique value for the ADC conversion; a lookup table is used to determine which button is pressed. I'll post the values as well; if chosen with some care, one can maintain more than 35 ADC counts between buttons, which makes them easily identifiable.
Locate the unique resistors with the buttons. This results in a 2-wire keypad lead. The shorter this is the better, though the capacitor seems to handle noise pretty well.
caveat: You must, obviously, only press one button at any one time. No multi-press, no n-button-rollover, etc. etc.
I presume there's no interest in the multibutton option, so the short answer to your question is, use an external pullup resistor for each of A6 and A7, and
`
buttonstateA6 = readAnalog(A6)>511?1:0;
buttonstateA7 = readAnalog(A7)>511?1:0;
`
Should be all you need.