I've been trying to figure out why this isnt working, when I run it, it prints test even when I don't press a button. I'm sure its something related to the pinModes but I'm still learning. Thanks for any help!
int colPins[] = {5, 4, 3, 2};
int rowPins[] = {7, 6};
void setup() {
Serial.begin(9600);
for (int i = 0; i<sizeof(colPins)/sizeof(colPins[0]); i++) {
pinMode(colPins[i], OUTPUT);
digitalWrite(colPins[i], HIGH);
}
for (int i = 0; i<sizeof(rowPins)/sizeof(rowPins[0]); i++) {
pinMode(rowPins[i], INPUT);
digitalWrite(rowPins[i], LOW);
}
}
void loop() {
for (int i = 0; i<sizeof(rowPins)/sizeof(rowPins[0]); i++) {
if (digitalRead(rowPins[i])==HIGH) {
Serial.println('test');
}
}
}
Your inputs are floating. They could read HIGH or LOW. By chance, they are reading HIGH.
Have you successfully connected a single button to an Arduino and read if it is pressed or not pressed? If you do not understand about floating inputs, you won't be able to get a single button to work correctly.
You are expecting the row pins to read LOW when no button is pressed. But why should they? They are not connected to either 5V or ground. So they can do what they want. And that's usually going to be whatever you don't want
You need to prevent the input/row pins from floating. The easy way to do this is use mode INPUT_PULLUP. This will make sure they read HIGH when no button is pressed.
But then, in order to know when a button is pressed, you need them to change from HIGH to LOW. That means you need to set the column output pins to LOW.
then the digitalWrite(), because of a historical quirk, will turn INPUT_PULLUP back into INPUT, and you are back where you started. So remove that digitalWrite().