Hi there. I'm trying to connect several switches to one single input. I handle them like the common "keypad" algorithm. I cycle through the outputs, reading the pin 22. This example code will explain it way better:
/**
* Connect pins 23,24,25 to pin 22. (place a switch in the cables so it gets easier to cut the cable, to detect the "switch change")
*/
int readInput(uint8_t pin) {
digitalWrite(pin,LOW);
int pstatus = digitalRead(22);
digitalWrite(pin,HIGH);
return 1 ^ pstatus;
}
setup(){
pinMode(22, INPUT_PULLUP);
digitalWrite(22, HIGH);
pinMode(23, OUTPUT);
pinMode(24, OUTPUT);
pinMode(25, OUTPUT);
}
loop(){
for (int i = 23;i<26;i++){
Serial.println(readInput(i));
}
That's not really the code, but it's the plain algorithm behind it.
The problem is... it doesn't work when more than 1 switch is closed at the same time. I thought this wouldn't happen, because I set to HIGH the output pin after I finish reading the input pin. Why does this happen? My logic is failing apart
Thanks for the suggestions. But I'm still fighting. It only works when "switch" is used. if I close one switch, all other switchs are also read as "closed".
My current read method:
int readGpioInput(uint8_t pin) {
pinMode(pin,OUTPUT);
digitalWrite(pin,LOW);
delay(1);
int pstatus = digitalRead(22);
pinMode(pin,INPUT_PULLUP);
return 1 ^ pstatus;
}
The schematics are pretty simple:
(using an arduino Mega 2560)
Can you make a schematic or drawing of your switches ?
To attach a picture, you can click on "Additional Options..." at the lower left of the text field when writing a post.
It should not be so hard to detect 1,2 or 3 buttons at the same time.
Are these 3 buttons all you want ? You are using 4 pins now for 3 buttons.
Or do you want to extend it into an array ? The keypad array doesn't need diodes, it scans column by column and everytime it reads all the rows.
What about using the Keypad library ? Arduino Playground - HomePage
You might use it the other way around : Make 22 low, and read 23,24 and 25.
But it should also work this way. I don't know why you can not read more button presses at the same time.
There are other possibilities, with diodes, and a resistor ladder for an analog input.
serial output (also works with more than one button pressed)
row 0 is 0
row 1 is 0
row 2 is 0
row 0 is 0
row 1 is 0
row 2 is 0
row 0 is 0
row 1 is 0
row 2 is 0
row 0 is 1 -------- button 1 pressed
row 1 is 0
row 2 is 0
row 0 is 1 --------
row 1 is 0
row 2 is 0
row 0 is 1 --------
row 1 is 0
row 2 is 0
row 0 is 0 -------- button 1 released
row 1 is 0
row 2 is 0
row 0 is 0
row 1 is 0
row 2 is 0
row 0 is 0
row 1 is 0
row 2 is 0
row 0 is 0
row 1 is 0
row 2 is 0
row 0 is 0
row 1 is 0
It's finally working. After the confirmation of SingTorch I found another bug in my code, which would explain some weird behavior when multiple switches were closed. I didn't use the keypad library because it was just a 3x1 matrix and was supposed to "just work"...