Code Monkey home page Code Monkey logo

adafruit_sht31's Introduction

Adafruit SHT31-D Temperature and Humidity Sensor Breakout Build StatusDocumentation

This is a library for the SHT31 Digital Humidity + Temp sensor.

It is designed specifically to work with the SHT31 Digital in the Adafruit shop:

These sensors use I2C to communicate, 2 pins are required to interface

Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!

Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution

Check out the links above for our tutorials and wiring diagrams

Installation

Use the Arduino Library Manager to install this library. If you're unfamiliar with how this works, we have a great tutorial on Arduino library installation at: http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use

adafruit_sht31's People

Contributors

andydoro avatar caternuson avatar chuckvanzant avatar dhalbert avatar dirkmueller avatar evaherrada avatar frozencemetery avatar gpshead avatar hoffmannjan avatar kurte avatar ladyada avatar luapi avatar microbuilder avatar rotzbua avatar siddacious avatar sslupsky avatar swglasspit avatar tdicola avatar welvins avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adafruit_sht31's Issues

Adafruit_SHT31::begin always returns true

This line is commented out:
//return (readStatus() == 0x40);

Testing for presence is useful during setup. Even when the board is not present and/or not fully operational, readTemperature will return 0.0 & readHumidity will return 0.0. Temperature of 0.0 is perfectly valid, though humidity of 0.0 is quite unlikely.

Public interface to SHT31 library does not allow for fast, safe checking to see if sensor read fails

While the public interface does provide an indication of a read failure by setting the relevant floating point values to NAN, (i.e., the return values of Adafruit_SHT31::readTemperature and Adafruit_SHT31::readHumidity as well as the pointer parameters of Adafruit_SHT31::readBoth), this is not an effective defense to potential I2C read issues for two reasons:

  1. Floating point comparisons on AVR devices are extremely expensive compared to simple boolean checks. An isnan call (or even a more naive comparison of a number to itself) with a float as the argument consumes 21 instructions, compared with one or two instructions for a boolean comparison and a conditional jump.
  2. While there is private code in the form of Adafruit_SHT31::readTempHum that does return a bool value indicating read success, this code suffers from a fatal flaw: even though the underlying functions Adafruit_SHT31::writeCommand and Adafruit_I2CDevice::read do provide success/fail indicators via their boolean return values, those values are never checked in readTempHum. Instead, the only method used to determine success or failure is through two CRC8 checks. However, since the success of the read call is not checked, if an I2C read fails, these CRC8 checks will be performed on uninitialized data, which, if we assume a uniform random distribution of values, has a 1 in 65,536 chance of falsely reporting success and passing off invalid data as valid.

I suggest making the following changes:

  1. Modify readBoth to return a bool value and simply forward the return value of readTempHum. Changing the return value from void to bool should not affect the ability of any user code to compile -- users may receive warnings about ignored return values, but existing code that relies on current behavior will still continue to function.
  2. Modify readTempHum to check the return values of writeCommand and i2c_dev->read and return false immediately if either command fails. This avoids the risk of inadvertently passing along bad data as good.

Example code does not work for Feather Nrf52840 Sense

  • Arduino board: Feather NRF52840 Sense

  • Arduino IDE version (found in Arduino -> About Arduino menu): 1.8.19

  • List the steps to reproduce the problem below (if possible attach a sketch or
    copy the sketch code in too): LIST REPRO STEPS BELOW

Upload "SHt31Test" example code from this repo into the board, watch serial output -
"Temp *C = nan Hum. % = nan"

Other sensors on this board work fine.

ESP8266 communication issues

  • Arduino board: ESP8266 (ESP-01 Modul)

  • Arduino IDE version (found in Arduino -> About Arduino menu): 1.8.3 (esp8266 lib version 2.3.0)

  • List the steps to reproduce the problem below (if possible attach a sketch or
    copy the sketch code in too): I combined your SHT31 example with a REST example to get a REST API output for the SHT31, please confer the code. No matter what I try (I2C pullups, etc.) the SHT31 example works on an Arduino DUE but the ESP8266 cannot communicate with it. The I2C communication seems to work but returned values are always nan. readStatus always returns 65535.

