esp32 iic sht21 idf代码
时间: 2023-08-31 11:09:49 浏览: 145
以下是ESP32使用IIC接口读取SHT21温湿度传感器的IDF代码示例:
```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_TX_BUF_DISABLE 0 /*!< I2C master do not need buffer */
#define I2C_MASTER_RX_BUF_DISABLE 0 /*!< I2C master do not need buffer */
#define I2C_MASTER_FREQ_HZ 100000 /*!< I2C master clock frequency */
#define SHT21_ADDR 0x40 /*!< SHT21 I2C address */
esp_err_t 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);
return i2c_driver_install(I2C_MASTER_NUM, conf.mode,
I2C_MASTER_RX_BUF_DISABLE,
I2C_MASTER_TX_BUF_DISABLE, 0);
}
void sht21_read_id()
{
uint8_t cmd[1] = {0xEFC8}; // send command to read ID
uint8_t data[8] = {0};
i2c_cmd_handle_t cmd_handle = i2c_cmd_link_create();
i2c_master_start(cmd_handle);
i2c_master_write_byte(cmd_handle, (SHT21_ADDR << 1) | I2C_MASTER_WRITE, true);
i2c_master_write(cmd_handle, cmd, 1, true);
i2c_master_stop(cmd_handle);
esp_err_t ret = i2c_master_cmd_begin(I2C_MASTER_NUM, cmd_handle, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd_handle);
if (ret != ESP_OK) {
printf("Failed to send command\n");
return;
}
// delay for conversion
vTaskDelay(100 / portTICK_RATE_MS);
// read ID
cmd[0] = 0xFA0F; // send command to read ID
cmd_handle = i2c_cmd_link_create();
i2c_master_start(cmd_handle);
i2c_master_write_byte(cmd_handle, (SHT21_ADDR << 1) | I2C_MASTER_WRITE, true);
i2c_master_write(cmd_handle, cmd, 1, true);
i2c_master_start(cmd_handle);
i2c_master_write_byte(cmd_handle, (SHT21_ADDR << 1) | I2C_MASTER_READ, true);
i2c_master_read(cmd_handle, data, 8, I2C_MASTER_LAST_NACK);
i2c_master_stop(cmd_handle);
ret = i2c_master_cmd_begin(I2C_MASTER_NUM, cmd_handle, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd_handle);
if (ret != ESP_OK) {
printf("Failed to read ID\n");
return;
}
uint16_t id = (data[0] << 8) | data[1];
uint8_t crc = data[2];
if (crc != (uint8_t)id * 5 / 256) {
printf("CRC error\n");
return;
}
printf("SHT21 ID: 0x%04X\n", id);
}
void app_main()
{
i2c_master_init();
sht21_read_id();
}
```
在示例中,使用ESP-IDF提供的I2C驱动程序,初始化I2C主机并发送命令读取SHT21传感器的ID。在读取ID之前需要等待一段时间,以便传感器完成转换。读取ID后,需要验证CRC以确保数据正确性。
阅读全文