cht8305.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. if (_ready) {
  29. u16 data = 0x8000; //reset
  30. i2c_write(Config_Reg, data);
  31. i2c_read(Config_Reg, &data);
  32. state_debug("data = 0x%x\n", data);
  33. }
  34. }
  35. u8 cht8305_get_humidity(void){
  36. if (!_ready) {
  37. _init_count ++;
  38. if (_init_count <= 20) {
  39. cht8305_init();
  40. }
  41. return 0xFF;
  42. }
  43. u16 data = 0;
  44. if (i2c_read(Humi_Reg, &data) == 2) {
  45. u32 data32 = data << 10;
  46. u32 humidity = 100 * data32/((1<<16) - 1) >> 10;
  47. return (u8) humidity;
  48. }
  49. return 0xFF;
  50. }
  51. static int i2c_read(u8 reg, u16 *data) {
  52. u8 reg_value[2] = {0x00, 0x00};
  53. int ret = gd32_i2c_read_nbytes(0, CHT8305_I2C_ADDR, reg, reg_value, 2);
  54. if (ret == 2) {
  55. *data = ((reg_value[0] << 8)&0xFF00) | reg_value[1];
  56. }
  57. return ret;
  58. }
  59. static int i2c_write(u8 reg, u16 data) {
  60. u8 reg_value[2];
  61. reg_value[0] = (data>>8) & 0xFF;
  62. reg_value[1] = data & 0xFF;
  63. return gd32_i2c_write_nbytes(0, CHT8305_I2C_ADDR, reg, reg_value, 2);
  64. }