I'm trying to hook up 4 Momentary switches and have some simple output telling me which switch is pressed/released but I'm getting some very odd behavior. I get a lot of false reads on pin 2, should I not use this one? I'm wondering if there are 4 better pins?
I've attached my program in case someone has a better idea how to do what I'm doing.
Thanks,
BlackNoir
int switches[] = {2, 5, 6, 7};
int val; // variable for reading the pin status
int buttonState[] = {LOW, LOW, LOW, LOW}; // variable to hold the last button state
void setup() {
Serial.begin(9600); // Set up serial communication at 9600bps
for (int i = 0; i < 4; i++) {
pinMode(switches[i], INPUT); // Set the switch pin as input
buttonState[i] = digitalRead(switches[i]); // read the initial state
}
}
void loop(){
for (int i = 0; i < 4; i++) {
val = digitalRead(switches[i]); // read input value and store it in val
if (val != buttonState[i]) { // the button state has changed!
if (val == LOW) {
Serial.print("Button ");
Serial.print(i);
Serial.println(" just released");
} else {
Serial.print("Button ");
Serial.print(i);
Serial.println(" just pressed");
}
buttonState[i] = val;
}
}
}
Could you say how you've wired up the switches? Have you used pull-up or pull-down resistors? Are the switches wired to 5V or Ground? Maybe you could show us a simple diagram?
Your switch wiring looks fine for either case. However your choice of pins may be in conflict with the serial pins used by the Arduino and you are using serial commands that use digital pins 0 and 1.
Try using pins 2 through 5 for your input switches. Also you should read up on switch debouncing as you are sure to be reading 'bouncing' values as you have no delay in your digital reading steps.
Just a point, there is no need for that 100 ohm resistor in line with the input. It is only adding to the noise.
While the series resistor adds no advantage when the pin is used as a input like here, I've always considered it good insurance against my occasional brain farts. If the pin was set to be a output pin and set high and then the button was pressed (in the grounding switch example) it would short output the pin and most likely damage it.
Again not needed once a design is fixed but not bad insurance when say bread-boarding a project and make lots of quick changes. I would make it a 220 ohm resistor however. It's not unlike the series resistors that the Arduino design places between pins 0 & 1 to the USB serial converter chip to protect the USB chip's data pins.