#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <Wire.h>
#include <SD.h>
#include <SPI.h>

/* MICROSD CARD READER */
File myFile;

int pinCS = 10; // Pin 10 on Arduino Uno

/* DISPLAY */
LiquidCrystal_I2C lcd(0x27, 20, 4); // address, cols, rows

/* KEYPAD */
const byte KEYPAD_ROWS = 4; // four rows
const byte KEYPAD_COLS = 4; // four columns
// define the symbols on the buttons of the keypads
char keys[KEYPAD_ROWS][KEYPAD_COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'.', '0', '<', '>'}
};
byte rowPins[KEYPAD_ROWS] = {9, 8, 7, 6}; // connect to the row pinouts of the keypad
byte colPins[KEYPAD_COLS] = {5, 4, 3, 2}; // connect to the column pinouts of the keypad
// initialize an instance of class NewKeypad
Keypad customKeypad = Keypad(makeKeymap(keys), rowPins, colPins, KEYPAD_ROWS, KEYPAD_COLS);


String message = "";

/* CODE LOGIC */
void setup() {
  Serial.begin(9600);
  lcd.begin(20, 4);
  lcd.init();
  lcd.backlight();
  pinMode(pinCS, OUTPUT);
  

  // SD Card Initialization
  if (SD.begin())
  {
    lcd.print("SD card is ready to use.");
  } else
  {
    lcd.print("SD card initialization failed");
    return;
  }

  delay(2000);
  lcd.clear();
  delay(2000);
  
  // Create/Open file 
  myFile = SD.open("test.txt", FILE_WRITE);
  
  // if the file opened okay, write to it:
  if (myFile) {
    lcd.print("Writing to file...");
    delay(500);
    // Write to file
    lcd.clear();
    myFile.println("Testing text 1, 2 ,3...");
    delay(500);
    lcd.clear();
    myFile.close(); // close the file
    lcd.print("Done.");
  }
  // if the file didn't open, print an error:
  else {
    lcd.clear();
    lcd.print("error opening test.txt");
  }

  delay(2000);
  // Reading the file
  myFile = SD.open("test.txt");
  if (myFile) {
    lcd.clear();
    lcd.print("Read: ");
    delay(1000);
    // Reading the whole file
    while (myFile.available()) {
      // lcd.clear();

      lcd.print(char(myFile.read()));
      delay(50);
   }
    myFile.close();
  }
  else {
    lcd.clear();
    lcd.print("error opening test.txt");
  }
  

}

void loop() {
  // char customKey = customKeypad.getKey();
  // if (customKey) {
  //     lcd.print(customKey);    
  //   // switch () {}
  // }
}