#include "pico/stdlib.h"
#include "hardware/i2c.h"
#include <stdio.h>
// Define I2C pins and DS1307 address
#define SDA_PIN 4 // GPIO pin for I2C SDA
#define SCL_PIN 5 // GPIO pin for I2C SCL
#define I2C_ADDR 0x68 // I2C address of the DS1307 RTC
// Function to set the date and time on the DS1307
void set_date_time() {
// Arrays to store register addresses and corresponding values
uint8_t second[2] = {0x00, 0x00}; // Register 0x00: Seconds (set to 0)
uint8_t minute[2] = {0x01, 0x27}; // Register 0x01: Minutes (set to 27)
uint8_t hour[2] = {0x02, 0x0D}; // Register 0x02: Hours (set to 13 in 24-hour format)
uint8_t day[2] = {0x04, 0x24}; // Register 0x04: Day of the month (set to 24)
uint8_t month[2] = {0x05, 0x09}; // Register 0x05: Month (set to September)
uint8_t year[2] = {0x06, 0x24}; // Register 0x06: Year (set to 2024)
// Array of pointers to the register-value pairs
uint8_t *datetime[] = {second, minute, hour, day, month, year};
// Iterate over the array and write each register-value pair to the DS1307
for (int i = 0; i < 6; i++) {
i2c_write_blocking(i2c0, I2C_ADDR, datetime[i], 2, false);
}
}
// Function to read the date and time from the DS1307
void read_date_time(uint8_t *datetime) {
uint8_t initial_register = 0x00; // Start reading from register 0x00 (seconds)
i2c_write_blocking(i2c0, I2C_ADDR, &initial_register, 1, true); // Send the starting register address
i2c_read_blocking(i2c0, I2C_ADDR, datetime, 7, false); // Read 7 bytes (seconds, minutes, hours, day of week, day, month, year)
}
// Main function
int main() {
stdio_init_all(); // Initialize standard I/O for USB communication
i2c_init(i2c0, 100 * 1000); // Initialize I2C with a 100 kHz clock speed
gpio_set_function(SDA_PIN, GPIO_FUNC_I2C); // Set SDA pin to I2C function
gpio_set_function(SCL_PIN, GPIO_FUNC_I2C); // Set SCL pin to I2C function
gpio_pull_up(SDA_PIN); // Enable pull-up resistor on SDA pin
gpio_pull_up(SCL_PIN); // Enable pull-up resistor on SCL pin
set_date_time(); // Set the initial date and time on the DS1307
while (true) {
uint8_t datetime[7]; // Array to store the date and time values
read_date_time(datetime); // Read the current date and time from the DS1307
// Print the date and time to the console
printf("\nData: %02x/%02x/%02x - Horário: %02x:%02x:%02x\n",
datetime[4], datetime[5], datetime[6], // Day, Month, Year
datetime[2], datetime[1], datetime[0]); // Hour, Minute, Second
sleep_ms(5000); // Wait for 5 seconds before reading again
}
}