/********************************************************************** * Copyright: (C)2024 LingYun IoT System Studio * Author: GuoWenxue * * Description: Temperature and humidity sensor SHT20 driver on ISKBoard * * ChangeLog: * Version Date Author Description * V1.0.0 2024.08.29 GuoWenxue Release initial version * ***********************************************************************/ #include #include #include "i2c_bitbang.h" #include "sht20.h" #define CONFIG_DEBUG_SHT2X /* Enable SHT20 debug */ #define SHT2X_CHIPADDR 0x40 /* SHT20 7-Bits Chip address */ #ifdef CONFIG_DEBUG_SHT2X #define sht2x_print(format,args...) printf(format, ##args) #else #define sht2x_print(format,args...) do{} while(0); #endif #ifdef CONFIG_DEBUG_SHT2X static inline void dump_buf(uint8_t *buf, uint32_t size) { int i; if(!buf) return ; for(i=0; i0; --bit) { if (crc & 0x80) crc = (crc << 1) ^ 0x0131; //POLYNOMIAL; else crc = (crc << 1); } } if (crc != checksum) { return -1; } else { return 0; } } static int sht2x_measure_value(uint8_t command, uint16_t *val) { uint8_t buf[3]; /* I2C receive buffer */ int count=4; /* I2C read retry times */ if( !val ) { sht2x_print("SHT2X invalid input arguments\r\n"); return -1; } if(TRIG_T_MEASUREMENT_POLL!=command && TRIG_RH_MEASUREMENT_POLL !=command ) { sht2x_print("SHT2X unsupport command: 0x%0x\r\n", command); return -2; } if( i2c_write(&command, 1) < 0 ) { sht2x_print("SHT2X send measure command 0x%0x failure\r\n", command); return -3; } if(TRIG_T_MEASUREMENT_POLL == command) HAL_Delay(85); else HAL_Delay(29); while(count--) { memset(buf, 0, 3); if( !i2c_read(buf, 3) ) { break; } HAL_Delay(5); } if( sht2x_checkcrc(buf, 2, buf[2])< 0 ) { #ifdef CONFIG_DEBUG_SHT2X sht2x_print("Measurement data checksum failure:\r\n"); dump_buf(buf, 3); #endif return -4; } if(TRIG_T_MEASUREMENT_POLL == command) *val = buf[0]<<8|(buf[1]&0xFC); //14bits(1111 1100) else *val = buf[0]<<8|(buf[1]&0xF0); //12bits(1111 0000) sht2x_print("Measurement temperature value: 0x%04x\r\n", *val); return 0; }