The Real-Time Clock (RTC) DS1307 is a low-power, full binary-coded decimal (BCD) clock/calendar with 56 bytes of NV SRAM. It provides precise timekeeping with a built-in 32.768 kHz crystal oscillator. The DS1307 communicates with microcontrollers via an I2C interface. Common applications include timekeeping in embedded systems, data loggers, clocks, and other devices that require an accurate time base.
Pin Number | Name | Description |
---|---|---|
1 | GND | Ground pin, connected to the system ground |
2 | Vbat | Battery input for any standard 3V lithium cell or other energy source |
3 | Vcc | Main power supply; should be between 4.5V and 5.5V |
4 | SDA | Serial Data Line for I2C communication |
5 | SCL | Serial Clock Line for I2C communication |
6 | SQW/OUT | Square Wave/Output Driver (configurable) |
7 | X1 | Input to the 32.768 kHz crystal oscillator |
8 | X2 | Output from the 32.768 kHz crystal oscillator |
#include <Wire.h>
#include <RTClib.h>
RTC_DS1307 rtc;
void setup() {
Serial.begin(9600);
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (!rtc.isrunning()) {
Serial.println("RTC is NOT running!");
// Following line sets the RTC to the date & time this sketch was compiled
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop() {
DateTime now = rtc.now();
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(" ");
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
delay(1000);
}
rtc.adjust()
function sparingly to avoid wearing out the RTC's internal oscillator calibration.Q: Can the DS1307 be used in a 3.3V system? A: The DS1307 is designed for 5V systems, but it can work at 3.3V with proper level shifting for I2C lines.
Q: How long will the RTC keep time on battery backup? A: This depends on the battery capacity and the quality of the crystal. Typically, it can last for several years.
Q: Is it necessary to use an external crystal with the DS1307? A: Yes, the DS1307 requires an external 32.768 kHz crystal to function properly.
Q: Can the DS1307 be used to generate interrupt signals? A: Yes, the SQW/OUT pin can be configured to output a square wave signal which can be used as an interrupt source.