/* * si7021 library * SI7021 Temperature and Humidity Sensor @ ESP32 i2c * * copyright: Jannik Beyerstedt | http://jannikbeyerstedt.de | code@jannikbeyerstedt.de * license: http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 License */ #include #include #include "si7021.hpp" /** * Constuctor of the SI7021 sensor wrapper */ Si7021::Si7021(void) { _i2caddr = SI7021_DEFAULT_ADDRESS; } /** * Start the I2C interface * Attention: leave at least 25 ms power up time before the first measurement */ bool Si7021::begin(void) { Wire.begin(); Wire.setClock(200000); reset(); if (readRegister8(SI7021_READRHT_REG_CMD) != 0x3A) { return false; } return true; } /** * Send a reset command to the sensor */ void Si7021::reset(void) { Wire.beginTransmission(_i2caddr); Wire.write((uint8_t)SI7021_RESET_CMD); Wire.endTransmission(true); delay(10); // SI7021 reset time } /** * Initiate a humidity and temperature measurement * Get the values from the public variables temperature and humudity * * @return true, if successful measurement */ bool Si7021::measure(void) { uint8_t chxsum; uint8_t cnt; // TRIGGER HUMIDITY MEASUREMENT AND GET VALUE Wire.beginTransmission(_i2caddr); Wire.write((uint8_t)SI7021_MEASRH_NOHOLD_CMD); Wire.endTransmission(true); // true, otherwise the read will not work delay(23); // wait for the Conversion Time of the Sensor cnt = Wire.requestFrom(_i2caddr, 3); if (cnt < 3) { // Serial.printf("[ERROR] SI7021 humi, only %d bytes received\n", cnt); return false; } uint16_t hum_raw = Wire.read(); hum_raw <<= 8; hum_raw |= Wire.read(); chxsum = Wire.read(); this->humidity = hum_raw; this->humidity *= 125; this->humidity /= 65536; this->humidity -= 6; // GET TEMPERATURE VALUE OF PREVIOUS HUMIDITY MEASUREMENT Wire.beginTransmission(_i2caddr); Wire.write((uint8_t)SI7021_READPREVTEMP_CMD); Wire.endTransmission(true); // true, otherwise the read will not work cnt = Wire.requestFrom(_i2caddr, 3); if (cnt < 3) { // Serial.printf("[ERROR] SI7021 temp, only %d bytes received\n", cnt); return false; } uint16_t temp_raw = Wire.read(); temp_raw <<= 8; temp_raw |= Wire.read(); chxsum = Wire.read(); this->temperature = temp_raw; this->temperature *= 175.72; this->temperature /= 65536; this->temperature -= 46.85; return true; } // void Si7021::writeRegister8(uint8_t reg, uint8_t value) { // // TODO: Test // Wire.beginTransmission(_i2caddr); // Wire.write((uint8_t)reg); // Wire.write((uint8_t)value); // Wire.endTransmission(); // } uint8_t Si7021::readRegister8(uint8_t reg) { uint8_t value; Wire.beginTransmission(_i2caddr); Wire.write((uint8_t)reg); Wire.endTransmission(true); // true, otherwise the value does not get read Wire.requestFrom(_i2caddr, 1); value = Wire.read(); return value; }