htu21.c 2.2 KB

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