| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- #include "cht8305.h"
- #include "libs/shark_task.h"
- #include "libs/logger.h"
- static int i2c_read(u8 reg, u16 *data);
- static int i2c_write(u8 reg, u16 data);
- static bool _ready = false;
- static int _init_count = 0;
- void cht8305_init(void) {
- u16 data;
- if (i2c_read(ID_Reg, &data) == 2) {
- if (data == CHT8305_ID) {
- if (i2c_write(Config_Reg, 0x1000) >= 0) {
- _ready = true;
- }
- }
- }
- }
- bool cht8305_ready(void) {
- return _ready;
- }
- void cht8305_reset(void) {
- if (_ready) {
- state_debug("cht8305 ready\n");
- }else {
- state_debug("cht8305 not ready reinit\n");
- cht8305_init();
- }
- if (_ready) {
- u16 data = 0x8000; //reset
- i2c_write(Config_Reg, data);
- i2c_read(Config_Reg, &data);
- state_debug("data = 0x%x\n", data);
- }
- }
- u8 cht8305_get_humidity(void){
- if (!_ready) {
- _init_count ++;
- if (_init_count <= 20) {
- cht8305_init();
- }
- return 0xFF;
- }
- u16 data = 0;
- if (i2c_read(Humi_Reg, &data) == 2) {
- u32 data32 = data << 10;
- u32 humidity = 100 * data32/((1<<16) - 1) >> 10;
- return (u8) humidity;
- }
- return 0xFF;
- }
- static int i2c_read(u8 reg, u16 *data) {
- u8 reg_value[2] = {0x00, 0x00};
- int ret = gd32_i2c_read_nbytes(0, CHT8305_I2C_ADDR, reg, reg_value, 2);
- if (ret == 2) {
- *data = ((reg_value[0] << 8)&0xFF00) | reg_value[1];
- }
- return ret;
- }
- static int i2c_write(u8 reg, u16 data) {
- u8 reg_value[2];
- reg_value[0] = (data>>8) & 0xFF;
- reg_value[1] = data & 0xFF;
- return gd32_i2c_write_nbytes(0, CHT8305_I2C_ADDR, reg, reg_value, 2);
- }
|