cht8305.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "cht8305.h"
  2. #include "libs/shark_task.h"
  3. #include "libs/logger.h"
  4. static int i2c_read(u8 reg, u16 *data);
  5. static int i2c_write(u8 reg, u16 data);
  6. static bool _ready = false;
  7. static int _init_count = 0;
  8. void cht8305_init(void) {
  9. u16 data;
  10. if (i2c_read(ID_Reg, &data) == 2) {
  11. if (data == CHT8305_ID) {
  12. if (i2c_write(Config_Reg, 0x1000) >= 0) {
  13. _ready = true;
  14. }
  15. }
  16. }
  17. }
  18. bool cht8305_ready(void) {
  19. return _ready;
  20. }
  21. void cht8305_reset(void) {
  22. if (_ready) {
  23. state_debug("cht8305 ready\n");
  24. }else {
  25. state_debug("cht8305 not ready reinit\n");
  26. cht8305_init();
  27. }
  28. u16 data = 0x8000; //reset
  29. i2c_write(Config_Reg, data);
  30. i2c_read(Config_Reg, &data);
  31. state_debug("data = 0x%x\n", data);
  32. }
  33. u8 cht8305_get_humidity(void){
  34. if (!_ready) {
  35. _init_count ++;
  36. if (_init_count <= 20) {
  37. cht8305_init();
  38. }
  39. return 0xFF;
  40. }
  41. u16 data = 0;
  42. if (i2c_read(Humi_Reg, &data) == 2) {
  43. u32 data32 = data << 10;
  44. u32 humidity = 100 * data32/((1<<16) - 1) >> 10;
  45. return (u8) humidity;
  46. }
  47. return 0xFF;
  48. }
  49. static int i2c_read(u8 reg, u16 *data) {
  50. u8 reg_value[2] = {0x00, 0x00};
  51. int ret = gd32_i2c_read_nbytes(0, CHT8305_I2C_ADDR, reg, reg_value, 2);
  52. if (ret == 2) {
  53. *data = ((reg_value[0] << 8)&0xFF00) | reg_value[1];
  54. }
  55. return ret;
  56. }
  57. static int i2c_write(u8 reg, u16 data) {
  58. u8 reg_value[2];
  59. reg_value[0] = (data>>8) & 0xFF;
  60. reg_value[1] = data & 0xFF;
  61. return gd32_i2c_write_nbytes(0, CHT8305_I2C_ADDR, reg, reg_value, 2);
  62. }