/*
  This a simple example of the aREST Library for the ESP8266 WiFi chip.
  See the README file for more details.

  (Written in 2015 by Marco Schwartz under a GPL license.)

// SHT31
// This code is designed to work with the SHT31_I2CS I2C Mini Module available from ControlEverything.com.
*/
/*************************************************** 
 *    TODO:
 *      - sht31: not working...
 *               
 *      - test LED output setting ".../led/o"
 *      - LED switch OFF ".../led/1" does not work! (ON works)
 *        command string does not contain the value, try e.g. ".../led?1"
 *        same with ".../digital/1/w/0",  ".../digital/1/w/1" works, test  ".../digital/1/r"
 *      - still need "set fuse settings (clock, etc.)" ? (Tools > Burn Bootloader)
 *    
 *    Programm ESP8266 using Arduino Due Board as 3.3V USB2serial converter:
 *    - Links
 *      - Hardware: https://www.itead.cc/wiki/ESP8266_Serial_WIFI_Module#Hardware
 *      - Arduino IDE mit dem ESP8266: https://arduino-hannover.de/2015/04/08/arduino-ide-mit-dem-esp8266/
 *      - ESP8266 with SHT31(-D) WiFi WebServer: https://github.com/ControlEverythingCommunity/SHT31/blob/master/ESP8266/SHT31.ino
 *                                               https://www.controleverything.com/content/Humidity?sku=SHT31_I2CS#tabs-0-product_tabset-2
 *      - ESP8266 I2C example: http://pdacontrolen.com/esp8266-display-oled-i2c-client-irc/ (SCL-GPIO0, SDA-GPIO2)
 *      - https://learn.adafruit.com/esp8266-temperature-slash-humidity-webserver/uploading-to-the-esp8266
 *    - use Arduino IDE >=1.8.3
 *    - install ESP8266 option to IDE
 *      - File > Preferences > Additional Boards Manager URLs: http://arduino.esp8266.com/stable/package_esp8266com_index.json
 *      - Tools > Board: ??? > Boards Manager...
 *        search for: "esp8266" and install (esp8266 2.3.0)
 *    - connect ESP8266 to an Arduino Due by wiring:
 *        Arduino Due Pin   ESP8266 Pin
 *                    GND   1 GND
 *                 TX0->1   2 UTXD          --------------------
 *                          3 GPIO2         |2 1        x--=== |
 *               3.3V VCC   4 CH_PD         |4 3           === |
 *                    GND   5 GPIO0         |6 5  ESP8266  === |
 *                          6 RST           |8 7  board      | |
 *                 RX0<-0   7 URXD          --------------------
 *               3.3V VCC   8 VCC
 *        Arduino Due RESET pin needs to be connected to GND (in order to disable the chip/sketch)
 *        (ESP8266 RST kann offen bleiben oder PullUp)
 *    - select ESP8266:
 *      - Board: "Generic ESP8266 Module"
 *      - Flash Mode: "DIO"
 *      - Flash Frequency: "40MHz"
 *      - CPU Frequency: "80MHz"
 *      - Flash Size: "512K (64K SPIFFS)"
 *      - Debug port: "Disabled"
 *      - Debug Level: "None"
 *      - Reset Method: "ck"
 *      - Upload Speed: "115200"
 *      - Port: ???
 *    - select Programmer:
 *      - Tools > Programmer: "AVRISP mkII"
 *        (this is the default for Arduinos)
 *    - upload this code
 *        (if it does not work dis- and re-connect the Due/ESP8266 or try the RST pin)
 *    
 *                      ESP8266 Pin Layout
 *                    GND   1 GND
 *                          2 UTXD          --------------------
 *     Adafruit_SHT31 SDA   3 GPIO2         |2 1        .--=== |
 *               3.3V VCC   4 CH_PD         |4 3           === |
 *     Adafruit_SHT31 SCL   5 GPIO0         |6 5  ESP8266  === |
 *                          6 RST           |8 7  board      | |
 *                          7 URXD          --------------------
 *               3.3V VCC   8 VCC
 * ( NOTE! - It's very important to use pullups on the SDA & SCL lines! )
 * (         I2C pullups should be 1-100k, so 4.7k fits well.           )
 * 
 *    - use serial monitor
 *      - Tools > Serial Monitor
 *      - Both NL & CR
 *      - 115200 baud
 ****************************************************/

