htu21.c 1.9 KB

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