#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/i2c.h"
#define DS1307_ADDR 0x68
#define I2C_PORT i2c0
// Convert decimal to BCD
uint8_t dec_to_bcd(uint8_t val) {
return ((val / 10 * 16) + (val % 10));
}
// Convert BCD to decimal
uint8_t bcd_to_dec(uint8_t val) {
return ((val / 16 * 10) + (val % 16));
}
// Set date and time on DS1307
void set_datetime() {
uint8_t time_data[] = {
0x00, // Register address (start of time registers)
dec_to_bcd(0), // Seconds
dec_to_bcd(27), // Minutes
dec_to_bcd(13), // Hours (24-hour mode)
dec_to_bcd(3), // Day of week
dec_to_bcd(24), // Day of month
dec_to_bcd(9), // Month
dec_to_bcd(24) // Year
};
i2c_write_blocking(I2C_PORT, DS1307_ADDR, time_data, sizeof(time_data), false);
}
// Read date and time from DS1307
void read_datetime() {
uint8_t reg = 0x00; // Start from seconds register
uint8_t buffer[7];
// Set register pointer
i2c_write_blocking(I2C_PORT, DS1307_ADDR, ®, 1, true);
// Read 7 bytes
i2c_read_blocking(I2C_PORT, DS1307_ADDR, buffer, 7, false);
// Extract and convert data
uint8_t seconds = bcd_to_dec(buffer[0] & 0x7F);
uint8_t minutes = bcd_to_dec(buffer[1]);
uint8_t hours = bcd_to_dec(buffer[2] & 0x3F);
uint8_t day_of_week = bcd_to_dec(buffer[3]);
uint8_t day = bcd_to_dec(buffer[4]);
uint8_t month = bcd_to_dec(buffer[5]);
uint8_t year = bcd_to_dec(buffer[6]);
// Print formatted date and time
printf("Date: %02d/%02d/20%02d - Time: %02d:%02d:%02d\n",
day, month, year, hours, minutes, seconds);
}
int main() {
// Initialize stdio and I2C
stdio_init_all();
i2c_init(I2C_PORT, 100 * 1000); // 100 kHz
// Set GPIO pins for I2C
gpio_set_function(16, GPIO_FUNC_I2C); // SDA
gpio_set_function(17, GPIO_FUNC_I2C); // SCL
gpio_pull_up(16);
gpio_pull_up(17);
// Set initial datetime
set_datetime();
// Continuous reading
while (1) {
read_datetime();
sleep_ms(5000); // 5-second delay
}
return 0;
}