123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156 |
-
-
- #include <Wire.h>
- #include "SHT2x.h"
-
- SHT2x::SHT2x(uint8_t _addr, TwoWire* _wire) {
- addr = _addr;
- wire = _wire;
- }
-
- void SHT2x::begin(void) {
- wire->begin();
- }
-
- bool SHT2x::GetAlive(void) {
- uint16_t r = readSensor(TRIGGER_TEMP_MEASURE_HOLD);
- if ((r == ERROR_TIMEOUT) || (r == ERROR_CRC)) {
- return false;
- }
- return true;
- }
-
-
- float SHT2x::GetHumidity(void) {
- return (-6.0 + 125.0 / 65536.0 * (float)(readSensor(TRIGGER_HUMD_MEASURE_HOLD)));
- }
-
-
- float SHT2x::GetTemperature(void) {
- return (-46.85 + 175.72 / 65536.0 * (float)(readSensor(TRIGGER_TEMP_MEASURE_HOLD)));
- }
-
-
- void SHT2x::setResolution(uint8_t resolution) {
- uint8_t userRegister = read_user_register();
- userRegister &= B01111110;
- resolution &= B10000001;
- userRegister |= resolution;
-
-
- wire->beginTransmission(addr);
- wire->write(WRITE_USER_REG);
- wire->write(userRegister);
- wire->endTransmission();
- }
-
- uint8_t SHT2x::read_user_register(void) {
- uint8_t userRegister;
-
-
- wire->beginTransmission(addr);
- wire->write(READ_USER_REG);
- wire->endTransmission();
-
-
- wire->requestFrom(addr, 1);
-
- userRegister = wire->read();
-
- return userRegister;
- }
-
- uint16_t SHT2x::readSensor(uint8_t command) {
- uint16_t result;
-
- wire->beginTransmission(addr);
- wire->write(command);
- wire->endTransmission();
-
-
- delay(55);
-
-
- wire->requestFrom(addr, 3);
-
-
- int counter = 0;
- while (wire->available() < 3) {
- counter++;
- delay(1);
- if(counter > 100) return ERROR_TIMEOUT;
- }
-
-
- result = ((wire->read()) << 8);
- result |= wire->read();
-
- uint8_t checksum = wire->read();
- if(check_crc(result, checksum) != 0) return(ERROR_CRC);
-
- result &= ~0x0003;
- return result;
- }
-
-
-
-
-
-
- #define SHIFTED_DIVISOR 0x988000
-
- uint8_t SHT2x::check_crc(uint16_t message_from_sensor, uint8_t check_value_from_sensor) {
-
- uint32_t remainder = (uint32_t)message_from_sensor << 8;
-
-
- remainder |= check_value_from_sensor;
- uint32_t divsor = (uint32_t)SHIFTED_DIVISOR;
-
-
-
- for (int i = 0; i < 16; i++) {
-
- if (remainder & ((uint32_t)1 << (23 - i))) {
- remainder ^= divsor;
- }
-
-
- divsor >>= 1;
- }
-
- return (uint8_t)remainder;
- }
|