i2c_simple_main.c 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <stdio.h>
  2. #include "esp_log.h"
  3. #include "driver/i2c.h"
  4. #include "i2c_sht3x.h"
  5. static const char *TAG = "i2c-sht3x";//"i2c-simple-example";
  6. #define I2C_MASTER_SCL_IO GPIO_NUM_14//CONFIG_I2C_MASTER_SCL /*!< GPIO number used for I2C master clock */
  7. #define I2C_MASTER_SDA_IO GPIO_NUM_4//CONFIG_I2C_MASTER_SDA /*!< GPIO number used for I2C master data */
  8. #define I2C_MASTER_NUM 0 /*!< I2C master i2c port number, the number of i2c peripheral interfaces available will depend on the chip */
  9. #define I2C_MASTER_FREQ_HZ 400000 /*!< I2C master clock frequency */
  10. #define I2C_MASTER_TX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */
  11. #define I2C_MASTER_RX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */
  12. #define I2C_MASTER_TIMEOUT_MS 1000
  13. /**
  14. * @brief i2c master initialization
  15. */
  16. static esp_err_t i2c_master_init(void)
  17. {
  18. int i2c_master_port = I2C_MASTER_NUM;
  19. i2c_config_t conf = {
  20. .mode = I2C_MODE_MASTER,
  21. .sda_io_num = I2C_MASTER_SDA_IO,
  22. .scl_io_num = I2C_MASTER_SCL_IO,
  23. .sda_pullup_en = GPIO_PULLUP_ENABLE,
  24. .scl_pullup_en = GPIO_PULLUP_ENABLE,
  25. .master.clk_speed = I2C_MASTER_FREQ_HZ,
  26. };
  27. i2c_param_config(i2c_master_port, &conf);
  28. return i2c_driver_install(i2c_master_port, conf.mode, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
  29. }
  30. // i2c_sht3x_task 任务。初始化 SHT3x工作于周期测量模式,获取环境温湿度数据
  31. void i2c_sht3x_task(void* arg)
  32. {
  33. // 配置I2C0-主机模式,400K,指定 SCL-14,SDA-4
  34. i2c_master_init();
  35. uint8_t recv_dat[6] = {0};
  36. float temperature = 0.0;
  37. float humidity = 0.0;
  38. ESP_LOGI(TAG, "esp32 sht3x project starting ……");
  39. sht3x_reset(); // 复位SHT3X
  40. if(sht3x_init() == ESP_OK) // 初始化SHT3X(周期测量模式)
  41. ESP_LOGI(TAG, "sht3x init ok.\n");
  42. else
  43. ESP_LOGE(TAG, "sht3x init fail.\n");
  44. vTaskDelay(1000 / portTICK_PERIOD_MS); //延时1s 等待SHT3X传感器内部采样完成
  45. for (;;)
  46. {
  47. if(sht3x_read_th_raw_dat(recv_dat) == ESP_OK) // 从SHT3X读取一次数据(周期测量模式下)
  48. {
  49. // 将SHT3X接收的6个字节数据进行CRC校验,并转换为温度值和湿度值
  50. if(sht3x_dat2float(recv_dat, &temperature, &humidity) == 0)
  51. {
  52. ESP_LOGI(TAG, "temperature = %.2f ℃,humidity = %.2f %%RH", temperature, humidity);
  53. }
  54. else
  55. {
  56. ESP_LOGE(TAG, "crc check fail.\n");
  57. }
  58. }
  59. else
  60. {
  61. ESP_LOGE(TAG, "read data from sht3x fail.\n");
  62. }
  63. vTaskDelay(1000 / portTICK_PERIOD_MS);
  64. }
  65. }
  66. void app_main(void)
  67. {
  68. // 创建 i2c_sht3x_task 任务。初始化 SHT30工作于周期测量模式,获取环境温湿度数据
  69. xTaskCreate(i2c_sht3x_task, "i2c_sht3x_task", 2048, NULL, 3, NULL);
  70. }