| 本帖最后由 dirtwillfly 于 2025-6-29 09:59 编辑 
 4. 软件开发
 4.1配置资源
 
 在RT-Thread Setting 界面的硬件标签页,使能I2C,以及I2C1 BUS。
   
 在组件标签页,打开"使用I2C设备驱动程序"的使能开关。
 
 
   
 在软件包标签页,打开"sht4x:digital humidity and temperature sensor sht4x driver library"的使能开关。
 
 然后点击”保存“,等待开发环境自动配置完毕。
 
 4.2 配置rtconfig.h
 
 在rtconfig.h文件,添加宏定义:
 
 4.3 代码开发#define BSP_USING_I2C
#define BSP_USING_I2C1
新建app_sht4x.c文件和头文件app_sht4x.h。
 在app_sht4x.c文件添加包含的头文件:
 
 添加宏定义,其中i2c1为要使用的I2C的设备名:#include <rtthread.h>
#include <rtdevice.h>
#include <hpm_soc.h>
#include "app_sht4x.h"
#include "sht4x.h"
 添加全局变量:#define SHT4X_DEBUG
#define SHT4X_DEV_NAME       "i2c1"
 其中结构体struct sht4x_struct需要在app_sht4x.h定义:sht4x_device_t sht4x_dev = RT_NULL;
struct sht4x_struct sht4x_str;
static struct rt_thread sht4x_thread;//定义线程控制块
static char sht4x_thread_stack[1024];//定义线程栈
 编写sht4x的线程逻辑,整体线程循环为:读取温度和湿度,然后通过串口打印输出,然后延时1000ms。struct sht4x_struct{
        rt_int32_t temperature;
        rt_uint32_t humidity;
};
 编写初始化函数,主要功能为初始化sht4x_dev设备,读取sht4x的芯片串号,初始化sht4x线程,最后启动线程。static void sht4x_thread_entry(void *parameter)
{
        while(1)
        {
                sht4x_str.temperature = sht4x_read_temperature(sht4x_dev);
                sht4x_str.humidity = sht4x_read_humidity(sht4x_dev);
#ifdef SHT4X_DEBUG
                rt_kprintf("humidity   : %d.%d %%\n", (int)sht4x_str.humidity, (int)(sht4x_str.humidity * 10) % 10);
                rt_kprintf("temperature: %d.%d C\n", (int)sht4x_str.temperature, (int)(sht4x_str.temperature * 10) % 10);
#endif
                rt_thread_mdelay(1000);
        }
}
 然后,再把初始化函数添加到app_sht4x.h文件。int sht4x_sensor_init(void)
{
        rt_err_t ret = 0;
        sht4x_dev = sht4x_init(SHT4X_DEV_NAME);
        if(sht4x_dev == RT_NULL)
        {
                rt_kprintf("sht4x_init fail\n\r");
                return RT_ERROR;
        }
        rt_kprintf("sht4x id:0x%x\n",sht4x_read_serial(sht4x_dev));
        rt_kprintf("sht4x_thread init\n\r");
        ret = rt_thread_init(&sht4x_thread, "sht4x_thread", sht4x_thread_entry, RT_NULL, sht4x_thread_stack, sizeof(sht4x_thread_stack), 19, 20);
        if(ret != RT_EOK)
                rt_kprintf("sht4x_thread init fail\n\r");
        else
                ret = rt_thread_startup(&sht4x_thread);
        return ret;
}
最后的app_sht4x.h文件内容为:
 
 #ifndef APPLICATIONS_APP_SHT4X_H_
#define APPLICATIONS_APP_SHT4X_H_
struct sht4x_struct{
        rt_int32_t temperature;
        rt_uint32_t humidity;
};
int sht4x_sensor_init(void);
#endif /* APPLICATIONS_APP_SHT4X_H_ */
 
 
 
 |