// Import required libraries
#include <ESP8266WiFi.h>
#include <aREST.h>

#include <Wire.h>
#include "Adafruit_SHT31.h"
//// SHT31 I2C address is 0x44(68)
//#define Addr 0x44

// Create aREST instance
aREST rest = aREST();

// WiFi parameters
const char* ssid = "your_wifi_network_name";
const char* password = "your_wifi_network_password";

// The port to listen for incoming TCP connections
#define LISTEN_PORT           80

// Create an instance of the server
WiFiServer server(LISTEN_PORT);

Adafruit_SHT31 sht31 = Adafruit_SHT31();

// Variables to be exposed to the API
float temperature;
float humidity;

String sDESC    = String("SHT31 Sensor I2C Mini Module");
String sDATE    = String(__DATE__);
String sTIME    = String(__TIME__);
String sIDE     = String(ARDUINO, DEC);
String sVERSION = String(__VERSION__);
String sFILE    = String(__FILE__);
//String sDEBUG   = String();

// Declare functions to be exposed to the API
int ledControl(String command);

void setup(void)
{
  // Start Serial
  Serial.begin(115200);

  Serial.println("SHT31 test");
  if (! sht31.begin(0x44)) {   // Set to 0x45 for alternate i2c addr
    Serial.println("Couldn't find SHT31");
//    while (1) delay(1);
  }
  Serial.println(sht31.readStatus());
  //void reset(void);
  //void heater(boolean);

  // Init variables and expose them to REST API
  temperature = 24;
  humidity = 40;
//  rest.variable("temperature",&temperature);
//  rest.variable("humidity",&humidity);
//  temperature = sht31.readTemperature();
//  humidity = sht31.readHumidity();
  rest.variable("temperature",&temperature);
  rest.variable("humidity",&humidity);

  rest.variable("DESC",&sDESC);
  rest.variable("DATE",&sDATE);
  rest.variable("TIME",&sTIME);
  rest.variable("IDE",&sIDE);
  rest.variable("VERSION",&sVERSION);
  rest.variable("FILE",&sFILE);
//  rest.variable("DEBUG",&sDEBUG);
 
  // Function to be exposed
  rest.function("led",ledControl);

  // Give name & ID to the device (ID should be 6 characters long)
  rest.set_id("1");
  rest.set_name("esp8266");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());

  Serial.flush();

  // Flash LED 2x to signal "boot ok"
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because 
                                    // it is acive low on the ESP-01)
  delay(500);                       // Wait
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(500);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
  digitalWrite(LED_BUILTIN, HIGH);
//  pinMode(LED_BUILTIN, INPUT);      // reset to default (does not work - freezes)

//  sDEBUG = String("boot ok");
}

void loop() {

  // Handle REST calls
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  while(!client.available()){
    delay(1);
  }
  rest.handle(client);

  // Update Sensor Measurements
  temperature = sht31.readTemperature();
  humidity = sht31.readHumidity();
//  rest.variable("temperature",&temperature);
//  rest.variable("humidity",&humidity);
//  handleroot();

}

// Custom function accessible by the API
int ledControl(String command) {

  // Update Sensor Measurements
  temperature = sht31.readTemperature();
  humidity = sht31.readHumidity();
//  rest.variable("temperature",&temperature);
//  rest.variable("humidity",&humidity);
//  handleroot();

  // Get state from command
  int state = command.toInt();
//  sDEBUG = String(command);

  digitalWrite(LED_BUILTIN,state);
  return 1;
}

