sensor.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. #include "sensor.h"
  2. #include "i2c.h"
  3. /* Type def */
  4. typedef union {
  5. uint32_t u32;
  6. struct {
  7. #ifdef LITTLE_ENDIAN // Byte-order is little endian
  8. uint8_t u8ll;
  9. uint8_t u8lh;
  10. uint8_t u8hl;
  11. uint8_t u8hh;
  12. #else // Byte-order is big endian
  13. uint8_t u8hh;
  14. uint8_t u8hl;
  15. uint8_t u8lh;
  16. uint8_t u8ll;
  17. #endif
  18. } s8;
  19. } nt32_t;
  20. /* Defines */
  21. #define I2C_ADDR 0x70
  22. #define CMD_INIT 0xe1
  23. #define CMD_MEASURE 0xac
  24. #define CMD_SRESET 0xba
  25. #define STATUS_BUSY 0x80
  26. #define STATUS_CMD 0x40
  27. #define STATUS_CYC 0x20
  28. #define STATUS_CAL 0x04
  29. aht10_st_t AHT10_Init(void)
  30. {
  31. i2c_status_t res;
  32. I2C_Start();
  33. res = I2C_WriteByte(I2C_ADDR);
  34. if (res != I2C_Ret_OK) {
  35. return AHT10_St_Err;
  36. }
  37. res = I2C_WriteByte(CMD_INIT);
  38. if (res != I2C_Ret_OK) {
  39. return AHT10_St_Err;
  40. }
  41. I2C_Stop();
  42. return AHT10_St_OK;
  43. }
  44. aht10_st_t AHT10_StartMeasure(void)
  45. {
  46. i2c_status_t res;
  47. I2C_Start();
  48. res = I2C_WriteByte(I2C_ADDR);
  49. if (res != I2C_Ret_OK) {
  50. return AHT10_St_Err;
  51. }
  52. res = I2C_WriteByte(CMD_MEASURE);
  53. if (res != I2C_Ret_OK) {
  54. return AHT10_St_Err;
  55. }
  56. I2C_Stop();
  57. return AHT10_St_OK;
  58. }
  59. aht10_st_t AHT10_GetData(aht10_t * data)
  60. {
  61. i2c_status_t res;
  62. I2C_Start();
  63. /* Send I2C read addr */
  64. res = I2C_WriteByte(I2C_ADDR | 0x1);
  65. if (res != I2C_Ret_OK) {
  66. return AHT10_St_Err;
  67. }
  68. /* Now read the value with NACK */
  69. uint8_t buf[6];
  70. res = I2C_ReadByte(buf, 0);
  71. if (res != I2C_Ret_OK) {
  72. return AHT10_St_Err;
  73. }
  74. I2C_Stop();
  75. if ((buf[0] & STATUS_BUSY) != 0) {
  76. return AHT10_St_Bsy;
  77. }
  78. /* Calculate values */
  79. uint32_t result;
  80. nt32_t tmp;
  81. /* Humidity = Srh * 100% / 2^20 */
  82. tmp.s8.u8hl = buf[1];
  83. tmp.s8.u8lh = buf[2];
  84. tmp.s8.u8ll = buf[3];
  85. result = tmp.u32 >> 4;
  86. result *= 100;
  87. result /= 1048576;
  88. data->Humidity = (int8_t)result;
  89. /* Temperature = St * 200 / 2^20 - 50 */
  90. tmp.s8.u8hl = buf[3] & 0xf;
  91. tmp.s8.u8lh = buf[4];
  92. tmp.s8.u8ll = buf[5];
  93. result = tmp.u32 * 200;
  94. result /= 1048576;
  95. data->Temperature = (int8_t)(result - 50);
  96. return AHT10_St_OK;
  97. }