#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_LINES 2
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
#define NO_KEY_PRESSED 15
#define KEYPAD_DDR DDRD
#define KEYPAD_PORT PORTD
#define KEYPAD_PIN PIND
volatile uint8_t pressed_key = NO_KEY_PRESSED;
volatile bool new_key_flag = false;
volatile uint8_t timer_milliseconds = 0;
void setup() {
//Serial.begin(115200);
// put your setup code here, to run once:
lcd.init();
lcd.backlight();
pinMode(10, OUTPUT);
KEYPAD_DDR = 0x78;
KEYPAD_PORT = 0xFF;
TCCR0A = (1 << WGM01);
TCCR0B = (1 << CS01) | (1 << CS00);
OCR0A = 250;
TIMSK0 = (1 << OCIE0A);
}
void loop() {
lcd.setCursor(0,0);
lcd.print("Pressed: ");
if(new_key_flag){
lcd.setCursor(9,0);
lcd.print(pressed_key);
new_key_flag = false;
}
//lcd.print(new_key_flag);
if(pressed_key == 15){
digitalWrite(10, HIGH);
}else{
digitalWrite(10, LOW);
new_key_flag = false;
}
//delay(30000);
//Serial.println(pressed_key);
}
uint8_t keypad_read(){
uint8_t shift_array[4]={0x77, 0x6F, 0x5F, 0x3F};
uint8_t key_code = NO_KEY_PRESSED;
for (uint8_t i = 0; i < 4 ; ++i){
KEYPAD_PORT = shift_array[i];
for (uint8_t j = 0 ; j < 4 ; ++j){
if ((KEYPAD_PIN & (1 << j)) == 0){
key_code = (i*4 + j);
/* Serial.print(key_code);
Serial.print(" ");*/
/*lcd.setCursor(9,0);
lcd.print(key_code);*/
}
}
}
KEYPAD_DDR = 0x78;
KEYPAD_PORT = 0xFF;
return key_code;
}
ISR(TIMER0_COMPA_vect){
TCNT0 = 250;
timer_milliseconds += 1;
if (timer_milliseconds >= 250){
if (new_key_flag == false){
pressed_key = keypad_read();
if ( pressed_key != NO_KEY_PRESSED) new_key_flag = true;
}
timer_milliseconds = 0;
}
}