// from SH31.ino
/*void handleroot()
{
  unsigned int data[6];

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Send 16-bit command byte
  Wire.write(0x2C);
  Wire.write(0x06);
  // Stop I2C transmission
  Wire.endTransmission();
  delay(300);

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Stop I2C Transmission
  Wire.endTransmission();

  // Request 6 bytes of data
  Wire.requestFrom(Addr, 6);

  // Read 6 bytes of data
  // temp msb, temp lsb, temp crc, hum msb, hum lsb, hum crc
  if (Wire.available() == 6)
  {
    data[0] = Wire.read();
    data[1] = Wire.read();
    data[2] = Wire.read();
    data[3] = Wire.read();
    data[4] = Wire.read();
    data[5] = Wire.read();
  }
  // Convert the data
  int temp = (data[0] * 256) + data[1];
  //cTemp = -45.0 + (175.0 * temp / 65535.0);
  temperature = -45.0 + (175.0 * temp / 65535.0);
  //fTemp = (cTemp * 1.8) + 32.0;
  humidity = (100.0 * ((data[3] * 256.0) + data[4])) / 65535.0;

  // Output data to serial monitor
  Serial.print("Temperature in Celsius :");
  //Serial.print(cTemp);
  Serial.print(temperature);
  Serial.println(" C");
  //Serial.print("Temperature in Fahrenheit :");
  //Serial.print(fTemp);
  //Serial.println(" F");
  Serial.print("Relative Humidity :");
  Serial.print(humidity);
  Serial.println(" %RH");
  delay(500);
}*/

