/*
* This ESP32 code is created by esp32io.com
*
* This ESP32 code is released in the public domain
*
* For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-keypad-lcd
*/
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#define ROW_NUM 4 // four rows
#define COLUMN_NUM 4 // four columns
uint8_t valIndex;
uint8_t cursorPos;
char entered_value [6];
uint8_t state=0;;
int val1=0,val2=0;
char keys[ROW_NUM][COLUMN_NUM] = {
{'1','2','3', 'A'},
{'4','5','6', 'B'},
{'7','8','9', 'C'},
{'*','0','#', 'D'}
};
byte pin_rows[ROW_NUM] = {12, 14, 27, 26}; // GPIO19, GPIO18, GPIO5, GPIO17 connect to the row pins
byte pin_column[COLUMN_NUM] = {25, 33, 32, 35}; // GPIO16, GPIO4, GPIO0, GPIO2 connect to the column pins
Keypad keypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM );
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 column and 2 rows
int cursorColumn = 0;
void enterTime()
{
state = 1;
memset(&entered_value[0], 0, sizeof(entered_value));
cursorPos = 0;
valIndex = 0;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Set clock then ");
lcd.setCursor(0, 1);
lcd.print("press # to save.");
delay(3000);
lcd.clear();
}
void enterAlarm()
{
state = 2;
memset(&entered_value[0], 0, sizeof(entered_value));
cursorPos = 0;
valIndex = 0;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter alarm time");
lcd.setCursor(0, 1);
lcd.print("press # to save.");
delay(3000);
lcd.clear();
}
void nextChar(char key)
{
if (valIndex < 6)
{
entered_value[valIndex] = key;
lcd.setCursor(0, 0);
lcd.print(entered_value);
cursorPos++;
valIndex++;
}
}
void eraseChar()
{
if (valIndex > 0 )
{
valIndex--;
cursorPos--;
entered_value[valIndex] = '\0';
lcd.setCursor(cursorPos, 0);
lcd.print(' ');
lcd.setCursor(cursorPos, 0);
}
}
void keyPadState0()
{
char key = keypad.getKey();
switch(key)
{
case '#':
enterAlarm();
break;
case '*':
enterTime();
break;
}
}
void keyPadState1()
{
char key = keypad.getKey();
switch(key)
{
case '#':
val1=atoi(entered_value);
state = 0;
break;
case '*':
eraseChar();
break;
default:
if (isDigit(key))
{
nextChar(key);
}
break;
}
}
void keyPadState2()
{
char key = keypad.getKey();
switch(key)
{
case '#':
val2=atoi(entered_value);
state = 0;
break;
case '*':
eraseChar();
break;
default:
if (isDigit(key))
{
nextChar(key);
}
break;
}
}
void getInput()
{
switch (state)
{
case 0:
keyPadState0();
break;
case 1:
keyPadState1();
break;
case 2:
keyPadState2();
break;
}
}
void setup(){
lcd.init(); // initialize the lcd
lcd.backlight();
}
void loop(){
char key = keypad.getKey();
/* if (key) {
lcd.setCursor(cursorColumn, 0); // move cursor to (cursorColumn, 0)
lcd.print(key); // print key at (cursorColumn, 0)
cursorColumn++; // move cursor to next position
if(cursorColumn == 16) { // if reaching limit, clear LCD
lcd.clear();
cursorColumn = 0;
}
}*/
if (state == 0)
{
getInput(); }
}