#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/i2c.h"
#define I2C_PORT i2c0
#define SDA_PIN 20
#define SCL_PIN 21
#define DS1307_ADDRESS 0x68
uint8_t dec_to_bcd(uint8_t val) {
return ((val / 10) << 4) | (val % 10);
}
uint8_t bcd_to_dec(uint8_t val) {
return ((val >> 4) * 10) + (val & 0x0F);
}
void set_rtc_datetime() {
uint8_t data[7];
data[0] = 0x00;
data[1] = dec_to_bcd(0);
data[2] = dec_to_bcd(27);
data[3] = dec_to_bcd(13);
data[4] = dec_to_bcd(24);
data[5] = dec_to_bcd(9);
data[6] = dec_to_bcd(24);
i2c_write_blocking(I2C_PORT, DS1307_ADDRESS, data, 7, false);
sleep_ms(10);
}
void read_rtc_datetime() {
uint8_t buffer[6];
uint8_t reg = 0x00;
i2c_write_blocking(I2C_PORT, DS1307_ADDRESS, ®, 1, true);
i2c_read_blocking(I2C_PORT, DS1307_ADDRESS, buffer, 6, false);
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 = bcd_to_dec(buffer[3]);
uint8_t month = bcd_to_dec(buffer[4]);
uint16_t year = bcd_to_dec(buffer[5]) + 2000;
printf("Date: %02d/%02d/%04d - Time: %02d:%02d:%02d\n",
day, month, year, hours, minutes, seconds);
}
int main() {
stdio_init_all();
i2c_init(I2C_PORT, 100000);
gpio_set_function(SDA_PIN, GPIO_FUNC_I2C);
gpio_set_function(SCL_PIN, GPIO_FUNC_I2C);
gpio_pull_up(SDA_PIN);
gpio_pull_up(SCL_PIN);
sleep_ms(2000);
printf("Setting up RTC...\n");
set_rtc_datetime();
while (1) {
read_rtc_datetime();
sleep_ms(5000);
}
return 0;
}