In this lesson, you will learn how to use the RTC module, The DS1307 real-time clock is a low-power chip.
Address and data are transferred serially through an I2C, which can be used unless being connected to ESP32 with only three data cables. DS1307 provides seconds, minutes, hours, day, date, month, and year information. Timekeeping operation continues while the part operates from the backup supply.
You can click the blue text link to download the program file to your local device, and double-click the file to open it after the download is complete. Please note: Before opening the file, ensure that you have installed the Arduino IDE development environment and completed the installation of relevant components such as the board support package and driver corresponding to the ESP32.
Wire.begin(21, 22);
This statement initializes the I2C communication bus. The parameters are SDA (data line) and SCL (clock line) pin numbers respectively. ESP32 uses GPIO 21 and GPIO 22 by default.
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
Attempts to connect to the DS3231 module. If the connection fails, it prints an error message and enters an infinite loop to prevent the program from continuing execution.
String input = Serial.readStringUntil('\n');
input.trim();
Serial.readStringUntil('\n'): Reads data from the serial port until a newline character is encountered, returning the complete input stringinput.trim(): Removes whitespace characters (including spaces, newlines, tabs, etc.) from the beginning and end of the string, ensuring the input time format is clean and reliableint year = input.substring(0, 4).toInt();
int month = input.substring(5, 7).toInt();
int day = input.substring(8, 10).toInt();
int hour = input.substring(11, 13).toInt();
int minute = input.substring(14, 16).toInt();
int second = input.substring(17, 19).toInt();rtc.adjust(DateTime(year, month, day, hour, minute, second));
substring(start, end) to extract each time component from the input stringYYYY-MM-DD HH:MM:SS, exactly 19 charactersrtc.adjust() writes the parsed time to the DS3231 module, which continues to run with its built-in batterywhile (Serial.available() > 0) {
Serial.read();
}
Clears the serial buffer after setting the time to prevent residual data from affecting the next read operation.
now = rtc.now();
Serial.print("Raw data: ");
Serial.print(now.year()); Serial.print("-");
Serial.print(now.month()); Serial.print("-");
Serial.print(now.day()); Serial.print(" ");
Serial.print(now.hour()); Serial.print(":");
Serial.print(now.minute()); Serial.print(":");
Serial.print(now.second()); Serial.println("");
Calls rtc.now() every second to get the current time, and formats it as YYYY-MM-DD HH:MM:SS for output.
YYYY-MM-DD HH:MM:SS| ESP32 Pin | DS3231 Module Pin | Description |
|---|---|---|
| VCC (3.3V) | VCC | Power Supply Positive |
| GND | GND | Power Supply Negative |
| GPIO 21 | SDA | I2C Data Line |
| GPIO 22 | SCL | I2C Clock Line |