#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClib.h>
#include <SD.h>
// Initialize the LCD library with the I2C address
LiquidCrystal_I2C lcd(0x27, 20, 4);
RTC_DS1307 rtc;
const int button1 = 8; // Button to increment counter
const int button2 = 9; // Button to read data
const int button3 = 7; // Button to switch back to counting mode
const int chipSelect = 10;
int counter = 0;
bool readingMode = false;
File myFile;
void setup() {
// Initialize the LCD
lcd.begin(20, 4);
lcd.backlight();
// Initialize the RTC
if (!rtc.begin()) {
lcd.print("Couldn't find RTC");
while (1);
}
if (!rtc.isrunning()) {
lcd.print("RTC is NOT running!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
// Initialize the SD card
if (!SD.begin(chipSelect)) {
lcd.print("SD init failed!");
while (1);
}
// Set button pins as input
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
pinMode(button3, INPUT_PULLUP);
// Print initial message
lcd.setCursor(0, 0);
lcd.print("Pokreni uredjaj");
}
void loop() {
// Check if button 1 is pressed
if (digitalRead(button1) == LOW && !readingMode) {
counter++;
DateTime now = rtc.now();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Count: ");
lcd.print(counter);
lcd.setCursor(0, 1);
lcd.print(now.timestamp(DateTime::TIMESTAMP_DATE));
lcd.setCursor(0, 2);
lcd.print(now.timestamp(DateTime::TIMESTAMP_TIME));
delay(500); // Debounce delay
// Save to SD card
myFile = SD.open("count.txt", FILE_WRITE);
if (myFile) {
myFile.print("Count: ");
myFile.print(counter);
myFile.print(" Date: ");
myFile.print(now.timestamp(DateTime::TIMESTAMP_DATE));
myFile.print(" Time: ");
myFile.println(now.timestamp(DateTime::TIMESTAMP_TIME));
myFile.close();
} else {
lcd.clear();
lcd.print("Error opening file");
}
}
// Check if button 2 is pressed to read data
if (digitalRead(button2) == LOW) {
readingMode = true;
lcd.clear();
myFile = SD.open("count.txt");
if (myFile) {
while (myFile.available()) {
String line = myFile.readStringUntil('\n');
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(line.substring(0, 20)); // Display first 20 characters on the first line
lcd.setCursor(0, 1);
lcd.print(line.substring(20, 40)); // Display next 20 characters on the second line
lcd.setCursor(0, 2);
lcd.print(line.substring(40, 60)); // Display next 20 characters on the third line
lcd.setCursor(0, 3);
lcd.print(line.substring(60)); // Display the rest on the fourth line
delay(2000); // Display each line for 2 seconds
}
myFile.close();
} else {
lcd.print("Error opening file");
}
delay(500); // Debounce delay
}
// Check if button 3 is pressed to switch back to counting mode
if (digitalRead(button3) == LOW) {
readingMode = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Pokreni uredjaj");
delay(500); // Debounce delay
}
}