#include #include "esp_log.h" #include "driver/i2c.h" #include "i2c_sht3x.h" static const char *TAG = "i2c-sht3x";//"i2c-simple-example"; #define I2C_MASTER_SCL_IO GPIO_NUM_14//CONFIG_I2C_MASTER_SCL /*!< GPIO number used for I2C master clock */ #define I2C_MASTER_SDA_IO GPIO_NUM_4//CONFIG_I2C_MASTER_SDA /*!< GPIO number used for I2C master data */ #define I2C_MASTER_NUM 0 /*!< I2C master i2c port number, the number of i2c peripheral interfaces available will depend on the chip */ #define I2C_MASTER_FREQ_HZ 400000 /*!< I2C master clock frequency */ #define I2C_MASTER_TX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */ #define I2C_MASTER_RX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */ #define I2C_MASTER_TIMEOUT_MS 1000 /** * @brief i2c master initialization */ static esp_err_t i2c_master_init(void) { int i2c_master_port = I2C_MASTER_NUM; i2c_config_t conf = { .mode = I2C_MODE_MASTER, .sda_io_num = I2C_MASTER_SDA_IO, .scl_io_num = I2C_MASTER_SCL_IO, .sda_pullup_en = GPIO_PULLUP_ENABLE, .scl_pullup_en = GPIO_PULLUP_ENABLE, .master.clk_speed = I2C_MASTER_FREQ_HZ, }; i2c_param_config(i2c_master_port, &conf); return i2c_driver_install(i2c_master_port, conf.mode, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0); } // i2c_sht3x_task 任务。初始化 SHT3x工作于周期测量模式,获取环境温湿度数据 void i2c_sht3x_task(void* arg) { // 配置I2C0-主机模式,400K,指定 SCL-14,SDA-4 i2c_master_init(); uint8_t recv_dat[6] = {0}; float temperature = 0.0; float humidity = 0.0; ESP_LOGI(TAG, "esp32 sht3x project starting ……"); sht3x_reset(); // 复位SHT3X if(sht3x_init() == ESP_OK) // 初始化SHT3X(周期测量模式) ESP_LOGI(TAG, "sht3x init ok.\n"); else ESP_LOGE(TAG, "sht3x init fail.\n"); vTaskDelay(1000 / portTICK_PERIOD_MS); //延时1s 等待SHT3X传感器内部采样完成 for (;;) { if(sht3x_read_th_raw_dat(recv_dat) == ESP_OK) // 从SHT3X读取一次数据(周期测量模式下) { // 将SHT3X接收的6个字节数据进行CRC校验,并转换为温度值和湿度值 if(sht3x_dat2float(recv_dat, &temperature, &humidity) == 0) { ESP_LOGI(TAG, "temperature = %.2f ℃,humidity = %.2f %%RH", temperature, humidity); } else { ESP_LOGE(TAG, "crc check fail.\n"); } } else { ESP_LOGE(TAG, "read data from sht3x fail.\n"); } vTaskDelay(1000 / portTICK_PERIOD_MS); } } void app_main(void) { // 创建 i2c_sht3x_task 任务。初始化 SHT30工作于周期测量模式,获取环境温湿度数据 xTaskCreate(i2c_sht3x_task, "i2c_sht3x_task", 2048, NULL, 3, NULL); }