#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/i2c.h"
#include "pico/cyw43_arch.h"
#define I2C_ADDR 0x68
static uint8_t decToBcd(uint8_t val) {
return ((val / 10 * 16) + (val % 10));
}
static uint8_t bcdToDec(uint8_t val) {
return ((val / 16 * 10) + (val % 16));
}
int main() {
stdio_init_all();
// Configura I2C
i2c_init(i2c0, 100 * 1000); // Inicializa I2C0 a 100kHz
gpio_set_function(4, GPIO_FUNC_I2C); // SDA
gpio_set_function(5, GPIO_FUNC_I2C); // SCL
gpio_pull_up(4); // Habilita pull-up para SDA
gpio_pull_up(5); // Habilita pull-up para SCL
// Configura RTC (seta data hora no formato bcd)
uint8_t bcd_date[] = {0x00, decToBcd(00), decToBcd(27), decToBcd(24 + 13),
decToBcd(3), decToBcd(24), decToBcd(9), decToBcd(24)};
i2c_write_blocking(i2c0, I2C_ADDR, bcd_date, 8, true);
while (true) {
uint8_t read_req[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
uint8_t read_date[7] = {0};
// Requisita o dado e ler o dado de data hora
for (int i = 0; i < 7; i++) {
i2c_write_blocking(i2c0, I2C_ADDR, &read_req[i], 1, false);
i2c_read_blocking(i2c0, I2C_ADDR, &read_date[i], 1, false);
}
// Imprime
printf("%d/%d/20%d %d:%d:%d\n",
bcdToDec(read_date[4]), bcdToDec(read_date[5]), bcdToDec(read_date[6]),
bcdToDec(read_date[2]), bcdToDec(read_date[1]), bcdToDec(read_date[0]));
sleep_ms(5000);
}
}