手头有块FireBeetle 2 ESP32 P4 开发板,这块开发板是基于ESP32-P4R32芯片设计的高性能微控制器(MCU)开发板,支持单精度FPU和 AI指令扩展,具有强大的AI处理能力。能支持Arduino,MicroPython,Esp-idf开发。有尝试使用MicroPython和Arduino在这个开发板上编程,还是比较简单,今天尝试一下使用ESP-IDF方式来实现一个SHT30温湿度传感器读取的项目。
使用esp-idf组件读取SHT30温湿度信息。不得不说使用Arduino和Mpy来读取SHT30传感器温湿度信息,还是相当简单的。但是使用esp-idf来实现对我来说就难得多了。正好留意到新版的esp-idf支持组件编程了,基本思想就是将硬件的读取,以组件的形式提供完整的功能模块,只要在程序中调用相应的组件即可,大大简化了编程。
第一步:新建一个工程,这里使用hello_world例程做为基础工程,来创建一个新的工程。
第二步:在esp-idf组件仓库里搜索SHT30,可以找到sht3x的组件库,接下来参考着文档说明,在项目中添加组件。
打开终端,输入“”idf.py add-dependency "esp-idf-lib/sht3x^1.0.8",系统就会自动将组件依赖关系写到“idf_component.yml”里边去。可以打开这个文件查看,里边有组件的基本说明.
第三步:先编译一下工程。系统会自动检查组件依赖关系,会创建一个"managed_components"文件夹,将需要的组件预先下载下来(如果没有出现这个文件夹,就先清理一下项目,然后再编译就会出现了)。
第四步:参考着组件文件夹里边官方提供的例程,写一个读取SHT30的代码。
/** * Simple example with SHT3x sensor. * * It shows different user task implementations in *single shot mode* and * *periodic mode*. In *single shot* mode either low level or high level * functions are used. */ #include <stdio.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> #include <esp_system.h> #include <sht3x.h> #include <string.h> #include <esp_err.h> #ifndef APP_CPU_NUM #define APP_CPU_NUM PRO_CPU_NUM #endif static sht3x_t dev; void task(void *pvParameters) { float temperature; float humidity; esp_err_t res; // Start periodic measurements with 1 measurement per second. ESP_ERROR_CHECK(sht3x_start_measurement(&dev, SHT3X_PERIODIC_1MPS, SHT3X_HIGH)); // Wait until first measurement is ready (constant time of at least 30 ms // or the duration returned from *sht3x_get_measurement_duration*). vTaskDelay(sht3x_get_measurement_duration(SHT3X_HIGH)); TickType_t last_wakeup = xTaskGetTickCount(); while (1) { // Get the values and do something with them. if ((res = sht3x_get_results(&dev, &temperature, &humidity)) == ESP_OK) printf("SHT3x Sensor: %.2f °C, %.2f %%\n", temperature, humidity); else printf("Could not get results: %d (%s)", res, esp_err_to_name(res)); // Wait until 2 seconds (cycle time) are over. vTaskDelayUntil(&last_wakeup, pdMS_TO_TICKS(2000)); } } void app_main() { ESP_ERROR_CHECK(i2cdev_init()); memset(&dev, 0, sizeof(sht3x_t)); ESP_ERROR_CHECK(sht3x_init_desc(&dev, 0x44, 0, 7, 8)); ESP_ERROR_CHECK(sht3x_init(&dev)); xTaskCreatePinnedToCore(task, "sh301x_test", configMINIMAL_STACK_SIZE * 8, NULL, 5, NULL, APP_CPU_NUM); }
这里还不知道如何将组件的“Kconfig”中的配置,引入到工程的配置中来,所以暂时都是用实际值来代替了配置的值。成功读取到SHT30的温湿度值。
简单总结一下,使用组件编程,还是蛮方便的,跳过了底层繁琐的硬件驱动部分,可以直接使用已有的代码,避免重复造轮子。