I2C driver api.
#include <rtthread.h>
#include <rtdevice.h>
#define AHT10_I2C_BUS_NAME "i2c1"
#define AHT10_ADDR 0x38
#define AHT10_CALIBRATION_CMD 0xE1
#define AHT10_NORMAL_CMD 0xA8
#define AHT10_GET_DATA 0xAC
static rt_bool_t initialized = RT_FALSE;
static rt_err_t write_reg(
struct rt_i2c_bus_device *bus, rt_uint8_t reg, rt_uint8_t *data)
{
rt_uint8_t buf[3];
rt_uint32_t buf_size = 1;
buf[0] = reg;
if (data != RT_NULL)
{
buf[1] = data[0];
buf[2] = data[1];
buf_size = 3;
}
msgs.addr = AHT10_ADDR;
msgs.buf = buf;
msgs.len = buf_size;
{
return RT_EOK;
}
else
{
return -RT_ERROR;
}
}
static rt_err_t read_regs(
struct rt_i2c_bus_device *bus, rt_uint8_t len, rt_uint8_t *buf)
{
msgs.addr = AHT10_ADDR;
msgs.buf = buf;
msgs.len = len;
{
return RT_EOK;
}
else
{
return -RT_ERROR;
}
}
static void read_temp_humi(float *cur_temp, float *cur_humi)
{
rt_uint8_t temp[6];
write_reg(i2c_bus, AHT10_GET_DATA, RT_NULL);
read_regs(i2c_bus, 6, temp);
*cur_humi = (temp[1] << 12 | temp[2] << 4 | (temp[3] & 0xf0) >> 4) * 100.0 / (1 << 20);
*cur_temp = ((temp[3] & 0xf) << 16 | temp[4] << 8 | temp[5]) * 200.0 / (1 << 20) - 50;
}
static void aht10_init(const char *name)
{
rt_uint8_t temp[2] = {0, 0};
if (i2c_bus == RT_NULL)
{
rt_kprintf("can't find %s device!\n", name);
}
else
{
write_reg(i2c_bus, AHT10_NORMAL_CMD, temp);
temp[0] = 0x08;
temp[1] = 0x00;
write_reg(i2c_bus, AHT10_CALIBRATION_CMD, temp);
initialized = RT_TRUE;
}
}
static void i2c_aht10_sample(int argc, char *argv[])
{
float humidity, temperature;
char name[RT_NAME_MAX];
humidity = 0.0;
temperature = 0.0;
if (argc == 2)
{
rt_strncpy(name, argv[1], RT_NAME_MAX);
}
else
{
rt_strncpy(name, AHT10_I2C_BUS_NAME, RT_NAME_MAX);
}
if (!initialized)
{
aht10_init(name);
}
if (initialized)
{
read_temp_humi(&temperature, &humidity);
rt_kprintf("read aht10 sensor humidity : %d.%d %%\n", (int)humidity, (int)(humidity * 10) % 10);
if( temperature >= 0 )
{
rt_kprintf("read aht10 sensor temperature: %d.%d°C\n", (int)temperature, (int)(temperature * 10) % 10);
}
else
{
rt_kprintf("read aht10 sensor temperature: %d.%d°C\n", (int)temperature, (int)(-temperature * 10) % 10);
}
}
else
{
rt_kprintf("initialize sensor failed!\n");
}
}
#define RT_I2C_RD
Definition dev_i2c.h:184
#define RT_I2C_WR
Definition dev_i2c.h:183
rt_ssize_t rt_i2c_transfer(struct rt_i2c_bus_device *bus, struct rt_i2c_msg msgs[], rt_uint32_t num)
I2C data transmission.
rt_err_t rt_thread_mdelay(rt_int32_t ms)
This function will let current thread delay for some milliseconds.
Definition thread.c:754
#define MSH_CMD_EXPORT(...)
Exports a command to module shell.
Definition finsh.h:151
I2C Bus Device.
Definition dev_i2c.h:243
I2C Message.
Definition dev_i2c.h:214