/********************************************************************************* * Copyright: (C) 2022 Guo Wenxue * All rights reserved. * * Filename: sht20.c * Description: This file is temperature and relative humidity sensor SHT20 code * * Version: 1.0.0(2022/4/14) * Author: Guo Wenxue * ChangeLog: 1, Release initial version on "2022/04/14 12:13:26" * ********************************************************************************/ /* * Hardware connection: * * Sht20 Module RaspberryPi/IGKBoard * VCC <-----> 3.3V * SDA <-----> SDA * SCL <-----> SCL * GND <-----> GND */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define SOFTRESET 0xFE #define TRIGGER_TEMPERATURE_NO_HOLD 0xF3 #define TRIGGER_HUMIDITY_NO_HOLD 0xF5 static inline void msleep(unsigned long ms); static inline void dump_buf(const char *prompt, uint8_t *buf, int size); int sht2x_init(char *i2c_dev); int sht2x_get_serialnumber(int fd, uint8_t *serialnumber, int size); int sht2x_get_temp_humidity(int fd, float *temp, float *rh); int main(int argc, char **argv) { int fd; float temp; float rh; uint8_t serialnumber[8]; if( argc != 2) { printf("This program used to do I2C test by sht20 temperature & humidity module.\n"); printf("Usage: %s /dev/i2c-x\n", argv[0]); return 0; } fd = sht2x_init(argv[1]); if(fd < 0) { printf("SHT2x initialize failure\n"); return 1; } if( sht2x_get_serialnumber(fd, serialnumber, 8) < 0) { printf("SHT2x get serial number failure\n"); return 3; } if( sht2x_get_temp_humidity(fd, &temp, &rh) < 0 ) { printf("SHT2x get get temperature and relative humidity failure\n"); return 3; } printf("Temperature=%lf ℃ relative humidity=%lf.\n", temp, rh); close(fd); } static inline void msleep(unsigned long ms) { struct timespec cSleep; unsigned long ulTmp; cSleep.tv_sec = ms / 1000; if (cSleep.tv_sec == 0) { ulTmp = ms * 10000; cSleep.tv_nsec = ulTmp * 100; } else { cSleep.tv_nsec = 0; } nanosleep(&cSleep, 0); } static inline void dump_buf(const char *prompt, uint8_t *buf, int size) { int i; if( !buf ) { return ; } if( prompt ) { printf("%s ", prompt); } for(i=0; i