esp-open-rtos/extras/sht3x/README.md
Gunar Schorcht ac6797e916 Driver for Sensirion SHT3x temperature and humidity sensor readded (#453)
* Driver for Sensirion SHT3x sensor added

This is a driver for Sensirion SHT3x temperature and humidity sensors
connected via I2C.

This commit is a rebasing and contains some interface changes based on
the review from @ourairquality.

* SHT3x driver changes

Additional include to satisfy the Travis CI test build

* SHT3x driver - small changes

README.md has been shortened

* SHT3x driver - small changes

* SHT3x driver - small changes

- crc8 lookup table is now static to be held in flash memory
- special handling for the timer overflow in sht3x_is_measuring removed
- initialization reduced to availability check

* SHT3x driver - some small changes

- crc8 lookup table is now static to be held in flash memory
- special handling for the timer overflow in sht3x_is_measuring removed
- some whitespace removed
- initialization reduced to availability check

* SHT3x driver - some minor changes

- lookup tables made const to be held in flash
- crc8 computation changed to a non table lookup version
- measurement duration is now given in ticks and can be used directly
  for vTaskDelay (documentation and examples changed accordingly)

* SHT3x driver - documentation changed

* SHT3x driver - minor correction

- number of ticks for measurement duration takes now into account
  portTICK_PERIOD_MS

* SHT3x driver - minor correction

- number of ticks for measurement duration takes now into account
  portTICK_PERIOD_MS

* SHT3x driver - minor correction

- number of ticks for measurement duration takes now into account
  portTICK_PERIOD_MS

* SHT3x driver - minor correction

- number of ticks for measurement duration takes now into account
  portTICK_PERIOD_MS

* SHT3x driver - minor corrections

* SHT3x driver - minor corrections

* Driver for Sensirion SHT3x sensor added

This is a driver for Sensirion SHT3x temperature and humidity sensors
connected via I2C.

This commit is a rebasing and contains some interface changes based on
the review from @ourairquality.

SHT3x driver changes

- additional include to satisfy the Travis CI test build
- README.md has been shortened
- special handling for the timer overflow in sht3x_is_measuring removed
- some whitespaces removed
- crc8 computation changed to a non table lookup version
- measurement duration is now given in ticks and can be used directly
  for vTaskDelay (documentation and examples changed accordingly)
- number of ticks for measurement duration takes now into account
  portTICK_PERIOD_MS
- clock stretching disabled on sensor to avoid blocking when data are
  not ready to read
- calculation of maesurement duration adds now one and a half ticks to
  be sure that measurement duration is not too short
- function sht3x_is_measuring is now private and only for internal use,
  user task has always to use function vTaskDelay to wait for
  measurement results
- function sht3x_is_measuring was simplified and returns now just a
  boolean value
- private function sht3x_reset added which is used to reset the sensor
  during initialization
- active flag in sensor data structure not needed anymore
- function sht3_get_raw_data simplified
- function sht3x_start_measurement returns now only a boolean
- function sht3x_start_measurement does not check anymore whether there is
  already a measurment running
- new function sht3x_get_measurement_duration which returns the measurement
  duration in ticks for configured repeatability

* SHT3x driver minor changes

- type sht3x_values_t replaced by separate float values
- additional repeatability parameter defined for function sht3x_start_measurement
- parameter of function sht3x_get_measurement_duration changed from
  sht3x_sensort_t to sht3_repeat_t
- sensor modes and repeatability levels extended by prefix sht3x_

* SHT3x driver minor changes

- new high level function sht3x_measure added, it comprises all three
  steps to perform one measurement in only one function
- example with two sensors removed

* SHT3x driver small correction
2017-10-23 23:39:48 +02:00

309 lines
14 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Driver for **SHT3x** digital **temperature and humidity sensor**
This driver is written for usage with the ESP8266 and FreeRTOS using the I2C interface driver. It supports multiple SHT3x sensors connected to the same or different I2C interfaces.
## About the sensor
SHT3x is a digital temperature and humidity sensor that uses an I2C interface with up to 1 MHz communication speed. It can operate with **three levels of repeatability** (low, medium and high) and in two different modes, the **single shot data acquisition mode** (or short **single shot mode**) and the **periodic data acquisition mode** (or short **periodic mode**).
## Measurement process
Once the SHT3x sensor is initialized, it can be used for measurements.
### Single shot mode
In **single shot mode**, a measurement command triggers the acquisition of **exactly one data pair**. Each data pair consists of temperature and humidity as 16-bit decimal values.
Due to the measurement duration of up to 15 ms, the measurement process is separated into steps to avoid blocking the user task during measurements:
1. Trigger the sensor with function ```sht3x_start_measurement``` to perform exactly one single measurement.
2. Wait the measurement duration using function ```vTaskDelay``` until the results are available . Use either a constant duration of at least 30 ms or the duration in RTOS ticks returned from function ```sht3x_get_measurement_duration``` to wait.
3. Fetch the results as floating point sensor values with function ```sht3x_get_results``` or as raw data with function ```sht3x_get_raw_data```.
In the *single shot mode*, the user task has to perform all steps every time new sensor values are needed.
For convenience a high level function ```sht3x_measure``` that comprises all three steps above in only one function to perform a measurement. This function is the easiest way to use the sensor. It is most suitable for users that don't want to have the control on sensor details.
The advantage of this mode is that the sensor can switch between successive measurements into the sleep mode, which is more energy-efficient. This is particularly useful when the measurement rate is less than 1 measurement per second.
### Periodic mode
In this mode, one issued measurement command yields a stream of data pairs. Each data pair consists again of temperature and humidity as 16-bit decimal values. As soon as the measurement command has been sent to the sensor, it automatically performs measurements **periodically at a rate of 0.5, 1, 2, 4 or 10 measurements per second (mps)**. The data pairs can be fetched with the same rate or a lower rate.
As in *single shot mode*, the measurement process is separated into the following steps:
1. Trigger the sensor with function ```sht3x_start_measurement``` with a given rate to start periodic measurements.
2. Wait the measurement duration using function ```vTaskDelay``` until the first results are available . Use either a constant duration of at least 30 ms or the duration in RTOS ticks returned from function ```sht3x_get_measurement_duration``` to wait.
3. Fetch the results as floating point sensor values with function ```sht3x_get_results``` or as raw data with function ```sht3x_get_raw_data```.
However, in contrast to the *single shot mode*, steps 1 and 2 have to be executed only once. Once the measurement is started, the user task hast can simply fetch data periodically.
**Please note:** The rate of fetching the measurement results must not be greater than the rate of periodic measurements of the sensor. Even more, it *should be less* to avoid conflicts caused by the timing tolerance of the sensor.
## Measurement results
Once new measurement results are available, either function ```sht3x_get_raw_data``` or function ```sht3x_get_results``` can be used to fetch the results.
Function ```_sht3x_get_raw_data``` fetches only raw sensor data in 16-decimal format, checks the CRC checksums and stores them in an byte array of type ```sht3x_raw_data_t```. The user task then can use them directly or to call function ```sht3x_compute_values``` to compute floating point sensor values from them.
Function ```sht3x_get_results``` combines function ```sht3x_read_raw_data``` and function
```sht3x_compute_values``` to get the sensor values. This is the preferred approach to get sensor values by the user task.
## Error Handling
Most driver functions return a simple boolean value to indicate whether its execution was successful or an error happened. In the latter case, the member ```error_code``` of the sensor device data structure is set which indicates what error happened.
There are two different error levels that are ORed into one single ```error_code```, errors in the I2C communication and errors with the SHT3x sensor itself. To test for a certain error you can AND the *error_code* with one of the error masks, ```SHT3x_I2C_ERROR_MASK``` for I2C errors and ```SHT3x_DRV_ERROR_MASK``` for other errors and then test for a certain error code.
## Repeatability
The SHT3x sensor supports **three levels of repeatability** (low, medium and high). Repeatability is the variation in measurement results taken by the sensor under the same conditions, and in a short period of time. It is a measure for the noise on the physical sensor output. The higher the repeatability the smaller are changes in the output of subsequent measurements.
The repeatability settings influences the measurement duration as well as the power consumption of the sensor. The measurement takes 3 ms with low repeatability, 5 ms with medium repeatability and 13.5 ms with high repeatability. That is, the measurement produces a noticeable delay in execution.
While the sensor measures at the lowest repeatability, the average current consumption is 800 μA. That is, the higher the repeatability level, the longer the measurement takes and the higher the power consumption. The sensor consumes only 0.2 μA in standby mode.
The repeatability used for a measurement is specified as parameter of function ```sht3x_start_measurement```.
## Usage
Before using the SHT3x driver, function ```i2c_init``` needs to be called for each I2C interface to setup them.
```
#include "sht3x/sht3x.h"
...
#define I2C_BUS 0
#define I2C_SCL_PIN GPIO_ID_PIN((5))
#define I2C_SDA_PIN GPIO_ID_PIN((4))
...
i2c_init(I2C_BUS, I2C_SCL_PIN, I2C_SDA_PIN, I2C_FREQ_100K))
...
```
Once I2C interfaces to be used are initialized, function ```sht3x_init_sensor``` has to be called for each SHT3x sensor to initialize the sensor and to check its availability as well as its error state. The parameters specify the I2C bus to which it is connected and its I2C slave address.
```
static sht3x_sensor_t* sensor; // pointer to sensor device data structure
...
if ((sensor = sht3x_init_sensor (I2C_BUS, SHT3x_ADDR_2)))
{
...
}
```
Function ```sht3x_init_sensor``` returns a pointer to the sensor device data structure or NULL in case of error.
Last, the user task that uses the sensor has to be created.
```
xTaskCreate(user_task, "user_task", 256, NULL, 2, 0);
```
In **periodic mode**, the user task has to start the periodic measurement only once at the beginning of the task. After that, it has only to wait for the results of the first measurement. In the task loop itself, it simply fetches the next measurement results in each cycle.
Thus, in this mode the user task could look like the following:
```
void user_task (void *pvParameters)
{
float temperature;
float humidity;
// Start periodic measurements with 1 measurement per second.
sht3x_start_measurement (sensor, sht3x_periodic_1mps, sht3x_high);
// Wait until first measurement is ready (constant time of at least 30 ms
// or the duration returned from *sht3x_get_measurement_duration*).
vTaskDelay (sht3x_get_measurement_duration(sht3x_high));
TickType_t last_wakeup = xTaskGetTickCount();
while (1)
{
// Get the values and do something with them.
if (sht3x_get_results (sensor, &temperature, &humidity))
printf("%.3f SHT3x Sensor: %.2f °C, %.2f %%\n",
(double)sdk_system_get_time()*1e-3, temperature, humidity);
// Wait until 2 seconds (cycle time) are over.
vTaskDelayUntil(&last_wakeup, 2000 / portTICK_PERIOD_MS);
}
}
```
At the beginning of the task, the periodic measurement is started with function ```sht3x_start_measurement``` at high repeatability level and a rate of 1 measurement per second. The task is then delayed with function ```vTaskDelay``` to wait for first measurement results. The duration can be either a constant time of at least 30 ms or the duration returned by ```sht3x_get_measurement_duration```, as in the example. Inside the task loop, simply the measurement results are fetched periodically using function ```sht3x_get_results``` every 2 seconds.
**Please note:** The rate of fetching the measurement results must be not greater than the rate of periodic measurements of the sensor, however, it *should be less* to avoid conflicts caused by the timing tolerance of the sensor.
In **single shot mode**, the measurement has to be triggered
in each cycle. Also the waiting for measurement results is required in each cylce, before the results can be fetched.
Thus the user task could look like the following:
```
void user_task (void *pvParameters)
{
float temperature;
float humidity;
TickType_t last_wakeup = xTaskGetTickCount();
uint8_t duration = sht3x_get_measurement_duration(sht3x_high);
while (1)
{
// Trigger one measurement in single shot mode with high repeatability.
sht3x_start_measurement (sensor, sht3x_single_shot, sht3x_high);
// Wait until measurement is ready (constant time of at least 30 ms
// or the duration returned from *sht3x_get_measurement_duration*).
vTaskDelay (duration);
// retrieve the values and do something with them
if (sht3x_get_results (sensor, &temperature, &humidity))
printf("%.3f SHT3x Sensor: %.2f °C, %.2f %%\n",
(double)sdk_system_get_time()*1e-3, temperature, humidity);
// wait until 5 seconds are over
vTaskDelayUntil(&last_wakeup, 5000 / portTICK_PERIOD_MS);
}
}
```
In contrast to the *periodic mode*, the function ```sht3x_start_measurement``` is called inside the task loop to start exactly one measurement in each cycle. The task is then also delayed every time using function ```vTaskDelay``` before the results are fetched with function ```sht3x_get_results```.
Alternatively, user task can use the high level function ```sht3x_measure``` that comprises these steps in only one function. This would simplify the user task that would then look like the following:
```
void user_task (void *pvParameters)
{
float temperature;
float humidity;
TickType_t last_wakeup = xTaskGetTickCount();
while (1)
{
// perform one measurement and do something with the results
if (sht3x_measure (sensor, &temperature, &humidity))
printf("%.3f SHT3x Sensor: %.2f °C, %.2f %%\n",
(double)sdk_system_get_time()*1e-3, temperature, humidity);
// wait until 5 seconds are over
vTaskDelayUntil(&last_wakeup, 5000 / portTICK_PERIOD_MS);
}
}
```
The code could be extended by an error handling. In the event of an error, most driver functions set the ```error_code``` element of the sensor device data structure. This indicates which error has occurred. Error codes are a combination of I2C communication error codes and SHT3x sensor error codes. To test for a particular error, the *error code* has to be ANDed with one of the error masks ```SHT3x_I2C_ERROR_MASK``` or ```SHT3x_DRV_ERROR_MASK``` and then tested for a certain value.
For example, error handling for ```sht3x_get_results``` could look like:
```
if (!sht3x_get_results (sensor, &values))
{
// error happened
switch (sensor->error_code & SHT3x_I2C_ERROR_MASK)
{
case SHT3x_I2C_BUSY: ...
case SHT3x_I2C_READ_FAILED: ...
...
}
switch (sensor->error_code & SHT3x_DRV_ERROR_MASK)
{
case SHT3x_MEAS_NOT_RUNNING: ...
case SHT3x_READ_RAW_DATA_FAILED: ...
case SHT3x_WRONG_CRC_TEMPERATURE: ...
...
}
}
```
## Full Example
```
#include "espressif/esp_common.h"
#include "esp/uart.h"
#include "FreeRTOS.h"
#include "task.h"
// include SHT3x driver
#include "sht3x/sht3x.h"
// define I2C interfaces at which SHTx3 sensors are connected
#define I2C_BUS 0
#define I2C_SCL_PIN GPIO_ID_PIN((5))
#define I2C_SDA_PIN GPIO_ID_PIN((4))
static sht3x_sensor_t* sensor; // sensor device data structure
/*
* User task that triggers a measurement every 5 seconds. Due to
* power efficiency reasons, it uses the SHT3x *sht3x_single_shot*.
*/
void user_task (void *pvParameters)
{
float temperature;
float humidity;
TickType_t last_wakeup = xTaskGetTickCount();
// get the measurement duration for high repeatability;
uint8_t duration = sht3x_get_measurement_duration(sht3x_high);
while (1)
{
// Trigger one measurement in single shot mode with high repeatability.
sht3x_start_measurement (sensor, sht3x_single_shot, sht3x_high);
// Wait until measurement is ready (constant time of at least 30 ms
// or the duration returned from *sht3x_get_measurement_duration*).
vTaskDelay (duration);
// retrieve the values and do something with them
if (sht3x_get_results (sensor, &temperature, &humidity))
printf("%.3f SHT3x Sensor: %.2f °C, %.2f %%\n",
(double)sdk_system_get_time()*1e-3, temperature, humidity);
// wait until 5 seconds are over
vTaskDelayUntil(&last_wakeup, 5000 / portTICK_PERIOD_MS);
}
}
void user_init(void)
{
// Set UART Parameter.
uart_set_baud(0, 115200);
// Give the UART some time to settle.
sdk_os_delay_us(500);
// Init I2C bus interfaces at which SHT3x sensors are connected
// (different busses are possible).
i2c_init(I2C_BUS, I2C_SCL_PIN, I2C_SDA_PIN, I2C_FREQ_100K);
// Create the sensors.
if ((sensor = sht3x_init_sensor (I2C_BUS, SHT3x_ADDR_2)))
{
// Create a user task that uses the sensors.
xTaskCreate(user_task, "user_task", 256, NULL, 2, 0);
}
// That's it.
}
```
## Further Examples
See also the examples in the examples directory [examples directory](../../examples/sht3x/README.md).