ESP32-idf读取sht30代码
时间: 2023-12-27 20:03:01 浏览: 255
以下是ESP32-idf读取SHT30温湿度传感器的代码示例:
```c
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/i2c.h"
#define I2C_MASTER_SCL_IO 22 /*!< GPIO number for I2C master clock */
#define I2C_MASTER_SDA_IO 21 /*!< GPIO number for I2C master data */
#define I2C_MASTER_NUM I2C_NUM_0 /*!< I2C port number for master dev */
#define I2C_MASTER_FREQ_HZ 100000 /*!< I2C master clock frequency */
#define SHT30_ADDRESS 0x44 /*!< I2C address for SHT30 sensor */
static void i2c_master_init()
{
i2c_config_t conf;
conf.mode = I2C_MODE_MASTER;
conf.sda_io_num = I2C_MASTER_SDA_IO;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.scl_io_num = I2C_MASTER_SCL_IO;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = I2C_MASTER_FREQ_HZ;
i2c_param_config(I2C_MASTER_NUM, &conf);
i2c_driver_install(I2C_MASTER_NUM, conf.mode, 0, 0, 0);
}
static esp_err_t i2c_master_sht30_read(uint8_t* data, size_t size)
{
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (SHT30_ADDRESS << 1) | I2C_MASTER_WRITE, true);
i2c_master_write_byte(cmd, 0x2C, true);
i2c_master_write_byte(cmd, 0x06, true);
i2c_master_stop(cmd);
esp_err_t ret = i2c_master_cmd_begin(I2C_MASTER_NUM, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
if (ret != ESP_OK) {
return ret;
}
vTaskDelay(20 / portTICK_RATE_MS);
cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (SHT30_ADDRESS << 1) | I2C_MASTER_READ, true);
if (size > 1) {
i2c_master_read(cmd, data, size - 1, I2C_MASTER_ACK);
}
i2c_master_read_byte(cmd, data + size - 1, I2C_MASTER_NACK);
i2c_master_stop(cmd);
ret = i2c_master_cmd_begin(I2C_MASTER_NUM, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
return ret;
}
void app_main()
{
i2c_master_init();
uint8_t data[6] = {0};
while (1) {
esp_err_t ret = i2c_master_sht30_read(data, sizeof(data));
if (ret != ESP_OK) {
printf("SHT30 read failed: %d\n", ret);
continue;
}
uint16_t temp_raw = (data[0] << 8) | data[1];
uint16_t hum_raw = (data[3] << 8) | data[4];
float temperature = -45 + 175 * ((float)temp_raw / 65535);
float humidity = 100 * ((float)hum_raw / 65535);
printf("Temperature: %.2f°C, Humidity: %.2f%%\n", temperature, humidity);
vTaskDelay(1000 / portTICK_RATE_MS);
}
}
```
首先需要在 `i2c_master_init()` 函数中初始化I2C总线。然后在 `i2c_master_sht30_read()` 函数中,发送读取SHT30传感器的命令,并读取温湿度数据。最后通过位运算和公式计算得到温度和湿度值。在主函数中循环读取SHT30传感器,并打印温湿度信息。
阅读全文