I have an lcd, keypad, and a button connected to an arduino mega 2560.
For now forget about the lcd as that works perfectly....lets focus on the keypad and button.
The keypad works just fine when I run the example code. The button also works perfectly fine when I run the example code for it.
So everything will work when coded together....WRONG
Both work independently but when I use the keypad library in conjunction with the digitalRead() for the button it doesn't work. The keypad portion works just fine but the digitalRead seems to do nothing.
I am unable to find anything online where someone else had this exact problem!
My arduino is a 2560 if that makes any difference.
THIS CODE WORKS - THE BUTTON IS OPERATIONAL
#include <LiquidCrystal.h>
#include <Keypad.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(31, 41, 33, 35, 39, 37);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {22, 32, 30, 26}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {24, 53, 44}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup() {
lcd.begin(20, 4);
lcd.print("Will the button work?");
Serial.begin(9600);
digitalWrite(52,LOW);
pinMode(52,INPUT);
}
void loop() {
buttonState = digitalRead(52);
if(buttonState != lastButtonState)
{
if(buttonState == HIGH){
lcd.print("SWITCH ON");
}else{
lcd.print("SWITCH OFF");
}
}
lastButtonState = buttonState;
}
THIS CODE DOES NOT WORK - ALL I ADDED WAS THE KEYPAD IF STATEMENT! It starts up, and the lcd prints switch off. Flip the switch on and nothing happens. Type on the keypad and it updates the lcd with keypad characters. It makes no sense.
#include <LiquidCrystal.h>
#include <Keypad.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(31, 41, 33, 35, 39, 37);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {22, 32, 30, 26}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {24, 53, 44}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup() {
lcd.begin(20, 4);
lcd.print("Will the button work?");
Serial.begin(9600);
digitalWrite(52,LOW);
pinMode(52,INPUT);
}
void loop() {
char key = keypad.getKey();
if (key){
lcd.print(key);
}
buttonState = digitalRead(52);
if(buttonState != lastButtonState)
{
if(buttonState == HIGH){
lcd.print("SWITCH ON");
}else{
lcd.print("SWITCH OFF");
}
}
lastButtonState = buttonState;
}