#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "hardware/i2c.h"
#define PICO_I2C_SDA_PIN 20
#define PICO_I2C_SCL_PIN 21
#define DS1307_ADDR 0x68
#define DS1307_REG_SECONDS 0x00
#define DS1307_REG_MINUTES 0x01
#define DS1307_REG_HOURS 0x02
#define DS1307_REG_DAYOFWEEK 0x03
#define DS1307_REG_DAY 0x04
#define DS1307_REG_MONTH 0x05
#define DS1307_REG_YEAR 0x06
uint8_t bcd_to_dec(uint8_t val) {
return (val >> 4) * 10 + (val & 0x0F);
}
uint8_t dec_to_bcd(uint8_t val) {
return ((val / 10) << 4) + (val % 10);
}
int main() {
stdio_init_all();
// Initialize I2C0 at 100kHz
i2c_init(i2c_default, 100 * 1000);
gpio_set_function(PICO_I2C_SDA_PIN, GPIO_FUNC_I2C);
gpio_set_function(PICO_I2C_SCL_PIN, GPIO_FUNC_I2C);
gpio_pull_up(PICO_I2C_SDA_PIN);
gpio_pull_up(PICO_I2C_SCL_PIN);
/* // --- Set Time (Optional - uncomment to set the time once) ---
uint8_t set_data[] = {
DS1307_REG_SECONDS, // Start writing from seconds register
dec_to_bcd(0), // Seconds
dec_to_bcd(55), // Minutes
dec_to_bcd(13), // Hours (24-hour format)
dec_to_bcd(5), // Day of Week (1–7, Sunday=1)
dec_to_bcd(2), // Day
dec_to_bcd(11), // Month
dec_to_bcd(2025 - 2000) // Year (last two digits)
};
i2c_write_blocking(i2c_default, DS1307_ADDR, set_data, sizeof(set_data), false);
*/
while (true) {
uint8_t read_data[7];
uint8_t reg_addr = DS1307_REG_SECONDS;
// Write the register address to start reading from
i2c_write_blocking(i2c_default, DS1307_ADDR, ®_addr, 1, true);
i2c_read_blocking(i2c_default, DS1307_ADDR, read_data, 7, false); // Read 7 bytes (seconds to year)
uint8_t seconds = bcd_to_dec(read_data[0] & 0x7F); // Mask CH bit
uint8_t minutes = bcd_to_dec(read_data[1]);
uint8_t hours = bcd_to_dec(read_data[2] & 0x3F); // Mask 12/24-hour bit
uint8_t day_of_week = bcd_to_dec(read_data[3]);
uint8_t day = bcd_to_dec(read_data[4]);
uint8_t month = bcd_to_dec(read_data[5]);
uint16_t year = bcd_to_dec(read_data[6]) + 2000; // Add 2000 for full year
printf("Time: %02d:%02d:%02d, Date: %02d/%02d/%04d (Day %d)\n",
hours, minutes, seconds, day, month, year, day_of_week);
sleep_ms(1000); // Read every second
}
return 0;
}