#include "sensor.h" #include "i2c.h" /* Type def */ typedef union { uint32_t u32; struct { #ifdef LITTLE_ENDIAN // Byte-order is little endian uint8_t u8ll; uint8_t u8lh; uint8_t u8hl; uint8_t u8hh; #else // Byte-order is big endian uint8_t u8hh; uint8_t u8hl; uint8_t u8lh; uint8_t u8ll; #endif } s8; } nt32_t; /* Defines */ #define I2C_ADDR 0x70 #define CMD_INIT 0xe1 #define CMD_MEASURE 0xac #define CMD_SRESET 0xba #define STATUS_BUSY 0x80 #define STATUS_CMD 0x40 #define STATUS_CYC 0x20 #define STATUS_CAL 0x04 aht10_st_t AHT10_Init(void) { i2c_status_t res; I2C_Start(); res = I2C_WriteByte(I2C_ADDR); if (res != I2C_Ret_OK) { return AHT10_St_Err; } res = I2C_WriteByte(CMD_INIT); if (res != I2C_Ret_OK) { return AHT10_St_Err; } I2C_Stop(); return AHT10_St_OK; } aht10_st_t AHT10_StartMeasure(void) { i2c_status_t res; I2C_Start(); res = I2C_WriteByte(I2C_ADDR); if (res != I2C_Ret_OK) { return AHT10_St_Err; } res = I2C_WriteByte(CMD_MEASURE); if (res != I2C_Ret_OK) { return AHT10_St_Err; } I2C_Stop(); return AHT10_St_OK; } aht10_st_t AHT10_GetData(aht10_t * data) { i2c_status_t res; I2C_Start(); /* Send I2C read addr */ res = I2C_WriteByte(I2C_ADDR | 0x1); if (res != I2C_Ret_OK) { return AHT10_St_Err; } /* Now read the value with NACK */ uint8_t buf[6]; res = I2C_ReadByte(buf, 0); if (res != I2C_Ret_OK) { return AHT10_St_Err; } I2C_Stop(); if ((buf[0] & STATUS_BUSY) != 0) { return AHT10_St_Bsy; } /* Calculate values */ uint32_t result; nt32_t tmp; /* Humidity = Srh * 100% / 2^20 */ tmp.s8.u8hl = buf[1]; tmp.s8.u8lh = buf[2]; tmp.s8.u8ll = buf[3]; result = tmp.u32 >> 4; result *= 100; result /= 1048576; data->Humidity = (int8_t)result; /* Temperature = St * 200 / 2^20 - 50 */ tmp.s8.u8hl = buf[3] & 0xf; tmp.s8.u8lh = buf[4]; tmp.s8.u8ll = buf[5]; result = tmp.u32 * 200; result /= 1048576; data->Temperature = (int8_t)(result - 50); return AHT10_St_OK; }