DS3231 RTC I2C(仅限 ESP-IDF/无线.h)

问题描述 投票:0回答:0

使用带 RTClib 的 Arduino 框架时,与 DS3231 RTC 的连接工作正常,所以我知道一切都已正确连接。但是,我的项目必须坚持只使用 ESP-IDF 框架,所以我必须适应他们的 I2C 库

这是我的最小代码:

#include "freertos/FreeRTOS.h"
#include "driver/i2c.h"

#define I2C_PORT I2C_NUM_0
#define I2C_SLAVE_ADDR 0x68
#define SDA_PIN 3
#define SCL_PIN 4

void initRTCI2C() {
    int i2c_master_port = I2C_PORT;
    i2c_config_t conf = {
        .mode = I2C_MODE_MASTER,
        .sda_io_num = SDA_PIN,
        .sda_pullup_en = GPIO_PULLUP_ENABLE,
        .scl_io_num = SCL_PIN,
        .scl_pullup_en = GPIO_PULLUP_ENABLE,
        .master.clk_speed = 100000,
        .clk_flags = I2C_SCLK_SRC_FLAG_FOR_NOMAL
    };
    i2c_param_config(i2c_master_port, &conf);
    i2c_driver_install(i2c_master_port, conf.mode, 0, 0, 0);
}

void readTime() {

    i2c_port_t i2c_num = I2C_PORT;

    uint8_t size = 7;
    uint8_t data_read[] = {0,0,0,0,0,0,0};
    uint8_t start_address[] = {0};

    esp_err_t err = i2c_master_write_read_device(i2c_num, I2C_SLAVE_ADDR, start_address, 1, data_read, size, pdMS_TO_TICKS(1000));
    if (err != ESP_OK) fprintf(stdout, "Err:%i\n", err);

    int i = 0;
    for(i=0;i<size;i++) {
        fprintf(stdout, "%x ", data_read[i]);
    }
    fprintf(stdout, "\n");
}

void app_main() {
    vTaskDelay(pdMS_TO_TICKS(5000));
    fprintf(stdout, "Start\n");
    initRTCI2C();
    
    while(1) {
        vTaskDelay(pdMS_TO_TICKS(2000));
        readTime();
    }
}

输出:

Start
Err:-1
0 0 0 0 0 0 0 
Err:-1
0 0 0 0 0 0 0 
Err:-1
0 0 0 0 0 0 0 
c esp32 i2c esp-idf
© www.soinside.com 2019 - 2024. All rights reserved.