ESP32S Core Dumps upon reading

  • Arduino board: ESP32S

  • Arduino IDE version (found in Arduino -> About Arduino menu): 1.8.16

  • I've connected the SHT31-D to an ESP32S which reports the sensor values over UDP Broadcast. These include:
    MPL3115A2 over I2C, an LDR, and a PIR (analog & digital respectively. Independently, the SHT-31 reports the values correctly via the demo sketch, however, upon reading the temperature the core panics.

The following error message is thrown during runtime. It seems as if there are null pointers being referenced, but why this occurs is not clear.

Guru Meditation Error: Core 1 panic'ed (LoadProhibited). Exception was unhandled.

Core 1 register dump: PC : 0x400d32eb PS : 0x00060f30 A0 : 0x800d4a99 A1 : 0x3ffb26b0 A2 : 0x00000000 A3 : 0x3ffb26de A4 : 0x00000002 A5 : 0x00000001 A6 : 0x00000000 A7 : 0x00000000 A8 : 0x800d6c1e A9 : 0x3ffb2690 A10 : 0x00000001 A11 : 0x00000000 A12 : 0x00000000 A13 : 0x00000000 A14 : 0x3ffb8a28 A15 : 0x00000000 SAR : 0x00000020 EXCCAUSE: 0x0000001c EXCVADDR: 0x0000000c LBEG : 0x40089cc5 LEND : 0x40089cd5 LCOUNT : 0xfffffffd

Backtrace:0x400d32e8:0x3ffb26b00x400d4a96:0x3ffb26d0 0x400d4aa9:0x3ffb2700 0x400d4b4d:0x3ffb2730 0x400d2b75:0x3ffb2750 0x400d66c9:0x3ffb2820

ELF file SHA256: 0000000000000000

Reduce delay before reading data

Hello,
The following delay shouldn't me smaller? 500ms is probably overkill, as the datasheet specifies the maximum measuring time for the high repeatability as 15ms.

I suggest changing it to 20ms as it would still provide a margin and would be much faster.

Thanks

Add function for reading serial

Is it possible to add this function?
https://sensirion.github.io/python-i2c-sht/0.2.0/_modules/sensirion_i2c_sht/sht3x/commands.html

Adafruit_SHT31.h

#define SHT31_READSERIAL 0x3780
...
class Adafruit_SHT31 {
public:
  Adafruit_SHT31(TwoWire *theWire = &Wire);
  ~Adafruit_SHT31();

  ...
  uint32_t readSerial(void);
  ....

Adafruit_SHT31.cpp

uint32_t Adafruit_SHT31::readSerial(void) {
  writeCommand(SHT31_READSERIAL);
  
  delay(10);
  
  uint8_t reply[6];
  if (!i2c_dev->read(reply, sizeof(reply))) {
    return false;
  }

  if ((crc8(reply, 2) != reply[2]) || (crc8(reply + 3, 2) != reply[5])) {
    return false;
  }

  uint32_t serial = 0;
  serial = reply[0];
  serial <<= 8;
  serial |= reply[1];
  serial <<= 8;
  serial |= reply[3];
  serial <<= 8;
  serial |= reply[4];

  return serial;
}

License is unclear

This library says it is licensed under the "BSD" license, but that has multiple variations. I cannot find the actual license text in the repository either, so this makes it ambiguous what license is used exactly. Could you clarify, e.g. by including the full license text in the source files or in a LICENSE file and referring to that?

Also, the example does not state any license at all in the source file itself, which would be more explicit if it did.

Arduino nano every hangs after a few minutes

Humidity and Temperature data is received correctly by Serial, but after a random number of minutes (2min to 10min) arduino hangs, and stops sending data.
I added the code the function to toggle the pin 13 led each time it sends data, it hangs too.

  • Arduino board: Arduino Nano Every

  • Arduino IDE version : 1.8.13

  • Code

#include <Arduino.h>
#include <Wire.h>
#include "Adafruit_SHT31.h"
 
Adafruit_SHT31 sht31 = Adafruit_SHT31();
const int led = 13;
 
void setup() 
{
  delay(100);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  if (! sht31.begin(0x44)) 
  {
    Serial.println("Couldn't find SHT31");
    while (1) delay(1);
  }
}
 
void loop() 
{
  float t = sht31.readTemperature();
  float h = sht31.readHumidity();
 
  if (! isnan(t)) 
  {
    Serial.print("Temp *C = "); Serial.println(t);
  } 
  else 
  { 
    Serial.println("Failed to read temperature");
  }
 
  if (! isnan(h)) 
  {
    Serial.print("Hum. % = "); Serial.println(h);
  } 
  else 
  { 
    Serial.println("Failed to read humidity");
  }
  Serial.println();
  digitalWrite(led, !digitalRead(led));
  delay(1000);
}

minus temperatures

Hello, since version 1.1.4, negative temperatures are displayed incorrectly. When I run the sht31test sketch I get the following output at negative temperatures Temp * C = 42949648.00

Negative readings?

Hi there,

I'm trying to read outdoor values, but something is wrong, I'm getting wrong readings.

SHT3x readings:

Temperature: 3.59c
Humidity: 68.50%

But, the real values should be:

Temperature: -0.90c
Humidity: 96.00 %

So, can you tell me what is wrong here?

Already tryied a second sensor, but got same reagings.

Using: Arduino IDE v1.8.2, ESP8266 Core v2.3.0 with WeMos D1 mini board.

Kind Regards,
Viktor

Header file does not check to see if already included

Wish the main header file checked to see if it was previously loaded, like most other header files.

Something like: (note, I only added the #ifndef #define and #endif

#ifndef ADAFRUIT_SHT31_H
#define ADAFRUIT_SHT31_H
#if (ARDUINO >= 100)
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "Wire.h"

#define SHT31_DEFAULT_ADDR 0x44
#define SHT31_MEAS_HIGHREP_STRETCH 0x2C06
#define SHT31_MEAS_MEDREP_STRETCH 0x2C0D
#define SHT31_MEAS_LOWREP_STRETCH 0x2C10
#define SHT31_MEAS_HIGHREP 0x2400
#define SHT31_MEAS_MEDREP 0x240B
#define SHT31_MEAS_LOWREP 0x2416
#define SHT31_READSTATUS 0xF32D
#define SHT31_CLEARSTATUS 0x3041
#define SHT31_SOFTRESET 0x30A2
#define SHT31_HEATEREN 0x306D
#define SHT31_HEATERDIS 0x3066

class Adafruit_SHT31 {
public:
Adafruit_SHT31();
boolean begin(uint8_t i2caddr = SHT31_DEFAULT_ADDR);
float readTemperature(void);
float readHumidity(void);
uint16_t readStatus(void);
void reset(void);
void heater(boolean);
uint8_t crc8(const uint8_t *data, int len);

private:
boolean readTempHum(void);
void writeCommand(uint16_t cmd);

uint8_t _i2caddr;
boolean readData(void);
float humidity, temp;
};

#endif

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.