working-with-code-experiments

Code Breakdown

The code for this project retrieves time data from the DS3231 RTC module and displays it on a 16x2 LCD. Let's break down the code into sections:

1. Including Libraries

We begin by including the necessary libraries:


// Include necessary libraries
#include 
#include 
#include 
            

2. Initializing the RTC and LCD

Next, we declare and initialize the RTC and LCD objects:


// Initialize the RTC and LCD
RTC_DS3231 rtc;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
            

3. Setup Function

The setup() function initializes the LCD, RTC, and checks if the RTC is functional:


void setup() {
  // Start the LCD and RTC
  lcd.begin(16, 2);
  Wire.begin();
  
  if (!rtc.begin()) {
    lcd.print("RTC error!");
    while (1); // Halt if RTC is not connected
  }
  
  if (rtc.lostPower()) {
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // Set time to compile time
  }
}
            

4. Loop Function

The loop() function continuously retrieves the time from the RTC and displays it on the LCD:


void loop() {
  // Get the current time
  DateTime now = rtc.now();
  
  // Display the current time
  lcd.setCursor(0, 0);
  lcd.print("Time: ");
  lcd.print(now.hour(), DEC);
  lcd.print(':');
  lcd.print(now.minute(), DEC);
  lcd.print(':');
  lcd.print(now.second(), DEC);
  
  // Display the date
  lcd.setCursor(0, 1);
  lcd.print("Date: ");
  lcd.print(now.day(), DEC);
  lcd.print('/');
  lcd.print(now.month(), DEC);
  lcd.print('/');
  lcd.print(now.year(), DEC);
  
  delay(1000); // Refresh the display every second
}
            

Conclusion

By following this tutorial, you have learned how to create a basic digital clock using an Arduino, DS3231 RTC module, and a 16x2 LCD display. This simple project is perfect for beginners and can be expanded with additional features, such as alarms or a more complex user interface.

Contact Us

If you have any questions or inquiries, feel free to reach out to us at Microautomation.no@icloud.com .

Follow our Socials for the newest updates!