#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SD.h>
const int chipSelect = 10; // CS pin of SD card module
const int saveButtonPin = 2; // Pin for save button
const int viewButtonPin = 3; // Pin for view button
LiquidCrystal_I2C lcd(0x27, 16, 2); // Address 0x27, 16 columns and 2 rows
File dataFile;
void setup() {
Serial.begin(9600);
while (!Serial) {
; // Wait for serial port to connect
}
pinMode(chipSelect, OUTPUT);
pinMode(saveButtonPin, INPUT_PULLUP); // Set save button pin as input with internal pull-up resistor
pinMode(viewButtonPin, INPUT_PULLUP); // Set view button pin as input with internal pull-up resistor
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("SD Card Test");
// Initialize SD card
if (!SD.begin(chipSelect)) {
lcd.setCursor(0, 1);
lcd.print("Initialization failed!");
Serial.println("Initialization failed!");
while (1); // Stop here if SD card initialization fails
}
lcd.setCursor(0, 1);
lcd.print("Initialization done.");
Serial.println("Initialization done.");
}
void loop() {
if (digitalRead(saveButtonPin) == LOW) { // Check if save button is pressed
saveTextToSDCard(); // Call function to save text to SD card
}
if (digitalRead(viewButtonPin) == LOW) { // Check if view button is pressed
viewTextOnLCD(); // Call function to view text on LCD
}
}
void clearTextFile() {
// Remove existing file
SD.remove("data.txt");
// Create new empty file
File dataFile = SD.open("data.txt", FILE_WRITE);
if (dataFile) {
dataFile.close();
Serial.println("Text file cleared successfully.");
} else {
Serial.println("Error clearing text file.");
}
}
void saveTextToSDCard() {
clearTextFile();
lcd.clear();
lcd.print("Saving...");
dataFile = SD.open("data.txt", FILE_WRITE); // Open file
if (dataFile) {
dataFile.println("Mayang Pango"); // Write text to file
dataFile.close(); // Close file
lcd.clear();
lcd.print("Saved successfully");
delay(2000);
lcd.clear();
} else {
lcd.clear();
lcd.print("Error saving");
Serial.println("Error saving");
delay(2000);
lcd.clear();
}
}
void viewTextOnLCD() {
lcd.clear();
lcd.print("Viewing...");
dataFile = SD.open("data.txt"); // Open file
if (dataFile) {
lcd.clear(); // Clear the LCD before displaying the text
while (dataFile.available()) {
lcd.write(dataFile.read()); // Read from file and print on LCD
}
dataFile.close(); // Close file
delay(5000); // Display for 5 seconds
lcd.clear();
} else {
lcd.clear();
lcd.print("Error viewing");
Serial.println("Error viewing");
delay(2000);
lcd.clear();
}
}