htu21.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "stm8s.h"
  2. #include "htu21.h"
  3. #include "i2c.h"
  4. #include "i2c_master_poll.h"
  5. #include "delay.h"
  6. #define HTU_T_MEASURE 0xF3
  7. #define HTU_H_MEASURE 0xF5
  8. static uint8_t buf[3];
  9. static const uint8_t addr = 0x40;
  10. static t_i2c_status i2cs = I2C_SUCCESS;
  11. static uint32_t val;
  12. static uint8_t CalcSht21Crc(uint8_t *data, uint8_t nbrOfBytes);
  13. htu_err_t htu_GetTemperature(int16_t * temperature) {
  14. buf[0] = HTU_T_MEASURE;
  15. i2cs = i2c_wr_data(addr, 1, buf);
  16. //I2C_WriteBytes(addr, 1, buf);
  17. if (i2cs == 0) {
  18. Delay(100);
  19. i2c_rd_data(addr, 3, buf);
  20. //I2C_ReadBytes(addr, 3, buf);
  21. if(buf[2] == CalcSht21Crc(buf,2)) {
  22. val = buf[0];
  23. val <<= 8;
  24. val |= (buf[1] & 0xfc);
  25. // Temp = val * 175.72 / 2^16 - 46.85
  26. val *= 4393; // 175.72/4*100
  27. val *= 100; // for .xx degree
  28. val += 819200; // for round
  29. val /= 1638400; // 2^16/4*100
  30. *temperature = val - 4685;
  31. return HTU_OK;
  32. } else {
  33. *temperature = 1100;
  34. return HTU_CRC_Temp;
  35. }
  36. } else {
  37. *temperature = 9900;
  38. return HTU_I2C;
  39. }
  40. }
  41. htu_err_t htu_GetHumidity(uint16_t * humidity) {
  42. buf[0] = HTU_H_MEASURE;
  43. i2cs = i2c_wr_data(addr, 1, buf);
  44. //I2C_WriteBytes(addr, 1, buf);
  45. if (i2cs == 0) {
  46. Delay(100);
  47. i2c_rd_data(addr, 3, buf);
  48. //I2C_ReadBytes(addr, 3, buf);
  49. if(buf[2] == CalcSht21Crc(buf,2)) {
  50. val = buf[0];
  51. val <<= 8;
  52. val |= (buf[1] & 0xfc);
  53. // Humidity = val * 125 / 2^16 - 6
  54. val *= 125;
  55. //val *= 10; // for .x %H
  56. val += 32768; // for round
  57. val /= 65536;
  58. *humidity = val - 6;
  59. return HTU_OK;
  60. } else {
  61. *humidity = 1100;
  62. return HTU_CRC_Humidity;
  63. }
  64. } else {
  65. *humidity = 9900;
  66. return HTU_I2C;
  67. }
  68. }
  69. static uint8_t CalcSht21Crc(uint8_t *data, const uint8_t nbrOfBytes) {
  70. // CRC
  71. //const u16t POLYNOMIAL = 0x131; //P(x)=x^8+x^5+x^4+1 = 100110001
  72. uint8_t byteCtr,bit,crc;
  73. crc = 0;
  74. //calculates 8-Bit checksum with given polynomial
  75. for (byteCtr = 0; byteCtr < nbrOfBytes; ++byteCtr)
  76. {
  77. crc ^= (data[byteCtr]);
  78. for (bit = 8; bit > 0; --bit)
  79. {
  80. if (crc & 0x80) crc = (crc << 1) ^ 0x131;
  81. else crc = (crc << 1);
  82. }
  83. }
  84. return(crc);
  85. }