SHT31.C:
#include "SHT31.h"
#include "stm32h7xx_hal.h"
static rt_err_t write_reg(struct rt_i2c_bus_device *bus, rt_uint8_t len, rt_uint8_t *data)
{
struct rt_i2c_msg msgs;
msgs.addr = SHT31_ADDR;
msgs.flags = RT_I2C_WR;
msgs.buf = data;
msgs.len = len;
if (rt_i2c_transfer(bus, &msgs, 1) == 1)
{
rt_kprintf("write ok\r\n");
return RT_EOK;
}
else
{
rt_kprintf("write error\r\n");
return -RT_ERROR;
}
}
static rt_err_t read_regs(struct rt_i2c_bus_device *bus, rt_uint8_t len, rt_uint8_t *buf)
{
struct rt_i2c_msg msgs;
msgs.addr = SHT31_ADDR;
msgs.flags = RT_I2C_RD;
msgs.buf = buf;
msgs.len = len;
if (rt_i2c_transfer(bus, &msgs, 1) == 1)
{
rt_kprintf("read ok\r\n");
return RT_EOK;
}
else
{
rt_kprintf("read error\r\n");
return -RT_ERROR;
}
}
void sht31_init(const char *name)
{
i2c_bus = (struct rt_i2c_bus_device *)rt_device_find(name);
if (i2c_bus == RT_NULL)
{
rt_kprintf("can't find %s device!!\n", name);
}
else
{
rt_kprintf("find %s device!!\n", name);
initialized = RT_TRUE;
}
}
void read_sht31_temp_humi(float * cur_temp, float * cur_humi)
{
rt_uint8_t temp[6];
rt_uint8_t id[1] ={0};
rt_uint8_t buf[2];
buf[0] = 0x30;
buf[1] = 0xa2;
write_reg(i2c_bus, 2, buf);
rt_thread_mdelay(40);
buf[0] = 0x24;
buf[1] = 0x00;
write_reg(i2c_bus, 2, buf);
rt_thread_mdelay(400);
read_regs(i2c_bus, 6, temp);
rt_uint16_t result[2];
result[0]=temp[0];
result[0]=(result[0]<<8)|temp[1];
result[1]=temp[3];
result[1]=(result[1]<<8)|temp[4];
float t=result[0];
*cur_temp = (t/65535)*175-45;
t=result[1];
*cur_humi = (t/65535)*100;
}
SHT31.H
#ifndef _SHT31_H
#define _SHT31_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct{
float temper;
float humidity;
}SHT31;
extern SHT31 sht31;
void SHT31M(void);
void SHT31init(void);
#ifdef __cplusplus
}
#endif
#endif
主文件main.c
int sht31_sensor(int argc, char const * argv[])
{
float humidity, temperature;
humidity = 0.0;
temperature = 0.0;
sht31_init(SHT31_I2C_BUS_NAME);
read_sht31_temp_humi(&temperature, &humidity);
rt_kprintf("temper = %d\r\n", temperature);
rt_kprintf("humidity = %d\r\n",humidity);
}
MSH_CMD_EXPORT(sht31_sensor, temperature and humidity);