My breadboard uses a 3x4 matrix keypad wired up in the usual way with resistors to give a one-wire analog output, together with a 2 line 20 character LCD display. The sketch to check the hardware is shown here (it works).
#include <OnewireKeypad.h> // OneWireKeypad Library
#include <LiquidCrystal.h> // Parallel LCD Library
char KEYS[]= { // Define keys values of Keypad
'1','2','3',
'4','5','6',
'7','8','9',
'*','0','#'
};
OnewireKeypad <Print, 12 > Keypad(Serial, KEYS, 4, 3, A0, 4700, 1000 );
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup ()
{
Serial.begin(9600);
lcd.begin(16, 2);
lcd.clear();
lcd.print("Key pressed");
}
void loop()
{
Keypad.SetHoldTime(200);
Keypad.SetDebounceTime(50);
if ((Keypad.Key_State() == 3)) // not pressed = 0, pressed = 1, released = 2, held = 3
{
char keypress = Keypad.Getkey();
int inKey = keypress-'0'; // Convert the character to an integer
lcd.setCursor(13,0);
lcd.print(inKey);
while ((Keypad.Key_State())){} // Stay here while Key is held down
}
}
When a key is pressed the number appears towards the right of the display. Obviously when a subsequent key is pressed the number overwrites the previous one. To do something useful (in this particular project - the quantity of water to be pumped), I need to enter a number between 1 and 9999 so that the digits shift to the left after being entered. When the number is correctly entered the key "#" (=-13) will tell the program to continue using this value. I've tried various ways to get this to work without success. I figure there must be a (simple) routine way of doing this that I have overlooked. Any advice would be very welcome!
PaulS: Thanks for your reply to my posting. I've modified my sketch to include your suggestions. Unfortunately it still doesn't seem to work.
Every time a key is pressed the 'if' statements are executed. However the next time the value of 'val' has been lost.
I would appreciate it if you could help me with this point.
#include <OnewireKeypad.h> // OneWireKeypad Library
#include <LiquidCrystal.h> // Parallel LCD Library
char KEYS[]= { // Define keys values of Keypad
'1','2','3',
'4','5','6',
'7','8','9',
'*','0','#'
};
OnewireKeypad <Print, 12 > Keypad(Serial, KEYS, 4, 3, A0, 4700, 1000 );
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup ()
{
Keypad.SetHoldTime(100);
Keypad.SetDebounceTime(50);
Serial.begin(9600);
lcd.begin(16, 2);
lcd.clear();
lcd.print("Key pressed");
}
void loop()
{
int val;
if ((Keypad.Key_State() == 3)) // not pressed = 0, pressed = 1, released = 2, held = 3
{
char keypress = Keypad.Getkey();
int inKey = keypress-'0';
lcd.setCursor(13,0);
lcd.print(inKey);
while ((Keypad.Key_State())){} // Stay here while Key is held down
val *= 10;
val += inKey;
lcd.clear();
lcd.print(val);
}
}
UKHeliBob: Thanks for pointing out the difference between global variables, static variables and variable scope. I should have studied this before, but now I'm sure I'm on the right track. My only excuse - a mis-spent youth programming in BASIC!