Hi all.
I am trying to read the values of button presses using just one digital input pin. My approach is to power the buttons using digital pins as output and only turn on one output pin at a time, cutting the power to the button so as to not read from it when its off. This works well when I press one button at a time and I receive the expected output. However, when I hold down both buttons what I'm expecting to read is:
Slot: 0
start buttonState: 1
Power Pin 2 forward is high
End buttonState: 0
Slot: 1
start buttonState: 1
Power Pin 13 forward is high
End buttonState: 0
but instead what I receive is:
Slot: 0
start buttonState: 0
End buttonState: 0
Slot: 1
start buttonState: 0
End buttonState: 0
Also, this is not always consistent. Sometimes while holding both one will still read as high but not both. I understand I'm using an unorthodox method so I suspect they may be what is causing problems for me. I have seen other methods of using just one pin for multiple buttons so I am aware I have other options, I'm just curious if this method is even feasible. I've provided a circuit diagram (I'm using 10k resistors for pull-down) and my code below. Any help is very appreciated!
const int powerPins[2] = { 2, 13 };
int buttonPin = 4;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
for (int i = 0; i < 2; i++) {
pinMode(powerPins[i], OUTPUT);
}
digitalWrite(powerPins[0], HIGH); //turn first slot on
digitalWrite(powerPins[1], LOW); //turn others off
}
void loop() {
for (int i = 0; i < 2; i++) {
Serial.println("Slot: " + String(i));
Serial.println("start buttonState: " + String(digitalRead(buttonPin))); //for troubleshooting
if (digitalRead(buttonPin) == HIGH ) {
Serial.print("Power Pin ");
Serial.print(powerPins[i]);
Serial.println(" forward is high");
}
digitalWrite(powerPins[(i + 1) % 2], HIGH); // turn the neighbouring pin on
digitalWrite(powerPins[i], LOW); //turn off current power pin so we dont read this button
Serial.println("End buttonState: " + String(digitalRead(buttonPin)));
}
delay(1000);
}
This is just a simplified scenario. Its for a school project and i need more than the alloted pins so im trying to save on using pins. As for frying the arduino I have tried and ran this program and the arduino seems to be working fine.
I understand now, sorry for the miscommunication on my part. I have a different setup for my project which is 4 slots with 3 strips of copper tape laid on one side and 1 strip of copper tape on the other side. The three strips are my inputs(3x4=12) and the one strip on the other side is the power pin so i only need 4 power pins. I then have blocks with copper tape on the bottom so when i place it into a slot depending on the block it turns a pin high. It works for the most part expect when i put in two blocks that are the same. I just used this scenario as an example to simplify it