diff --git a/docs/source/Plugin/P000_commands.repl b/docs/source/Plugin/P000_commands.repl index 4132fd2bb..4716f1a75 100644 --- a/docs/source/Plugin/P000_commands.repl +++ b/docs/source/Plugin/P000_commands.repl @@ -180,7 +180,18 @@ ``Gateway,192.168.1.1`` - Example output: ``Gateway:192.168.10.254(DHCP)``" + Example output: ``Gateway:192.168.10.254(DHCP)`` + " + " + HiddenSSID"," + :red:`Internal`"," + Get or set the Include Hidden SSID setting + + ``HiddenSSID`` + + ``HiddenSSID,true`` (can use ``1``, ``true`` or ``on`` to enable, and ``0``, ``false`` or ``off`` to disable) + + Example output: ``Include Hidden SSID:true``" " I2Cscanner"," :red:`Internal`"," @@ -386,6 +397,8 @@ On completion of the command, the returned status code can be handled in a generated event, f.e. ``http#hostname=404`` for not found error, or ``http#hostname=200`` for success. + See also: ``PutToHTTP`` and ``SendToHTTP`` + Added: 2023-01-15 " " @@ -425,6 +438,65 @@ ``Publish,[,]``" " + PutToHTTP"," + :green:`Rules`"," + *Syntax format 1:* + + ``PutToHTTP,[:@],,,[][,]`` + + Send a command to another network device via HTTP using the http ``PUT`` method. + + ```` can be either a domain name or IP address. + + ```` is the port to connect to, usually 80 for a HTTP site. + + ```` the path on the server to put the message to. + + *Syntax format 2:* + + ``PutToHTTP,http://[:@],[][,]`` + + ```` is the full hostname (or IP address) and path on the server to put the content to. + + *For both syntax formats:* + + ```` is an optional user to supply for Basic authentication. + + ```` is an optional password to supply for Basic authentication. + + ```` when provided will be added to the header of the ``PUT`` message, has to be in ``:`` format. Can be used to supply a ``Authorization: Bearer `` and/or ``api-key:`` (instead of a user/password Basic authentication) and a ``Content-Type: ``. Multiple entries have to be separated by a NewLine (``%LF%``) to be processed correctly. When not used (empty) and ```` *is used*, the comma should still be included! + + ```` is the optional content to include in the ``PUT`` message. Can be anything, f.e. a JSON formatted string, like in the example below. + + Syntax examples: + + ``PutToHTTP,,,,[][,]`` + + ``PutToHTTP,:@,,,[][,]`` + + ``PutToHTTP,http:///,[][,]`` + + ``PutToHTTP,http://:@/,[][,]`` + + ``PutToHTTP,http://:/,[][,]`` + + ``PutToHTTP,http://:@:/,[][,]`` + + Example using syntax format 1: + + ``PutToHTTP,user:password@192.168.1.100,8888,/someurl,'header1:value1%LF%header2:value2',`{'this':{'string':'can','be':'JSON','data':{'one':1,'two':2.0,'bool':true}}}``` + + Example using syntax format 2: + + ``PutToHTTP,http://user:password@192.168.1.100:8888/someurl,'header1:value1%LF%header2:value2',`{'this':{'string':'can','be':'JSON','data':{'one':1,'two':2.0,'bool':true}}}``` + + On completion of the command, the returned status code can be handled in a generated event, f.e. ``http#hostname=404`` for not found error, or ``http#hostname=200`` for success. + + See also: ``PostToHTTP`` and ``SendToHTTP`` + + Added: 2023-04-17 + " + " Reboot"," :red:`Internal`"," Reboot the ESP diff --git a/docs/source/Plugin/P106.rst b/docs/source/Plugin/P106.rst index b14f5100d..ebaf32c01 100644 --- a/docs/source/Plugin/P106.rst +++ b/docs/source/Plugin/P106.rst @@ -24,6 +24,53 @@ Used libraries: |P106_usedlibraries| Description ----------- +Plugin to use the Bosch BME680 and BME688 Temperature, Humidity, Barometric pressure and MOX Gas resistance values. + +.. warning:: For the BME688 sensor the AI features are not supported, only the BME680 features, as it is fully backward compatible. + +Specifications: + * Temperature (-40C to +85C) + * Relative humidity (0-100 %RH) + * Barometric pressure (300-1100 hPa) + * Gas resistance (can be used to determine IAQ, Index of Air Quality) + + +configuration +------------- + +.. image:: P106_DeviceConfiguration.png + +* **Name**: Required by ESPEasy, must be unique among the list of available devices/tasks. + +* **Enabled**: The device can be disabled or enabled. When not enabled the device should not use any resources. + +I2C options +^^^^^^^^^^^ + +* **I2C Address**: The device supports 2 addresses, that can be configured using the ``SDO`` pin: (not all boards have that pin available, but could use soldering-pads to configure the address) + +The available I2C settings here depend on the build used. At least the **Force Slow I2C speed** option is available, but selections for the I2C Multiplexer can also be shown. For details see the :ref:`Hardware_page` + +Device Settings +^^^^^^^^^^^^^^^ + +* **Altitude** When not at sea-level, the plugin can apply an altitude compensation on the **Pressure** value. + +* **Present `Gas` in Ohm (not kOhm)**: Normally the Gas resistance value, received from the MOX Gas sensor, is divided to be presented as kOhm, but with this setting checked, the native Ohm value is shown. + +Data Acquisition +^^^^^^^^^^^^^^^^ + +This group of settings, **Single event with all values** and **Send to Controller** settings are standard available configuration items. Send to Controller is only visible when one or more Controllers are configured. + +* **Interval** By default, Interval will be set to 60 sec. The data will be collected and optionally sent to any configured controllers using this interval. + +Values +^^^^^^ + +The plugin provides the ``Temperature``, ``Humidity``, ``Pressure`` and ``Gas`` values. A formula can be set to recalculate. The number of decimals can be set as desired. + +Per Value is a **Stats** checkbox available, that when checked, gathers the data and presents recent data in a graph, as described here: :ref:`Task Value Statistics: ` .. Events @@ -37,6 +84,8 @@ Change log ---------- .. versionchanged:: 2.0 - ... - |added| 2020-04-25 + +|changed| 2023-04-16 Renamed to BME68x, make ``Gas`` output scale configurable. ... + +|added| 2020-04-25 diff --git a/docs/source/Plugin/P106_DeviceConfiguration.png b/docs/source/Plugin/P106_DeviceConfiguration.png new file mode 100644 index 000000000..8d2c3fcbb Binary files /dev/null and b/docs/source/Plugin/P106_DeviceConfiguration.png differ diff --git a/docs/source/Plugin/P150.rst b/docs/source/Plugin/P150.rst new file mode 100644 index 000000000..a13450f8d --- /dev/null +++ b/docs/source/Plugin/P150.rst @@ -0,0 +1,155 @@ +.. include:: ../Plugin/_plugin_substitutions_p15x.repl +.. _P150_page: + +|P150_typename| +================================================== + +|P150_shortinfo| + +Plugin details +-------------- + +Type: |P150_type| + +Name: |P150_name| + +Status: |P150_status| + +GitHub: |P150_github|_ + +Maintainer: |P150_maintainer| + +Used libraries: |P150_usedlibraries| + +Description +----------- + +The Texas Instruments TMP117 High-accuracy temperature sensor offers an accuracy of 0.1°C in the range of -20°C to 50°C, and requires very low power when in shutdown mode. + +The low/high alarm options and accompanying ``INT`` pin, as provided by the sensor, are *not* implemented in this plugin. + +The datasheet offers the most up to date information: `Texas Instruments TMP117 Datasheet (online) `_ + +Hardware +-------- + +.. image:: P150_AdafruitTMP117.png + :height: 200 + +Adafruit TMP117 board. + +.. image:: P150_SparkfunTMP117.png + :height: 200 + +SparkFun TMP117 board. + +Configuration +------------- + +.. image:: P150_DeviceConfiguration.png + +* **Name**: Required by ESPEasy, must be unique among the list of available devices/tasks. + +* **Enabled**: The device can be disabled or enabled. When not enabled the device should not use any resources. + +I2C options +^^^^^^^^^^^ + +* **I2C Address**: The device supports up to 4 addresses, that can be configured using the ``ADDR`` pin: (not all boards have the ADDR pin directly available, but use soldering-pads to configure the address) + +.. csv-table:: + :header: "Address", "ADDR pin to:", "Remark" + :widths: 10, 10, 40 + + "0x48", "GND", "Default, also when not connected." + "0x49", "VCC / VIN", "" + "0x4A", "SDA", "" + "0x4B", "SCL", "" + +The available I2C settings here depend on the build used. At least the **Force Slow I2C speed** option is available, but selections for the I2C Multiplexer can also be shown. For details see the :ref:`Hardware_page` + +Device Settings +^^^^^^^^^^^^^^^ + +* **Temperature offset**: An offset from the current temperature can be applied in 0.1°C steps. The number of steps can be set here. + +* **Averaging**: The sensor supports several averaging options, to stabilize the measurement. By default the average of 8 measurements is used. + +.. image:: P150_AveragingOptions.png + +*No averaging*: This turns off averaging. + +*8 sample averaging*: Average the last 8 measured samples (default). + +*32 sample averaging*: Average the last 32 measured samples. + +*64 sample averaging*: Average the last 64 measured samples. + +.. .. separator + +* **Conversion mode**: The default measuring conversion mode is to continuously perform measurements. + +.. image:: P150_ConversionModeOptions.png + +*Continuous*: Continuously perform measurements, with a configurable cycle-time (see below). + +*One-shot*: Perform a single measurement, then go into shutdown mode to conserve power. When the values are retrieved by the Interval event cycle, the One-shot mode is started, and read as soon as available (once per second). This value is returned on the next Interval, and a new One-shot measurement is started. + +.. warning:: When changing this setting, the current settings are saved, and the page is reloaded, to show or hide the **Continuous conversion cycle time** setting, as that is only available/applicable for Continuous mode. + +* **Continuous conversion cycle time**: The delay between actual measurements in Continuous conversion mode. When this is set to a value longer than the **Interval** time, some of the Interval readings will return the previous values, as no new value has been read yet. It is advised to set the **Interval** higher than the configured cycle time. + +.. image:: P150_CycleTimeOptions.png + +*15.5 msec*: A new measurement is performed every 15.5 milliseconds. + +*125 msec*: A new measurement is performed every 125 milliseconds. + +*250 msec*: A new measurement is performed every 250 milliseconds. + +*500 msec*: A new measurement is performed every 500 milliseconds. + +*1 sec*: A new measurement is performed every second. + +*4 sec*: A new measurement is performed every 4 seconds. + +*8 sec*: A new measurement is performed every 8 seconds. + +*16 sec*: A new measurement is performed every 16 seconds. + +This option is only available if **Conversion mode** is set to **Continuous**. + +Output +^^^^^^ + +* **Enable 'Raw' value**: Select Yes if you want to include the **Raw** value on the Devices overview page, and when sent to controllers. This contains the raw digital value read from the sensor. + +.. warning:: When changing this setting, the current settings are saved, and the page is reloaded, to show or hide the **Raw** Value (bottom of the page). + +* **Log measured values (INFO)**: When checked, the values will be included in the serial log, when that is enabled, on INFO level. + +* **Log low-level values (INFO)**: When checked, the values during the actual read (max. 1 per second) will be output to the serial log, on INFO level. This can be used for debugging purposes. May not be available in all builds to save space in the bin file. + +Data Acquisition +^^^^^^^^^^^^^^^^ + +This group of settings, **Single event with all values** and **Send to Controller** settings are standard available configuration items. Send to Controller is only visible when one or more Controllers are configured. + +* **Interval** By default, Interval will be set to 60 sec. The data will be collected and optionally sent to any configured controllers using this interval. If the Interval is set lower than the **Continuous conversion cycle time**, the interval will return the previously measured value until an actual measurement has been retrieved from the sensor. + +Values +^^^^^^ + +The plugin provides the ``Temperature`` and ``Raw`` values. Raw can be disabled, see above. A formula can be set to recalculate. The number of decimals can be set as desired, and defaults to 2 for Temperature, and 0 for Raw. + +Per Value is a **Stats** checkbox available, that when checked, gathers the data and presents recent data in a graph, as described here: :ref:`Task Value Statistics: ` + +Change log +---------- + +.. versionchanged:: 2.0 + ... + + |added| + 2023-04-15 Initial release version. + diff --git a/docs/source/Plugin/P150_AdafruitTMP117.png b/docs/source/Plugin/P150_AdafruitTMP117.png new file mode 100644 index 000000000..5db0d29c5 Binary files /dev/null and b/docs/source/Plugin/P150_AdafruitTMP117.png differ diff --git a/docs/source/Plugin/P150_AveragingOptions.png b/docs/source/Plugin/P150_AveragingOptions.png new file mode 100644 index 000000000..3fb32b718 Binary files /dev/null and b/docs/source/Plugin/P150_AveragingOptions.png differ diff --git a/docs/source/Plugin/P150_ConversionModeOptions.png b/docs/source/Plugin/P150_ConversionModeOptions.png new file mode 100644 index 000000000..a40d688fd Binary files /dev/null and b/docs/source/Plugin/P150_ConversionModeOptions.png differ diff --git a/docs/source/Plugin/P150_CycleTimeOptions.png b/docs/source/Plugin/P150_CycleTimeOptions.png new file mode 100644 index 000000000..b5fcc1001 Binary files /dev/null and b/docs/source/Plugin/P150_CycleTimeOptions.png differ diff --git a/docs/source/Plugin/P150_DeviceConfiguration.png b/docs/source/Plugin/P150_DeviceConfiguration.png new file mode 100644 index 000000000..e157da6f2 Binary files /dev/null and b/docs/source/Plugin/P150_DeviceConfiguration.png differ diff --git a/docs/source/Plugin/P150_EnableRawValueOptions.png b/docs/source/Plugin/P150_EnableRawValueOptions.png new file mode 100644 index 000000000..581997a6d Binary files /dev/null and b/docs/source/Plugin/P150_EnableRawValueOptions.png differ diff --git a/docs/source/Plugin/P150_SparkfunTMP117.png b/docs/source/Plugin/P150_SparkfunTMP117.png new file mode 100644 index 000000000..bba3e13d2 Binary files /dev/null and b/docs/source/Plugin/P150_SparkfunTMP117.png differ diff --git a/docs/source/Plugin/_Plugin.rst b/docs/source/Plugin/_Plugin.rst index 4564c3c06..24b9d9479 100644 --- a/docs/source/Plugin/_Plugin.rst +++ b/docs/source/Plugin/_Plugin.rst @@ -369,6 +369,7 @@ There are different released versions of ESP Easy: ":ref:`P144_page`","|P144_status|","P144" ":ref:`P145_page`","|P145_status|","P145" ":ref:`P148_page`","|P148_status|","P148" + ":ref:`P150_page`","|P150_status|","P150" ":ref:`P151_page`","|P151_status|","P151" diff --git a/docs/source/Plugin/_plugin_categories.repl b/docs/source/Plugin/_plugin_categories.repl index 77869d4fe..a4d0c96da 100644 --- a/docs/source/Plugin/_plugin_categories.repl +++ b/docs/source/Plugin/_plugin_categories.repl @@ -7,7 +7,7 @@ .. |Plugin_Energy_AC| replace:: :ref:`P076_page`, :ref:`P077_page`, :ref:`P078_page`, :ref:`P102_page`, :ref:`P108_page` .. |Plugin_Energy_DC| replace:: :ref:`P027_page`, :ref:`P085_page`, :ref:`P115_page`, :ref:`P132_page` .. |Plugin_Energy_Heat| replace:: :ref:`P088_page`, :ref:`P093_page` -.. |Plugin_Environment| replace:: :ref:`P004_page`, :ref:`P005_page`, :ref:`P006_page`, :ref:`P014_page`, :ref:`P024_page`, :ref:`P028_page`, :ref:`P030_page`, :ref:`P031_page`, :ref:`P032_page`, :ref:`P034_page`, :ref:`P039_page`, :ref:`P047_page`, :ref:`P051_page`, :ref:`P068_page`, :ref:`P069_page`, :ref:`P072_page`, :ref:`P103_page`, :ref:`P105_page`, :ref:`P106_page`, :ref:`P151_page` +.. |Plugin_Environment| replace:: :ref:`P004_page`, :ref:`P005_page`, :ref:`P006_page`, :ref:`P014_page`, :ref:`P024_page`, :ref:`P028_page`, :ref:`P030_page`, :ref:`P031_page`, :ref:`P032_page`, :ref:`P034_page`, :ref:`P039_page`, :ref:`P047_page`, :ref:`P051_page`, :ref:`P068_page`, :ref:`P069_page`, :ref:`P072_page`, :ref:`P103_page`, :ref:`P105_page`, :ref:`P106_page`, :ref:`P150_page`, :ref:`P151_page` .. |Plugin_Extra_IO| replace:: :ref:`P011_page`, :ref:`P022_page` .. |Plugin_Gases| replace:: :ref:`P049_page`, :ref:`P052_page`, :ref:`P083_page`, :ref:`P090_page`, :ref:`P117_page`, :ref:`P127_page`, :ref:`P135_page`, :ref:`P145_page` .. |Plugin_Generic| replace:: :ref:`P003_page`, :ref:`P026_page`, :ref:`P033_page`, :ref:`P037_page`, :ref:`P081_page`, :ref:`P100_page` diff --git a/docs/source/Plugin/_plugin_substitutions_p10x.repl b/docs/source/Plugin/_plugin_substitutions_p10x.repl index 646f2e5c0..5da2f35b2 100644 --- a/docs/source/Plugin/_plugin_substitutions_p10x.repl +++ b/docs/source/Plugin/_plugin_substitutions_p10x.repl @@ -92,16 +92,16 @@ .. |P105_datasheet3| replace:: http://www.aosong.com/en/products-60.html -.. |P106_name| replace:: :cyan:`BME680` +.. |P106_name| replace:: :cyan:`BME68x` .. |P106_type| replace:: :cyan:`Environment` -.. |P106_typename| replace:: :cyan:`Environment - BME680` +.. |P106_typename| replace:: :cyan:`Environment - BME68x` .. |P106_porttype| replace:: `.` .. |P106_status| replace:: :yellow:`COLLECTION B` :yellow:`CLIMATE` .. |P106_github| replace:: P106_BME680.ino .. _P106_github: https://github.com/letscontrolit/ESPEasy/blob/mega/src/_P106_BME680.ino .. |P106_usedby| replace:: `.` .. |P106_shortinfo| replace:: `.` -.. |P106_maintainer| replace:: TD-er +.. |P106_maintainer| replace:: `TD-er, tonhuisman` .. |P106_compileinfo| replace:: `.` .. |P106_usedlibraries| replace:: https://github.com/adafruit/Adafruit_BME680 diff --git a/docs/source/Plugin/_plugin_substitutions_p15x.repl b/docs/source/Plugin/_plugin_substitutions_p15x.repl index 0051f05be..7bde9ca0a 100644 --- a/docs/source/Plugin/_plugin_substitutions_p15x.repl +++ b/docs/source/Plugin/_plugin_substitutions_p15x.repl @@ -1,3 +1,16 @@ +.. |P150_name| replace:: :cyan:`TMP117 Temperature` +.. |P150_type| replace:: :cyan:`Environment` +.. |P150_typename| replace:: :cyan:`Environment - TMP117 Temperature` +.. |P150_porttype| replace:: `.` +.. |P150_status| replace:: :yellow:`COLLECTION F` :yellow:`CLIMATE` +.. |P150_github| replace:: P150_TMP117.ino +.. _P150_github: https://github.com/letscontrolit/ESPEasy/blob/mega/src/_P150_TMP117.ino +.. |P150_usedby| replace:: `.` +.. |P150_shortinfo| replace:: `TMP117 Precision temperature sensor` +.. |P150_maintainer| replace:: `tonhuisman` +.. |P150_compileinfo| replace:: `.` +.. |P150_usedlibraries| replace:: `.` + .. |P151_name| replace:: :cyan:`I2C Honeywell Pressure` .. |P151_type| replace:: :cyan:`Environment` .. |P151_typename| replace:: :cyan:`Environment - I2C Honeywell Pressure` diff --git a/lib/Adafruit_BME680/Adafruit_BME680.cpp b/lib/Adafruit_BME680/Adafruit_BME680.cpp index faa52336d..0f714dd55 100644 --- a/lib/Adafruit_BME680/Adafruit_BME680.cpp +++ b/lib/Adafruit_BME680/Adafruit_BME680.cpp @@ -32,28 +32,16 @@ //#define BME680_DEBUG -/** Wire object **/ -TwoWire *_wire = NULL; - -/** SPI object **/ -SPIClass *_spi = NULL; - -/** These SPI pins must be global in order to work with underlying library **/ -int8_t _BME680_SoftwareSPI_MOSI; ///< Global SPI MOSI pin -int8_t _BME680_SoftwareSPI_MISO; ///< Global SPI MISO pin -int8_t _BME680_SoftwareSPI_SCK; ///< Globak SPI Clock pin - /** Our hardware interface functions **/ -static int8_t i2c_write(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, - uint16_t len); -static int8_t i2c_read(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, - uint16_t len); -static int8_t spi_read(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, - uint16_t len); -static int8_t spi_write(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, - uint16_t len); -static uint8_t spi_transfer(uint8_t x); -static void delay_msec(uint32_t ms); +static int8_t i2c_read(uint8_t reg_addr, uint8_t *reg_data, uint32_t len, + void *interface); +static int8_t i2c_write(uint8_t reg_addr, const uint8_t *reg_data, uint32_t len, + void *interface); +static int8_t spi_read(uint8_t reg_addr, uint8_t *reg_data, uint32_t len, + void *interface); +static int8_t spi_write(uint8_t reg_addr, const uint8_t *reg_data, uint32_t len, + void *interface); +static void delay_usec(uint32_t us, void *intf_ptr); // PUBLIC FUNCTIONS @@ -63,13 +51,8 @@ static void delay_msec(uint32_t ms); * optional Wire object */ Adafruit_BME680::Adafruit_BME680(TwoWire *theWire) - : _cs(-1), _meas_start(0), _meas_period(0) { + : _meas_start(0), _meas_period(0) { _wire = theWire; - _BME680_SoftwareSPI_MOSI = -1; - _BME680_SoftwareSPI_MISO = -1; - _BME680_SoftwareSPI_SCK = -1; - _filterEnabled = _tempEnabled = _humEnabled = _presEnabled = _gasEnabled = - false; } /*! @@ -80,13 +63,9 @@ Adafruit_BME680::Adafruit_BME680(TwoWire *theWire) * optional SPI object */ Adafruit_BME680::Adafruit_BME680(int8_t cspin, SPIClass *theSPI) - : _cs(cspin), _meas_start(0), _meas_period(0) { - _spi = theSPI; - _BME680_SoftwareSPI_MOSI = -1; - _BME680_SoftwareSPI_MISO = -1; - _BME680_SoftwareSPI_SCK = -1; - _filterEnabled = _tempEnabled = _humEnabled = _presEnabled = _gasEnabled = - false; + : _meas_start(0), _meas_period(0) { + _spidev = new Adafruit_SPIDevice(cspin, 1000000, SPI_BITORDER_MSBFIRST, + SPI_MODE0, theSPI); } /*! @@ -102,12 +81,9 @@ Adafruit_BME680::Adafruit_BME680(int8_t cspin, SPIClass *theSPI) */ Adafruit_BME680::Adafruit_BME680(int8_t cspin, int8_t mosipin, int8_t misopin, int8_t sckpin) - : _cs(cspin), _meas_start(0), _meas_period(0) { - _BME680_SoftwareSPI_MOSI = mosipin; - _BME680_SoftwareSPI_MISO = misopin; - _BME680_SoftwareSPI_SCK = sckpin; - _filterEnabled = _tempEnabled = _humEnabled = _presEnabled = _gasEnabled = - false; + : _meas_start(0), _meas_period(0) { + _spidev = new Adafruit_SPIDevice(cspin, sckpin, misopin, mosipin, 1000000, + SPI_BITORDER_MSBFIRST, SPI_MODE0); } /*! @@ -122,45 +98,46 @@ Adafruit_BME680::Adafruit_BME680(int8_t cspin, int8_t mosipin, int8_t misopin, * @return True on sensor initialization success. False on failure. */ bool Adafruit_BME680::begin(uint8_t addr, bool initSettings) { - _i2caddr = addr; + int8_t rslt; - if (_cs == -1) { - // i2c - _wire->begin(); - - gas_sensor.dev_id = addr; - gas_sensor.intf = BME680_I2C_INTF; - gas_sensor.read = &i2c_read; - gas_sensor.write = &i2c_write; - } else { - digitalWrite(_cs, HIGH); - pinMode(_cs, OUTPUT); - - if (_BME680_SoftwareSPI_SCK == -1) { - // hardware SPI - _spi->begin(); - } else { - // software SPI - pinMode(_BME680_SoftwareSPI_SCK, OUTPUT); - pinMode(_BME680_SoftwareSPI_MOSI, OUTPUT); - pinMode(_BME680_SoftwareSPI_MISO, INPUT); + if (!_spidev) { // i2c + if (_i2cdev) { + delete _i2cdev; + } + _i2cdev = new Adafruit_I2CDevice(addr, _wire); + if (!_i2cdev->begin()) { + return false; } - gas_sensor.dev_id = _cs; - gas_sensor.intf = BME680_SPI_INTF; + gas_sensor.chip_id = addr; + gas_sensor.intf = BME68X_I2C_INTF; + gas_sensor.intf_ptr = (void *)_i2cdev; + gas_sensor.read = &i2c_read; + gas_sensor.write = &i2c_write; + + } else { + if (!_spidev->begin()) { + return false; + } + + gas_sensor.chip_id = 0; + gas_sensor.intf = BME68X_SPI_INTF; + gas_sensor.intf_ptr = (void *)_spidev; gas_sensor.read = &spi_read; gas_sensor.write = &spi_write; } - gas_sensor.delay_ms = delay_msec; + gas_sensor.amb_temp = 25; /* The ambient temperature in deg C is used for + defining the heater temperature */ + gas_sensor.delay_us = delay_usec; - int8_t rslt = bme680_init(&gas_sensor); + rslt = bme68x_init(&gas_sensor); #ifdef BME680_DEBUG - Serial.print("Result: "); + Serial.print(F("Init Result: ")); Serial.println(rslt); #endif - if (rslt != BME680_OK) + if (rslt != BME68X_OK) return false; #ifdef BME680_DEBUG @@ -225,16 +202,25 @@ bool Adafruit_BME680::begin(uint8_t addr, bool initSettings) { #endif if (initSettings) { - setTemperatureOversampling(BME680_OS_8X); - setHumidityOversampling(BME680_OS_2X); - setPressureOversampling(BME680_OS_4X); - setIIRFilterSize(BME680_FILTER_SIZE_3); + setIIRFilterSize(BME68X_FILTER_SIZE_3); + setODR(BME68X_ODR_NONE); + setHumidityOversampling(BME68X_OS_2X); + setPressureOversampling(BME68X_OS_4X); + setTemperatureOversampling(BME68X_OS_8X); setGasHeater(320, 150); // 320*C for 150 ms } else { setGasHeater(0, 0); } // don't do anything till we request a reading - gas_sensor.power_mode = BME680_FORCED_MODE; + rslt = bme68x_set_op_mode(BME68X_FORCED_MODE, &gas_sensor); + +#ifdef BME680_DEBUG + Serial.print(F("Opmode Result: ")); + Serial.println(rslt); +#endif + + if (rslt != BME68X_OK) + return false; return true; } @@ -304,66 +290,56 @@ float Adafruit_BME680::readAltitude(float seaLevel) { */ bool Adafruit_BME680::performReading(void) { return endReading(); } -unsigned long Adafruit_BME680::beginReading(void) { +/*! @brief Begin an asynchronous reading. + * @return When the reading would be ready as absolute time in millis(). + */ +uint32_t Adafruit_BME680::beginReading(void) { if (_meas_start != 0) { /* A measurement is already in progress */ return _meas_start + _meas_period; } - uint8_t set_required_settings = 0; - int8_t rslt; - - /* Select the power mode */ - /* Must be set before writing the sensor configuration */ - gas_sensor.power_mode = BME680_FORCED_MODE; - - /* Set the required sensor settings needed */ - if (_tempEnabled) - set_required_settings |= BME680_OST_SEL; - if (_humEnabled) - set_required_settings |= BME680_OSH_SEL; - if (_presEnabled) - set_required_settings |= BME680_OSP_SEL; - if (_filterEnabled) - set_required_settings |= BME680_FILTER_SEL; - if (_gasEnabled) - set_required_settings |= BME680_GAS_SENSOR_SEL; - - /* Set the desired sensor configuration */ + int8_t rslt = bme68x_set_op_mode(BME68X_FORCED_MODE, &gas_sensor); #ifdef BME680_DEBUG - Serial.println("Setting sensor settings"); + Serial.print(F("Opmode Result: ")); + Serial.println(rslt); #endif - rslt = bme680_set_sensor_settings(set_required_settings, &gas_sensor); - if (rslt != BME680_OK) - return 0; + if (rslt != BME68X_OK) + return false; - /* Set the power mode */ -#ifdef BME680_DEBUG - Serial.println("Setting power mode"); -#endif - rslt = bme680_set_sensor_mode(&gas_sensor); - if (rslt != BME680_OK) - return 0; + /* Calculate delay period in microseconds */ + uint32_t delayus_period = (uint32_t)bme68x_get_meas_dur( + BME68X_FORCED_MODE, &gas_conf, &gas_sensor) + + ((uint32_t)gas_heatr_conf.heatr_dur * 1000); + // Serial.print("measure: "); + // Serial.println(bme68x_get_meas_dur(BME68X_FORCED_MODE, &gas_conf, + // &gas_sensor)); Serial.print("heater: "); + // Serial.println((uint32_t)gas_heatr_conf.heatr_dur * 1000); - /* Get the total measurement duration so as to sleep or wait till the - * measurement is complete */ - uint16_t meas_period; - bme680_get_profile_dur(&meas_period, &gas_sensor); _meas_start = millis(); - _meas_period = meas_period; + _meas_period = delayus_period / 1000; + return _meas_start + _meas_period; } +/*! @brief End an asynchronous reading. + * If the asynchronous reading is still in progress, block until it + * ends. If no asynchronous reading has started, this is equivalent to + * performReading(). + * @return Whether success. + */ bool Adafruit_BME680::endReading(void) { - unsigned long meas_end = beginReading(); + uint32_t meas_end = beginReading(); + if (meas_end == 0) { return false; } int remaining_millis = remainingReadingMillis(); + if (remaining_millis > 0) { #ifdef BME680_DEBUG - Serial.print("Waiting (ms) "); + Serial.print(F("Waiting (ms) ")); Serial.println(remaining_millis); #endif delay(static_cast(remaining_millis) * @@ -373,54 +349,54 @@ bool Adafruit_BME680::endReading(void) { _meas_period = 0; #ifdef BME680_DEBUG - Serial.print("t_fine = "); + Serial.print(F("t_fine = ")); Serial.println(gas_sensor.calib.t_fine); #endif - struct bme680_field_data data; + struct bme68x_data data; + uint8_t n_fields; - // Serial.println("Getting sensor data"); - int8_t rslt = bme680_get_sensor_data(&data, &gas_sensor); - if (rslt != BME680_OK) +#ifdef BME680_DEBUG + Serial.println(F("Getting sensor data")); +#endif + + int8_t rslt = + bme68x_get_data(BME68X_FORCED_MODE, &data, &n_fields, &gas_sensor); +#ifdef BME680_DEBUG + Serial.print(F("GetData Result: ")); + Serial.println(rslt); +#endif + if (rslt != BME68X_OK) return false; - if (_tempEnabled) { - // Serial.print("Temp: "); Serial.println(data.temperature / 100.0, 2); - temperature = data.temperature / 100.0; - } else { - temperature = NAN; - } - - if (_humEnabled) { - // Serial.print("Hum: "); Serial.println(data.humidity / 1000.0, 2); - humidity = data.humidity / 1000.0; - } else { - humidity = NAN; - } - - if (_presEnabled) { - // Serial.print("Pres: "); Serial.println(data.pressure, 2); + if (n_fields) { + temperature = data.temperature; + humidity = data.humidity; pressure = data.pressure; - } else { - pressure = 0; - } - /* Avoid using measurements from an unstable heating setup */ - if (_gasEnabled) { - if (data.status & BME680_HEAT_STAB_MSK) { +#ifdef BME680_DEBUG + Serial.print(F("data.status 0x")); + Serial.println(data.status, HEX); +#endif + if (data.status & (BME68X_HEAT_STAB_MSK | BME68X_GASM_VALID_MSK)) { // Serial.print("Gas resistance: "); Serial.println(data.gas_resistance); gas_resistance = data.gas_resistance; } else { gas_resistance = 0; // Serial.println("Gas reading unstable!"); } - } else { - gas_resistance = 0; } return true; } +/*! @brief Get remaining time for an asynchronous reading. + * If the asynchronous reading is still in progress, how many millis + * until its completion. If the asynchronous reading is completed, 0. If no + * asynchronous reading has started, -1 or + * Adafruit_BME680::reading_not_started. Does not block. + * @return Remaining millis until endReading will not block if invoked. + */ int Adafruit_BME680::remainingReadingMillis(void) { if (_meas_start != 0) { /* A measurement is already in progress */ @@ -439,279 +415,195 @@ int Adafruit_BME680::remainingReadingMillis(void) { * @return True on success, False on failure */ bool Adafruit_BME680::setGasHeater(uint16_t heaterTemp, uint16_t heaterTime) { - gas_sensor.gas_sett.heatr_temp = heaterTemp; - gas_sensor.gas_sett.heatr_dur = heaterTime; if ((heaterTemp == 0) || (heaterTime == 0)) { - // disabled! - gas_sensor.gas_sett.heatr_ctrl = BME680_DISABLE_HEATER; - gas_sensor.gas_sett.run_gas = BME680_DISABLE_GAS_MEAS; - _gasEnabled = false; + gas_heatr_conf.enable = BME68X_DISABLE; } else { - gas_sensor.gas_sett.heatr_ctrl = BME680_ENABLE_HEATER; - gas_sensor.gas_sett.run_gas = BME680_ENABLE_GAS_MEAS; - _gasEnabled = true; + gas_heatr_conf.enable = BME68X_ENABLE; + gas_heatr_conf.heatr_temp = heaterTemp; + gas_heatr_conf.heatr_dur = heaterTime; } - return true; + + int8_t rslt = + bme68x_set_heatr_conf(BME68X_FORCED_MODE, &gas_heatr_conf, &gas_sensor); +#ifdef BME680_DEBUG + Serial.print(F("SetHeaterConf Result: ")); + Serial.println(rslt); +#endif + return rslt == 0; +} + +/*! + * @brief Setter for Output Data Rate + * @param odr + * Output data rate setting, can be BME68X_ODR_NONE, + * BME68X_ODR_0_59_MS, BME68X_ODR_10_MS, BME68X_ODR_20_MS, BME68X_ODR_62_5_MS, + * BME68X_ODR_125_MS, BME68X_ODR_250_MS, BME68X_ODR_500_MS, BME68X_ODR_1000_MS + * @return True on success, False on failure + */ + +bool Adafruit_BME680::setODR(uint8_t odr) { + if (odr > BME68X_ODR_NONE) + return false; + + gas_conf.odr = odr; + + int8_t rslt = bme68x_set_conf(&gas_conf, &gas_sensor); +#ifdef BME680_DEBUG + Serial.print(F("SetConf Result: ")); + Serial.println(rslt); +#endif + return rslt == 0; } /*! * @brief Setter for Temperature oversampling * @param oversample - * Oversampling setting, can be BME680_OS_NONE (turn off Temperature - * reading), BME680_OS_1X, BME680_OS_2X, BME680_OS_4X, BME680_OS_8X or - * BME680_OS_16X + * Oversampling setting, can be BME68X_OS_NONE (turn off Temperature + * reading), BME68X_OS_1X, BME68X_OS_2X, BME68X_OS_4X, BME68X_OS_8X or + * BME68X_OS_16X * @return True on success, False on failure */ bool Adafruit_BME680::setTemperatureOversampling(uint8_t oversample) { - if (oversample > BME680_OS_16X) + if (oversample > BME68X_OS_16X) return false; - gas_sensor.tph_sett.os_temp = oversample; + gas_conf.os_temp = oversample; - if (oversample == BME680_OS_NONE) - _tempEnabled = false; - else - _tempEnabled = true; - - return true; + int8_t rslt = bme68x_set_conf(&gas_conf, &gas_sensor); +#ifdef BME680_DEBUG + Serial.print(F("SetConf Result: ")); + Serial.println(rslt); +#endif + return rslt == 0; } /*! * @brief Setter for Humidity oversampling * @param oversample - * Oversampling setting, can be BME680_OS_NONE (turn off Humidity - * reading), BME680_OS_1X, BME680_OS_2X, BME680_OS_4X, BME680_OS_8X or - * BME680_OS_16X + * Oversampling setting, can be BME68X_OS_NONE (turn off Humidity + * reading), BME68X_OS_1X, BME68X_OS_2X, BME68X_OS_4X, BME68X_OS_8X or + * BME68X_OS_16X * @return True on success, False on failure */ bool Adafruit_BME680::setHumidityOversampling(uint8_t oversample) { - if (oversample > BME680_OS_16X) + if (oversample > BME68X_OS_16X) return false; - gas_sensor.tph_sett.os_hum = oversample; + gas_conf.os_hum = oversample; - if (oversample == BME680_OS_NONE) - _humEnabled = false; - else - _humEnabled = true; - - return true; + int8_t rslt = bme68x_set_conf(&gas_conf, &gas_sensor); +#ifdef BME680_DEBUG + Serial.print(F("SetConf Result: ")); + Serial.println(rslt); +#endif + return rslt == 0; } /*! * @brief Setter for Pressure oversampling * @param oversample - * Oversampling setting, can be BME680_OS_NONE (turn off Pressure - * reading), BME680_OS_1X, BME680_OS_2X, BME680_OS_4X, BME680_OS_8X or - * BME680_OS_16X + * Oversampling setting, can be BME68X_OS_NONE (turn off Pressure + * reading), BME68X_OS_1X, BME68X_OS_2X, BME68X_OS_4X, BME68X_OS_8X or + * BME68X_OS_16X * @return True on success, False on failure */ bool Adafruit_BME680::setPressureOversampling(uint8_t oversample) { - if (oversample > BME680_OS_16X) + if (oversample > BME68X_OS_16X) return false; - gas_sensor.tph_sett.os_pres = oversample; + gas_conf.os_pres = oversample; - if (oversample == BME680_OS_NONE) - _presEnabled = false; - else - _presEnabled = true; - - return true; + int8_t rslt = bme68x_set_conf(&gas_conf, &gas_sensor); +#ifdef BME680_DEBUG + Serial.print(F("SetConf Result: ")); + Serial.println(rslt); +#endif + return rslt == 0; } /*! * @brief Setter for IIR filter. * @param filtersize * Size of the filter (in samples). - * Can be BME680_FILTER_SIZE_0 (no filtering), BME680_FILTER_SIZE_1, - * BME680_FILTER_SIZE_3, BME680_FILTER_SIZE_7, BME680_FILTER_SIZE_15, - * BME680_FILTER_SIZE_31, BME680_FILTER_SIZE_63, BME680_FILTER_SIZE_127 + * Can be BME68X_FILTER_SIZE_0 (no filtering), BME68X_FILTER_SIZE_1, + * BME68X_FILTER_SIZE_3, BME68X_FILTER_SIZE_7, BME68X_FILTER_SIZE_15, + * BME68X_FILTER_SIZE_31, BME68X_FILTER_SIZE_63, BME68X_FILTER_SIZE_127 * @return True on success, False on failure */ bool Adafruit_BME680::setIIRFilterSize(uint8_t filtersize) { - if (filtersize > BME680_FILTER_SIZE_127) + if (filtersize > BME68X_FILTER_SIZE_127) return false; + gas_conf.filter = filtersize; - gas_sensor.tph_sett.filter = filtersize; - - if (filtersize == BME680_FILTER_SIZE_0) - _filterEnabled = false; - else - _filterEnabled = true; - - return true; + int8_t rslt = bme68x_set_conf(&gas_conf, &gas_sensor); +#ifdef BME680_DEBUG + Serial.print(F("SetConf Result: ")); + Serial.println(rslt); +#endif + return rslt == 0; } /*! * @brief Reads 8 bit values over I2C */ -int8_t i2c_read(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, - uint16_t len) { -#ifdef BME680_DEBUG - Serial.print("\tI2C $"); - Serial.print(reg_addr, HEX); - Serial.print(" => "); -#endif +int8_t i2c_read(uint8_t reg_addr, uint8_t *reg_data, uint32_t len, void *intf) { - _wire->beginTransmission((uint8_t)dev_id); - _wire->write((uint8_t)reg_addr); - _wire->endTransmission(); - if (len != _wire->requestFrom((uint8_t)dev_id, (uint8_t)len)) { -#ifdef BME680_DEBUG - Serial.print("Failed to read "); - Serial.print(len); - Serial.print(" bytes from "); - Serial.println(dev_id, HEX); -#endif - return 1; + Adafruit_I2CDevice *_dev = (Adafruit_I2CDevice *)intf; + + if (!_dev->write_then_read(®_addr, 1, reg_data, len, true)) { + return -1; } - while (len--) { - *reg_data = (uint8_t)_wire->read(); -#ifdef BME680_DEBUG - Serial.print("0x"); - Serial.print(*reg_data, HEX); - Serial.print(", "); -#endif - reg_data++; - } -#ifdef BME680_DEBUG - Serial.println(""); -#endif + return 0; } /*! * @brief Writes 8 bit values over I2C */ -int8_t i2c_write(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, - uint16_t len) { -#ifdef BME680_DEBUG - Serial.print("\tI2C $"); - Serial.print(reg_addr, HEX); - Serial.print(" <= "); -#endif - _wire->beginTransmission((uint8_t)dev_id); - _wire->write((uint8_t)reg_addr); - while (len--) { - _wire->write(*reg_data); -#ifdef BME680_DEBUG - Serial.print("0x"); - Serial.print(*reg_data, HEX); - Serial.print(", "); -#endif - reg_data++; +int8_t i2c_write(uint8_t reg_addr, const uint8_t *reg_data, uint32_t len, + void *intf) { + Adafruit_I2CDevice *_dev = (Adafruit_I2CDevice *)intf; + + if (!_dev->write((uint8_t *)reg_data, len, true, ®_addr, 1)) { + return -1; } - _wire->endTransmission(); -#ifdef BME680_DEBUG - Serial.println(""); -#endif return 0; } /*! * @brief Reads 8 bit values over SPI */ -static int8_t spi_read(uint8_t cspin, uint8_t reg_addr, uint8_t *reg_data, - uint16_t len) { -#ifdef BME680_DEBUG - Serial.print("\tSPI $"); - Serial.print(reg_addr, HEX); - Serial.print(" => "); -#endif +static int8_t spi_read(uint8_t reg_addr, uint8_t *reg_data, uint32_t len, + void *intf_ptr) { + Adafruit_SPIDevice *_dev = (Adafruit_SPIDevice *)intf_ptr; - // If hardware SPI we should use transactions! - if (_BME680_SoftwareSPI_SCK == -1) { - _spi->beginTransaction( - SPISettings(BME680_DEFAULT_SPIFREQ, MSBFIRST, SPI_MODE0)); + reg_addr |= 0x80; + + if (!_dev->write_then_read(®_addr, 1, reg_data, len, 0x0)) { + return -1; } - digitalWrite(cspin, LOW); - - spi_transfer(reg_addr | 0x80); - - while (len--) { - *reg_data = spi_transfer(0x00); -#ifdef BME680_DEBUG - Serial.print("0x"); - Serial.print(*reg_data, HEX); - Serial.print(", "); -#endif - reg_data++; - } - - digitalWrite(cspin, HIGH); - - if (_BME680_SoftwareSPI_SCK == -1) { - _spi->endTransaction(); - } - -#ifdef BME680_DEBUG - Serial.println(""); -#endif return 0; } /*! * @brief Writes 8 bit values over SPI */ -static int8_t spi_write(uint8_t cspin, uint8_t reg_addr, uint8_t *reg_data, - uint16_t len) { -#ifdef BME680_DEBUG - Serial.print("\tSPI $"); - Serial.print(reg_addr, HEX); - Serial.print(" <= "); -#endif +static int8_t spi_write(uint8_t reg_addr, const uint8_t *reg_data, uint32_t len, + void *intf_ptr) { + Adafruit_SPIDevice *_dev = (Adafruit_SPIDevice *)intf_ptr; - // If hardware SPI we should use transactions! - if (_BME680_SoftwareSPI_SCK == -1) { - _spi->beginTransaction( - SPISettings(BME680_DEFAULT_SPIFREQ, MSBFIRST, SPI_MODE0)); + if (!_dev->write((uint8_t *)reg_data, len, ®_addr, 1)) { + return -1; } - digitalWrite(cspin, LOW); - - spi_transfer(reg_addr); - while (len--) { - spi_transfer(*reg_data); -#ifdef BME680_DEBUG - Serial.print("0x"); - Serial.print(*reg_data, HEX); - Serial.print(", "); -#endif - reg_data++; - } - - digitalWrite(cspin, HIGH); - - if (_BME680_SoftwareSPI_SCK == -1) { - _spi->endTransaction(); - } - -#ifdef BME680_DEBUG - Serial.println(""); -#endif return 0; } -static uint8_t spi_transfer(uint8_t x) { - if (_BME680_SoftwareSPI_SCK == -1) - return _spi->transfer(x); - - // software spi - // Serial.println("Software SPI"); - uint8_t reply = 0; - for (int i = 7; i >= 0; i--) { - reply <<= 1; - digitalWrite(_BME680_SoftwareSPI_SCK, LOW); - digitalWrite(_BME680_SoftwareSPI_MOSI, x & (1 << i)); - digitalWrite(_BME680_SoftwareSPI_SCK, HIGH); - if (digitalRead(_BME680_SoftwareSPI_MISO)) - reply |= 1; - } - return reply; +static void delay_usec(uint32_t us, void *intf_ptr) { + (void)intf_ptr; // Unused parameter + delayMicroseconds(us); + yield(); } - -static void delay_msec(uint32_t ms) { delay(ms); } diff --git a/lib/Adafruit_BME680/Adafruit_BME680.h b/lib/Adafruit_BME680/Adafruit_BME680.h index 48e4c05d0..be4301097 100644 --- a/lib/Adafruit_BME680/Adafruit_BME680.h +++ b/lib/Adafruit_BME680/Adafruit_BME680.h @@ -26,13 +26,38 @@ #include "Arduino.h" -#include "bme680.h" +#include "bme68x.h" +#include +#include #include -#include #include -#define BME680_DEFAULT_ADDRESS (0x77) ///< The default I2C address -#define BME680_DEFAULT_SPIFREQ (1000000) ///< The default SPI Clock speed +#define BME68X_DEFAULT_ADDRESS (0x77) ///< The default I2C address +#define BME68X_DEFAULT_SPIFREQ (1000000) ///< The default SPI Clock speed + +#define BME680_OS_16X BME68X_OS_16X ///< Alias for BME680 existing examples +#define BME680_OS_8X BME68X_OS_8X ///< Alias for BME680 existing examples +#define BME680_OS_4X BME68X_OS_4X ///< Alias for BME680 existing examples +#define BME680_OS_2X BME68X_OS_2X ///< Alias for BME680 existing examples +#define BME680_OS_1X BME68X_OS_1X ///< Alias for BME680 existing examples +#define BME680_OS_NONE BME68X_OS_NONE ///< Alias for BME680 existing examples + +#define BME680_FILTER_SIZE_127 \ + BME68X_FILTER_SIZE_127 ///< Alias for BME680 existing examples +#define BME680_FILTER_SIZE_63 \ + BME68X_FILTER_SIZE_63 ///< Alias for BME680 existing examples +#define BME680_FILTER_SIZE_31 \ + BME68X_FILTER_SIZE_31 ///< Alias for BME680 existing examples +#define BME680_FILTER_SIZE_15 \ + BME68X_FILTER_SIZE_15 ///< Alias for BME680 existing examples +#define BME680_FILTER_SIZE_7 \ + BME68X_FILTER_SIZE_7 ///< Alias for BME680 existing examples +#define BME680_FILTER_SIZE_3 \ + BME68X_FILTER_SIZE_3 ///< Alias for BME680 existing examples +#define BME680_FILTER_SIZE_1 \ + BME68X_FILTER_SIZE_1 ///< Alias for BME680 existing examples +#define BME680_FILTER_SIZE_0 \ + BME68X_FILTER_OFF ///< Alias for BME680 existing examples /*! Adafruit_BME680 Class for both I2C and SPI usage. * Wraps the Bosch library for Arduino usage @@ -50,7 +75,7 @@ public: Adafruit_BME680(int8_t cspin, SPIClass *theSPI = &SPI); Adafruit_BME680(int8_t cspin, int8_t mosipin, int8_t misopin, int8_t sckpin); - bool begin(uint8_t addr = BME680_DEFAULT_ADDRESS, bool initSettings = true); + bool begin(uint8_t addr = BME68X_DEFAULT_ADDRESS, bool initSettings = true); float readTemperature(); float readPressure(); float readHumidity(); @@ -62,30 +87,15 @@ public: bool setHumidityOversampling(uint8_t os); bool setIIRFilterSize(uint8_t fs); bool setGasHeater(uint16_t heaterTemp, uint16_t heaterTime); + bool setODR(uint8_t odr); // Perform a reading in blocking mode. bool performReading(); - /*! @brief Begin an asynchronous reading. - * @return When the reading would be ready as absolute time in millis(). - */ - unsigned long beginReading(); + uint32_t beginReading(); - /*! @brief End an asynchronous reading. - * If the asynchronous reading is still in progress, block until it - * ends. If no asynchronous reading has started, this is equivalent to - * performReading(). - * @return Whether success. - */ bool endReading(); - /*! @brief Get remaining time for an asynchronous reading. - * If the asynchronous reading is still in progress, how many millis - * until its completion. If the asynchronous reading is completed, 0. If no - * asynchronous reading has started, -1 or - * Adafruit_BME680::reading_not_started. Does not block. - * @return Remaining millis until endReading will not block if invoked. - */ int remainingReadingMillis(); /** Temperature (Celsius) assigned after calling performReading() or @@ -102,16 +112,17 @@ public: uint32_t gas_resistance; private: - bool _filterEnabled, _tempEnabled, _humEnabled, _presEnabled, _gasEnabled; - uint8_t _i2caddr; + Adafruit_I2CDevice *_i2cdev = NULL; + Adafruit_SPIDevice *_spidev = NULL; + TwoWire *_wire = NULL; + int32_t _sensorID; - int8_t _cs; - unsigned long _meas_start; - uint16_t _meas_period; + uint32_t _meas_start = 0; + uint16_t _meas_period = 0; - uint8_t spixfer(uint8_t x); - - struct bme680_dev gas_sensor; + struct bme68x_dev gas_sensor; + struct bme68x_conf gas_conf; + struct bme68x_heatr_conf gas_heatr_conf; }; #endif diff --git a/lib/Adafruit_BME680/Doxyfile b/lib/Adafruit_BME680/Doxyfile index 917108f10..304bb4c2b 100644 --- a/lib/Adafruit_BME680/Doxyfile +++ b/lib/Adafruit_BME680/Doxyfile @@ -873,7 +873,7 @@ RECURSIVE = NO # Note that relative paths are relative to the directory from which doxygen is # run. -EXCLUDE = bme680.c bme680.h bme680_defs.h README.md +EXCLUDE = bme68x.c bme68x.h bme68x_defs.h README.md # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded diff --git a/lib/Adafruit_BME680/bme680.c b/lib/Adafruit_BME680/bme680.c deleted file mode 100644 index 5c3ddda34..000000000 --- a/lib/Adafruit_BME680/bme680.c +++ /dev/null @@ -1,1361 +0,0 @@ -/**\mainpage - * Copyright (C) 2017 - 2018 Bosch Sensortec GmbH - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * Neither the name of the copyright holder nor the names of the - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER - * OR CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - * OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE - * - * The information provided is believed to be accurate and reliable. - * The copyright holder assumes no responsibility - * for the consequences of use - * of such information nor for any infringement of patents or - * other rights of third parties which may result from its use. - * No license is granted by implication or otherwise under any patent or - * patent rights of the copyright holder. - * - * File bme680.c - * @date 19 Jun 2018 - * @version 3.5.9 - * @file bme680.c - */ - -#include "bme680.h" - -/*! - * @brief This internal API is used to read the calibrated data from the sensor. - * This function is used to retrieve the calibration - * data from the image registers of the sensor. - * - * @note Registers 89h to A1h for calibration data 1 to 24 - * from bit 0 to 7 - * @note Registers E1h to F0h for calibration data 25 to 40 - * from bit 0 to 7 - * @param[in] dev - * Structure instance of bme680_dev. - * @return Result of API execution status. - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -static int8_t get_calib_data(struct bme680_dev *dev); - -/*! - * @brief This internal API is used to set the gas configuration of the sensor. - * @param[in] dev - * Structure instance of bme680_dev. - * @return Result of API execution status. - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -static int8_t set_gas_config(struct bme680_dev *dev); - -/*! - * @brief This internal API is used to get the gas configuration of the sensor. - * @note heatr_temp and heatr_dur values are currently register data - * and not the actual values set - * @param[in] dev - * Structure instance of bme680_dev. - * @return Result of API execution status. - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -static int8_t get_gas_config(struct bme680_dev *dev); - -/*! - * @brief This internal API is used to calculate the Heat duration value. - * @param[in] dur - * Value of the duration to be shared. - * @return uint8_t threshold duration after calculation. - */ -static uint8_t calc_heater_dur(uint16_t dur); - -#ifndef BME680_FLOAT_POINT_COMPENSATION - -/*! - * @brief This internal API is used to calculate the temperature value. - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] temp_adc - * Contains the temperature ADC value - * @return uint32_t calculated temperature. - */ -static int16_t calc_temperature(uint32_t temp_adc, struct bme680_dev *dev); - -/*! - * @brief This internal API is used to calculate the pressure value. - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] pres_adc - * Contains the pressure ADC value . - * @return uint32_t calculated pressure. - */ -static uint32_t calc_pressure(uint32_t pres_adc, const struct bme680_dev *dev); - -/*! - * @brief This internal API is used to calculate the humidity value. - * - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] hum_adc - * Contains the humidity ADC value. - * @return uint32_t calculated humidity. - */ -static uint32_t calc_humidity(uint16_t hum_adc, const struct bme680_dev *dev); - -/*! - * @brief This internal API is used to calculate the Gas Resistance value. - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] gas_res_adc - * Contains the Gas Resistance ADC value. - * @param[in] gas_range - * Contains the range of gas values. - * @return uint32_t calculated gas resistance. - */ -static uint32_t calc_gas_resistance(uint16_t gas_res_adc, uint8_t gas_range, const struct bme680_dev *dev); - -/*! - * @brief This internal API is used to calculate the Heat Resistance value. - * @param[in] dev - * Structure instance of bme680_dev - * @param[in] temp - * Contains the target temperature value. - * @return uint8_t calculated heater resistance. - */ -static uint8_t calc_heater_res(uint16_t temp, const struct bme680_dev *dev); - -#else -/*! - * @brief This internal API is used to calculate the - * temperature value value in float format - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] temp_adc - * Contains the temperature ADC value . - * @return Calculated temperature in float - */ -static float calc_temperature(uint32_t temp_adc, struct bme680_dev *dev); - -/*! - * @brief This internal API is used to calculate the - * pressure value value in float format - * - * @param[in] dev :Structure instance of bme680_dev. - * @param[in] pres_adc :Contains the pressure ADC value . - * - * @return Calculated pressure in float. - */ -static float calc_pressure(uint32_t pres_adc, const struct bme680_dev *dev); - -/*! - * @brief This internal API is used to calculate the - * humidity value value in float format - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] hum_adc - * Contains the humidity ADC value. - * @return Calculated humidity in float. - */ -static float calc_humidity(uint16_t hum_adc, const struct bme680_dev *dev); - -/*! - * @brief This internal API is used to calculate the - * gas resistance value value in float format - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] gas_res_adc - * Contains the Gas Resistance ADC value. - * @param[in] gas_range - * Contains the range of gas values. - * @return Calculated gas resistance in float. - */ -static float calc_gas_resistance(uint16_t gas_res_adc, uint8_t gas_range, const struct bme680_dev *dev); - -/*! - * @brief This internal API is used to calculate the - * heater resistance value in float format - * @param[in] temp - * Contains the target temperature value. - * @param[in] dev - * Structure instance of bme680_dev. - * @return Calculated heater resistance in float. - */ -static float calc_heater_res(uint16_t temp, const struct bme680_dev *dev); - -#endif - -/*! - * @brief This internal API is used to calculate the field data of sensor. - * @param[out] data - * Structure instance to hold the data - * @param[in] dev - * Structure instance of bme680_dev. - * @return int8_t result of the field data from sensor. - */ -static int8_t read_field_data(struct bme680_field_data *data, struct bme680_dev *dev); - -/*! - * @brief This internal API is used to set the memory page based on register address. - * The value of memory page - * value | Description - * --------|-------------- - * 0 | BME680_PAGE0_SPI - * 1 | BME680_PAGE1_SPI - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] reg_addr - * Contains the register address array. - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -static int8_t set_mem_page(uint8_t reg_addr, struct bme680_dev *dev); - -/*! - * @brief This internal API is used to get the memory page based - * on register address. - * The value of memory page - * value | Description - * --------|-------------- - * 0 | BME680_PAGE0_SPI - * 1 | BME680_PAGE1_SPI - * @param[in] dev - * Structure instance of bme680_dev. - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -static int8_t get_mem_page(struct bme680_dev *dev); - -/*! - * @brief This internal API is used to validate the device pointer for - * null conditions. - * @param[in] dev - * Structure instance of bme680_dev. - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -static int8_t null_ptr_check(const struct bme680_dev *dev); - -/*! - * @brief This internal API is used to check the boundary - * conditions. - * @param[in] value - * pointer to the value. - * @param[in] min - * minimum value. - * @param[in] max - * maximum value. - * @param[in] dev - * Structure instance of bme680_dev. - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -static int8_t boundary_check(uint8_t *value, uint8_t min, uint8_t max, struct bme680_dev *dev); - -/** Global Function Definitions **/ -/*! - * @brief This API is the entry point. - * It reads the chip-id and calibration data from the sensor. - */ -int8_t bme680_init(struct bme680_dev *dev) -{ - int8_t rslt; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - /* Soft reset to restore it to default values*/ - rslt = bme680_soft_reset(dev); - if (rslt == BME680_OK) { - rslt = bme680_get_regs(BME680_CHIP_ID_ADDR, &dev->chip_id, 1, dev); - if (rslt == BME680_OK) { - if (dev->chip_id == BME680_CHIP_ID) { - /* Get the Calibration data */ - rslt = get_calib_data(dev); - } else { - rslt = BME680_E_DEV_NOT_FOUND; - } - } - } - } - - return rslt; -} - -/*! - * @brief This API reads the data from the given register address of the sensor. - */ -int8_t bme680_get_regs(uint8_t reg_addr, uint8_t *reg_data, uint16_t len, struct bme680_dev *dev) -{ - int8_t rslt; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - if (dev->intf == BME680_SPI_INTF) { - /* Set the memory page */ - rslt = set_mem_page(reg_addr, dev); - if (rslt == BME680_OK) - reg_addr = reg_addr | BME680_SPI_RD_MSK; - } - dev->com_rslt = dev->read(dev->dev_id, reg_addr, reg_data, len); - if (dev->com_rslt != 0) - rslt = BME680_E_COM_FAIL; - } - - return rslt; -} - -/*! - * @brief This API writes the given data to the register address - * of the sensor. - */ -int8_t bme680_set_regs(const uint8_t *reg_addr, const uint8_t *reg_data, uint8_t len, struct bme680_dev *dev) -{ - int8_t rslt; - /* Length of the temporary buffer is 2*(length of register)*/ - uint8_t tmp_buff[BME680_TMP_BUFFER_LENGTH] = { 0 }; - uint16_t index; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - if ((len > 0) && (len < BME680_TMP_BUFFER_LENGTH / 2)) { - /* Interleave the 2 arrays */ - for (index = 0; index < len; index++) { - if (dev->intf == BME680_SPI_INTF) { - /* Set the memory page */ - rslt = set_mem_page(reg_addr[index], dev); - tmp_buff[(2 * index)] = reg_addr[index] & BME680_SPI_WR_MSK; - } else { - tmp_buff[(2 * index)] = reg_addr[index]; - } - tmp_buff[(2 * index) + 1] = reg_data[index]; - } - /* Write the interleaved array */ - if (rslt == BME680_OK) { - dev->com_rslt = dev->write(dev->dev_id, tmp_buff[0], &tmp_buff[1], (2 * len) - 1); - if (dev->com_rslt != 0) - rslt = BME680_E_COM_FAIL; - } - } else { - rslt = BME680_E_INVALID_LENGTH; - } - } - - return rslt; -} - -/*! - * @brief This API performs the soft reset of the sensor. - */ -int8_t bme680_soft_reset(struct bme680_dev *dev) -{ - int8_t rslt; - uint8_t reg_addr = BME680_SOFT_RESET_ADDR; - /* 0xb6 is the soft reset command */ - uint8_t soft_rst_cmd = BME680_SOFT_RESET_CMD; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - if (dev->intf == BME680_SPI_INTF) - rslt = get_mem_page(dev); - - /* Reset the device */ - if (rslt == BME680_OK) { - rslt = bme680_set_regs(®_addr, &soft_rst_cmd, 1, dev); - /* Wait for 5ms */ - dev->delay_ms(BME680_RESET_PERIOD); - - if (rslt == BME680_OK) { - /* After reset get the memory page */ - if (dev->intf == BME680_SPI_INTF) - rslt = get_mem_page(dev); - } - } - } - - return rslt; -} - -/*! - * @brief This API is used to set the oversampling, filter and T,P,H, gas selection - * settings in the sensor. - */ -int8_t bme680_set_sensor_settings(uint16_t desired_settings, struct bme680_dev *dev) -{ - int8_t rslt; - uint8_t reg_addr; - uint8_t data = 0; - uint8_t count = 0; - uint8_t reg_array[BME680_REG_BUFFER_LENGTH] = { 0 }; - uint8_t data_array[BME680_REG_BUFFER_LENGTH] = { 0 }; - uint8_t intended_power_mode = dev->power_mode; /* Save intended power mode */ - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - if (desired_settings & BME680_GAS_MEAS_SEL) - rslt = set_gas_config(dev); - - dev->power_mode = BME680_SLEEP_MODE; - if (rslt == BME680_OK) - rslt = bme680_set_sensor_mode(dev); - - /* Selecting the filter */ - if (desired_settings & BME680_FILTER_SEL) { - rslt = boundary_check(&dev->tph_sett.filter, BME680_FILTER_SIZE_0, BME680_FILTER_SIZE_127, dev); - reg_addr = BME680_CONF_ODR_FILT_ADDR; - - if (rslt == BME680_OK) - rslt = bme680_get_regs(reg_addr, &data, 1, dev); - - if (desired_settings & BME680_FILTER_SEL) - data = BME680_SET_BITS(data, BME680_FILTER, dev->tph_sett.filter); - - reg_array[count] = reg_addr; /* Append configuration */ - data_array[count] = data; - count++; - } - - /* Selecting heater control for the sensor */ - if (desired_settings & BME680_HCNTRL_SEL) { - rslt = boundary_check(&dev->gas_sett.heatr_ctrl, BME680_ENABLE_HEATER, - BME680_DISABLE_HEATER, dev); - reg_addr = BME680_CONF_HEAT_CTRL_ADDR; - - if (rslt == BME680_OK) - rslt = bme680_get_regs(reg_addr, &data, 1, dev); - data = BME680_SET_BITS_POS_0(data, BME680_HCTRL, dev->gas_sett.heatr_ctrl); - - reg_array[count] = reg_addr; /* Append configuration */ - data_array[count] = data; - count++; - } - - /* Selecting heater T,P oversampling for the sensor */ - if (desired_settings & (BME680_OST_SEL | BME680_OSP_SEL)) { - rslt = boundary_check(&dev->tph_sett.os_temp, BME680_OS_NONE, BME680_OS_16X, dev); - reg_addr = BME680_CONF_T_P_MODE_ADDR; - - if (rslt == BME680_OK) - rslt = bme680_get_regs(reg_addr, &data, 1, dev); - - if (desired_settings & BME680_OST_SEL) - data = BME680_SET_BITS(data, BME680_OST, dev->tph_sett.os_temp); - - if (desired_settings & BME680_OSP_SEL) - data = BME680_SET_BITS(data, BME680_OSP, dev->tph_sett.os_pres); - - reg_array[count] = reg_addr; - data_array[count] = data; - count++; - } - - /* Selecting humidity oversampling for the sensor */ - if (desired_settings & BME680_OSH_SEL) { - rslt = boundary_check(&dev->tph_sett.os_hum, BME680_OS_NONE, BME680_OS_16X, dev); - reg_addr = BME680_CONF_OS_H_ADDR; - - if (rslt == BME680_OK) - rslt = bme680_get_regs(reg_addr, &data, 1, dev); - data = BME680_SET_BITS_POS_0(data, BME680_OSH, dev->tph_sett.os_hum); - - reg_array[count] = reg_addr; /* Append configuration */ - data_array[count] = data; - count++; - } - - /* Selecting the runGas and NB conversion settings for the sensor */ - if (desired_settings & (BME680_RUN_GAS_SEL | BME680_NBCONV_SEL)) { - rslt = boundary_check(&dev->gas_sett.run_gas, BME680_RUN_GAS_DISABLE, - BME680_RUN_GAS_ENABLE, dev); - if (rslt == BME680_OK) { - /* Validate boundary conditions */ - rslt = boundary_check(&dev->gas_sett.nb_conv, BME680_NBCONV_MIN, - BME680_NBCONV_MAX, dev); - } - - reg_addr = BME680_CONF_ODR_RUN_GAS_NBC_ADDR; - - if (rslt == BME680_OK) - rslt = bme680_get_regs(reg_addr, &data, 1, dev); - - if (desired_settings & BME680_RUN_GAS_SEL) - data = BME680_SET_BITS(data, BME680_RUN_GAS, dev->gas_sett.run_gas); - - if (desired_settings & BME680_NBCONV_SEL) - data = BME680_SET_BITS_POS_0(data, BME680_NBCONV, dev->gas_sett.nb_conv); - - reg_array[count] = reg_addr; /* Append configuration */ - data_array[count] = data; - count++; - } - - if (rslt == BME680_OK) - rslt = bme680_set_regs(reg_array, data_array, count, dev); - - /* Restore previous intended power mode */ - dev->power_mode = intended_power_mode; - } - - return rslt; -} - -/*! - * @brief This API is used to get the oversampling, filter and T,P,H, gas selection - * settings in the sensor. - */ -int8_t bme680_get_sensor_settings(uint16_t desired_settings, struct bme680_dev *dev) -{ - int8_t rslt; - /* starting address of the register array for burst read*/ - uint8_t reg_addr = BME680_CONF_HEAT_CTRL_ADDR; - uint8_t data_array[BME680_REG_BUFFER_LENGTH] = { 0 }; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - rslt = bme680_get_regs(reg_addr, data_array, BME680_REG_BUFFER_LENGTH, dev); - - if (rslt == BME680_OK) { - if (desired_settings & BME680_GAS_MEAS_SEL) - rslt = get_gas_config(dev); - - /* get the T,P,H ,Filter,ODR settings here */ - if (desired_settings & BME680_FILTER_SEL) - dev->tph_sett.filter = BME680_GET_BITS(data_array[BME680_REG_FILTER_INDEX], - BME680_FILTER); - - if (desired_settings & (BME680_OST_SEL | BME680_OSP_SEL)) { - dev->tph_sett.os_temp = BME680_GET_BITS(data_array[BME680_REG_TEMP_INDEX], BME680_OST); - dev->tph_sett.os_pres = BME680_GET_BITS(data_array[BME680_REG_PRES_INDEX], BME680_OSP); - } - - if (desired_settings & BME680_OSH_SEL) - dev->tph_sett.os_hum = BME680_GET_BITS_POS_0(data_array[BME680_REG_HUM_INDEX], - BME680_OSH); - - /* get the gas related settings */ - if (desired_settings & BME680_HCNTRL_SEL) - dev->gas_sett.heatr_ctrl = BME680_GET_BITS_POS_0(data_array[BME680_REG_HCTRL_INDEX], - BME680_HCTRL); - - if (desired_settings & (BME680_RUN_GAS_SEL | BME680_NBCONV_SEL)) { - dev->gas_sett.nb_conv = BME680_GET_BITS_POS_0(data_array[BME680_REG_NBCONV_INDEX], - BME680_NBCONV); - dev->gas_sett.run_gas = BME680_GET_BITS(data_array[BME680_REG_RUN_GAS_INDEX], - BME680_RUN_GAS); - } - } - } else { - rslt = BME680_E_NULL_PTR; - } - - return rslt; -} - -/*! - * @brief This API is used to set the power mode of the sensor. - */ -int8_t bme680_set_sensor_mode(struct bme680_dev *dev) -{ - int8_t rslt; - uint8_t tmp_pow_mode; - uint8_t pow_mode = 0; - uint8_t reg_addr = BME680_CONF_T_P_MODE_ADDR; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - /* Call repeatedly until in sleep */ - do { - rslt = bme680_get_regs(BME680_CONF_T_P_MODE_ADDR, &tmp_pow_mode, 1, dev); - if (rslt == BME680_OK) { - /* Put to sleep before changing mode */ - pow_mode = (tmp_pow_mode & BME680_MODE_MSK); - - if (pow_mode != BME680_SLEEP_MODE) { - tmp_pow_mode = tmp_pow_mode & (~BME680_MODE_MSK); /* Set to sleep */ - rslt = bme680_set_regs(®_addr, &tmp_pow_mode, 1, dev); - dev->delay_ms(BME680_POLL_PERIOD_MS); - } - } - } while (pow_mode != BME680_SLEEP_MODE); - - /* Already in sleep */ - if (dev->power_mode != BME680_SLEEP_MODE) { - tmp_pow_mode = (tmp_pow_mode & ~BME680_MODE_MSK) | (dev->power_mode & BME680_MODE_MSK); - if (rslt == BME680_OK) - rslt = bme680_set_regs(®_addr, &tmp_pow_mode, 1, dev); - } - } - - return rslt; -} - -/*! - * @brief This API is used to get the power mode of the sensor. - */ -int8_t bme680_get_sensor_mode(struct bme680_dev *dev) -{ - int8_t rslt; - uint8_t mode; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - rslt = bme680_get_regs(BME680_CONF_T_P_MODE_ADDR, &mode, 1, dev); - /* Masking the other register bit info*/ - dev->power_mode = mode & BME680_MODE_MSK; - } - - return rslt; -} - -/*! - * @brief This API is used to set the profile duration of the sensor. - */ -void bme680_set_profile_dur(uint16_t duration, struct bme680_dev *dev) -{ - uint32_t tph_dur; /* Calculate in us */ - uint32_t meas_cycles; - uint8_t os_to_meas_cycles[6] = {0, 1, 2, 4, 8, 16}; - - meas_cycles = os_to_meas_cycles[dev->tph_sett.os_temp]; - meas_cycles += os_to_meas_cycles[dev->tph_sett.os_pres]; - meas_cycles += os_to_meas_cycles[dev->tph_sett.os_hum]; - - /* TPH measurement duration */ - tph_dur = meas_cycles * UINT32_C(1963); - tph_dur += UINT32_C(477 * 4); /* TPH switching duration */ - tph_dur += UINT32_C(477 * 5); /* Gas measurement duration */ - tph_dur += UINT32_C(500); /* Get it to the closest whole number.*/ - tph_dur /= UINT32_C(1000); /* Convert to ms */ - - tph_dur += UINT32_C(1); /* Wake up duration of 1ms */ - /* The remaining time should be used for heating */ - dev->gas_sett.heatr_dur = duration - (uint16_t) tph_dur; -} - -/*! - * @brief This API is used to get the profile duration of the sensor. - */ -void bme680_get_profile_dur(uint16_t *duration, const struct bme680_dev *dev) -{ - uint32_t tph_dur; /* Calculate in us */ - uint32_t meas_cycles; - uint8_t os_to_meas_cycles[6] = {0, 1, 2, 4, 8, 16}; - - meas_cycles = os_to_meas_cycles[dev->tph_sett.os_temp]; - meas_cycles += os_to_meas_cycles[dev->tph_sett.os_pres]; - meas_cycles += os_to_meas_cycles[dev->tph_sett.os_hum]; - - /* TPH measurement duration */ - tph_dur = meas_cycles * UINT32_C(1963); - tph_dur += UINT32_C(477 * 4); /* TPH switching duration */ - tph_dur += UINT32_C(477 * 5); /* Gas measurement duration */ - tph_dur += UINT32_C(500); /* Get it to the closest whole number.*/ - tph_dur /= UINT32_C(1000); /* Convert to ms */ - - tph_dur += UINT32_C(1); /* Wake up duration of 1ms */ - - *duration = (uint16_t) tph_dur; - - /* Get the gas duration only when the run gas is enabled */ - if (dev->gas_sett.run_gas) { - /* The remaining time should be used for heating */ - *duration += dev->gas_sett.heatr_dur; - } -} - -/*! - * @brief This API reads the pressure, temperature and humidity and gas data - * from the sensor, compensates the data and store it in the bme680_data - * structure instance passed by the user. - */ -int8_t bme680_get_sensor_data(struct bme680_field_data *data, struct bme680_dev *dev) -{ - int8_t rslt; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - /* Reading the sensor data in forced mode only */ - rslt = read_field_data(data, dev); - if (rslt == BME680_OK) { - if (data->status & BME680_NEW_DATA_MSK) - dev->new_fields = 1; - else - dev->new_fields = 0; - } - } - - return rslt; -} - -/*! - * @brief This internal API is used to read the calibrated data from the sensor. - */ -static int8_t get_calib_data(struct bme680_dev *dev) -{ - int8_t rslt; - uint8_t coeff_array[BME680_COEFF_SIZE] = { 0 }; - uint8_t temp_var = 0; /* Temporary variable */ - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - rslt = bme680_get_regs(BME680_COEFF_ADDR1, coeff_array, BME680_COEFF_ADDR1_LEN, dev); - /* Append the second half in the same array */ - if (rslt == BME680_OK) - rslt = bme680_get_regs(BME680_COEFF_ADDR2, &coeff_array[BME680_COEFF_ADDR1_LEN] - , BME680_COEFF_ADDR2_LEN, dev); - - /* Temperature related coefficients */ - dev->calib.par_t1 = (uint16_t) (BME680_CONCAT_BYTES(coeff_array[BME680_T1_MSB_REG], - coeff_array[BME680_T1_LSB_REG])); - dev->calib.par_t2 = (int16_t) (BME680_CONCAT_BYTES(coeff_array[BME680_T2_MSB_REG], - coeff_array[BME680_T2_LSB_REG])); - dev->calib.par_t3 = (int8_t) (coeff_array[BME680_T3_REG]); - - /* Pressure related coefficients */ - dev->calib.par_p1 = (uint16_t) (BME680_CONCAT_BYTES(coeff_array[BME680_P1_MSB_REG], - coeff_array[BME680_P1_LSB_REG])); - dev->calib.par_p2 = (int16_t) (BME680_CONCAT_BYTES(coeff_array[BME680_P2_MSB_REG], - coeff_array[BME680_P2_LSB_REG])); - dev->calib.par_p3 = (int8_t) coeff_array[BME680_P3_REG]; - dev->calib.par_p4 = (int16_t) (BME680_CONCAT_BYTES(coeff_array[BME680_P4_MSB_REG], - coeff_array[BME680_P4_LSB_REG])); - dev->calib.par_p5 = (int16_t) (BME680_CONCAT_BYTES(coeff_array[BME680_P5_MSB_REG], - coeff_array[BME680_P5_LSB_REG])); - dev->calib.par_p6 = (int8_t) (coeff_array[BME680_P6_REG]); - dev->calib.par_p7 = (int8_t) (coeff_array[BME680_P7_REG]); - dev->calib.par_p8 = (int16_t) (BME680_CONCAT_BYTES(coeff_array[BME680_P8_MSB_REG], - coeff_array[BME680_P8_LSB_REG])); - dev->calib.par_p9 = (int16_t) (BME680_CONCAT_BYTES(coeff_array[BME680_P9_MSB_REG], - coeff_array[BME680_P9_LSB_REG])); - dev->calib.par_p10 = (uint8_t) (coeff_array[BME680_P10_REG]); - - /* Humidity related coefficients */ - dev->calib.par_h1 = (uint16_t) (((uint16_t) coeff_array[BME680_H1_MSB_REG] << BME680_HUM_REG_SHIFT_VAL) - | (coeff_array[BME680_H1_LSB_REG] & BME680_BIT_H1_DATA_MSK)); - dev->calib.par_h2 = (uint16_t) (((uint16_t) coeff_array[BME680_H2_MSB_REG] << BME680_HUM_REG_SHIFT_VAL) - | ((coeff_array[BME680_H2_LSB_REG]) >> BME680_HUM_REG_SHIFT_VAL)); - dev->calib.par_h3 = (int8_t) coeff_array[BME680_H3_REG]; - dev->calib.par_h4 = (int8_t) coeff_array[BME680_H4_REG]; - dev->calib.par_h5 = (int8_t) coeff_array[BME680_H5_REG]; - dev->calib.par_h6 = (uint8_t) coeff_array[BME680_H6_REG]; - dev->calib.par_h7 = (int8_t) coeff_array[BME680_H7_REG]; - - /* Gas heater related coefficients */ - dev->calib.par_gh1 = (int8_t) coeff_array[BME680_GH1_REG]; - dev->calib.par_gh2 = (int16_t) (BME680_CONCAT_BYTES(coeff_array[BME680_GH2_MSB_REG], - coeff_array[BME680_GH2_LSB_REG])); - dev->calib.par_gh3 = (int8_t) coeff_array[BME680_GH3_REG]; - - /* Other coefficients */ - if (rslt == BME680_OK) { - rslt = bme680_get_regs(BME680_ADDR_RES_HEAT_RANGE_ADDR, &temp_var, 1, dev); - - dev->calib.res_heat_range = ((temp_var & BME680_RHRANGE_MSK) / 16); - if (rslt == BME680_OK) { - rslt = bme680_get_regs(BME680_ADDR_RES_HEAT_VAL_ADDR, &temp_var, 1, dev); - - dev->calib.res_heat_val = (int8_t) temp_var; - if (rslt == BME680_OK) - rslt = bme680_get_regs(BME680_ADDR_RANGE_SW_ERR_ADDR, &temp_var, 1, dev); - } - } - dev->calib.range_sw_err = ((int8_t) temp_var & (int8_t) BME680_RSERROR_MSK) / 16; - } - - return rslt; -} - -/*! - * @brief This internal API is used to set the gas configuration of the sensor. - */ -static int8_t set_gas_config(struct bme680_dev *dev) -{ - int8_t rslt; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - - uint8_t reg_addr[2] = {0}; - uint8_t reg_data[2] = {0}; - - if (dev->power_mode == BME680_FORCED_MODE) { - reg_addr[0] = BME680_RES_HEAT0_ADDR; - reg_data[0] = calc_heater_res(dev->gas_sett.heatr_temp, dev); - reg_addr[1] = BME680_GAS_WAIT0_ADDR; - reg_data[1] = calc_heater_dur(dev->gas_sett.heatr_dur); - dev->gas_sett.nb_conv = 0; - } else { - rslt = BME680_W_DEFINE_PWR_MODE; - } - if (rslt == BME680_OK) - rslt = bme680_set_regs(reg_addr, reg_data, 2, dev); - } - - return rslt; -} - -/*! - * @brief This internal API is used to get the gas configuration of the sensor. - * @note heatr_temp and heatr_dur values are currently register data - * and not the actual values set - */ -static int8_t get_gas_config(struct bme680_dev *dev) -{ - int8_t rslt; - /* starting address of the register array for burst read*/ - uint8_t reg_addr1 = BME680_ADDR_SENS_CONF_START; - uint8_t reg_addr2 = BME680_ADDR_GAS_CONF_START; - uint8_t reg_data = 0; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - if (BME680_SPI_INTF == dev->intf) { - /* Memory page switch the SPI address*/ - rslt = set_mem_page(reg_addr1, dev); - } - - if (rslt == BME680_OK) { - rslt = bme680_get_regs(reg_addr1, ®_data, 1, dev); - if (rslt == BME680_OK) { - dev->gas_sett.heatr_temp = reg_data; - rslt = bme680_get_regs(reg_addr2, ®_data, 1, dev); - if (rslt == BME680_OK) { - /* Heating duration register value */ - dev->gas_sett.heatr_dur = reg_data; - } - } - } - } - - return rslt; -} - -#ifndef BME680_FLOAT_POINT_COMPENSATION - -/*! - * @brief This internal API is used to calculate the temperature value. - */ -static int16_t calc_temperature(uint32_t temp_adc, struct bme680_dev *dev) -{ - int64_t var1; - int64_t var2; - int64_t var3; - int16_t calc_temp; - - var1 = ((int32_t) temp_adc >> 3) - ((int32_t) dev->calib.par_t1 << 1); - var2 = (var1 * (int32_t) dev->calib.par_t2) >> 11; - var3 = ((var1 >> 1) * (var1 >> 1)) >> 12; - var3 = ((var3) * ((int32_t) dev->calib.par_t3 << 4)) >> 14; - dev->calib.t_fine = (int32_t) (var2 + var3); - calc_temp = (int16_t) (((dev->calib.t_fine * 5) + 128) >> 8); - - return calc_temp; -} - -/*! - * @brief This internal API is used to calculate the pressure value. - */ -static uint32_t calc_pressure(uint32_t pres_adc, const struct bme680_dev *dev) -{ - int32_t var1; - int32_t var2; - int32_t var3; - int32_t pressure_comp; - - var1 = (((int32_t)dev->calib.t_fine) >> 1) - 64000; - var2 = ((((var1 >> 2) * (var1 >> 2)) >> 11) * - (int32_t)dev->calib.par_p6) >> 2; - var2 = var2 + ((var1 * (int32_t)dev->calib.par_p5) << 1); - var2 = (var2 >> 2) + ((int32_t)dev->calib.par_p4 << 16); - var1 = (((((var1 >> 2) * (var1 >> 2)) >> 13) * - ((int32_t)dev->calib.par_p3 << 5)) >> 3) + - (((int32_t)dev->calib.par_p2 * var1) >> 1); - var1 = var1 >> 18; - var1 = ((32768 + var1) * (int32_t)dev->calib.par_p1) >> 15; - pressure_comp = 1048576 - pres_adc; - pressure_comp = (int32_t)((pressure_comp - (var2 >> 12)) * ((uint32_t)3125)); - if (pressure_comp >= BME680_MAX_OVERFLOW_VAL) - pressure_comp = ((pressure_comp / var1) << 1); - else - pressure_comp = ((pressure_comp << 1) / var1); - var1 = ((int32_t)dev->calib.par_p9 * (int32_t)(((pressure_comp >> 3) * - (pressure_comp >> 3)) >> 13)) >> 12; - var2 = ((int32_t)(pressure_comp >> 2) * - (int32_t)dev->calib.par_p8) >> 13; - var3 = ((int32_t)(pressure_comp >> 8) * (int32_t)(pressure_comp >> 8) * - (int32_t)(pressure_comp >> 8) * - (int32_t)dev->calib.par_p10) >> 17; - - pressure_comp = (int32_t)(pressure_comp) + ((var1 + var2 + var3 + - ((int32_t)dev->calib.par_p7 << 7)) >> 4); - - return (uint32_t)pressure_comp; - -} - -/*! - * @brief This internal API is used to calculate the humidity value. - */ -static uint32_t calc_humidity(uint16_t hum_adc, const struct bme680_dev *dev) -{ - int32_t var1; - int32_t var2; - int32_t var3; - int32_t var4; - int32_t var5; - int32_t var6; - int32_t temp_scaled; - int32_t calc_hum; - - temp_scaled = (((int32_t) dev->calib.t_fine * 5) + 128) >> 8; - var1 = (int32_t) (hum_adc - ((int32_t) ((int32_t) dev->calib.par_h1 * 16))) - - (((temp_scaled * (int32_t) dev->calib.par_h3) / ((int32_t) 100)) >> 1); - var2 = ((int32_t) dev->calib.par_h2 - * (((temp_scaled * (int32_t) dev->calib.par_h4) / ((int32_t) 100)) - + (((temp_scaled * ((temp_scaled * (int32_t) dev->calib.par_h5) / ((int32_t) 100))) >> 6) - / ((int32_t) 100)) + (int32_t) (1 << 14))) >> 10; - var3 = var1 * var2; - var4 = (int32_t) dev->calib.par_h6 << 7; - var4 = ((var4) + ((temp_scaled * (int32_t) dev->calib.par_h7) / ((int32_t) 100))) >> 4; - var5 = ((var3 >> 14) * (var3 >> 14)) >> 10; - var6 = (var4 * var5) >> 1; - calc_hum = (((var3 + var6) >> 10) * ((int32_t) 1000)) >> 12; - - if (calc_hum > 100000) /* Cap at 100%rH */ - calc_hum = 100000; - else if (calc_hum < 0) - calc_hum = 0; - - return (uint32_t) calc_hum; -} - -/*! - * @brief This internal API is used to calculate the Gas Resistance value. - */ -static uint32_t calc_gas_resistance(uint16_t gas_res_adc, uint8_t gas_range, const struct bme680_dev *dev) -{ - int64_t var1; - uint64_t var2; - int64_t var3; - uint32_t calc_gas_res; - /**Look up table 1 for the possible gas range values */ - uint32_t lookupTable1[16] = { UINT32_C(2147483647), UINT32_C(2147483647), UINT32_C(2147483647), UINT32_C(2147483647), - UINT32_C(2147483647), UINT32_C(2126008810), UINT32_C(2147483647), UINT32_C(2130303777), - UINT32_C(2147483647), UINT32_C(2147483647), UINT32_C(2143188679), UINT32_C(2136746228), - UINT32_C(2147483647), UINT32_C(2126008810), UINT32_C(2147483647), UINT32_C(2147483647) }; - /**Look up table 2 for the possible gas range values */ - uint32_t lookupTable2[16] = { UINT32_C(4096000000), UINT32_C(2048000000), UINT32_C(1024000000), UINT32_C(512000000), - UINT32_C(255744255), UINT32_C(127110228), UINT32_C(64000000), UINT32_C(32258064), UINT32_C(16016016), - UINT32_C(8000000), UINT32_C(4000000), UINT32_C(2000000), UINT32_C(1000000), UINT32_C(500000), - UINT32_C(250000), UINT32_C(125000) }; - - var1 = (int64_t) ((1340 + (5 * (int64_t) dev->calib.range_sw_err)) * - ((int64_t) lookupTable1[gas_range])) >> 16; - var2 = (((int64_t) ((int64_t) gas_res_adc << 15) - (int64_t) (16777216)) + var1); - var3 = (((int64_t) lookupTable2[gas_range] * (int64_t) var1) >> 9); - calc_gas_res = (uint32_t) ((var3 + ((int64_t) var2 >> 1)) / (int64_t) var2); - - return calc_gas_res; -} - -/*! - * @brief This internal API is used to calculate the Heat Resistance value. - */ -static uint8_t calc_heater_res(uint16_t temp, const struct bme680_dev *dev) -{ - uint8_t heatr_res; - int32_t var1; - int32_t var2; - int32_t var3; - int32_t var4; - int32_t var5; - int32_t heatr_res_x100; - - if (temp > 400) /* Cap temperature */ - temp = 400; - - var1 = (((int32_t) dev->amb_temp * dev->calib.par_gh3) / 1000) * 256; - var2 = (dev->calib.par_gh1 + 784) * (((((dev->calib.par_gh2 + 154009) * temp * 5) / 100) + 3276800) / 10); - var3 = var1 + (var2 / 2); - var4 = (var3 / (dev->calib.res_heat_range + 4)); - var5 = (131 * dev->calib.res_heat_val) + 65536; - heatr_res_x100 = (int32_t) (((var4 / var5) - 250) * 34); - heatr_res = (uint8_t) ((heatr_res_x100 + 50) / 100); - - return heatr_res; -} - -#else - - -/*! - * @brief This internal API is used to calculate the - * temperature value in float format - */ -static float calc_temperature(uint32_t temp_adc, struct bme680_dev *dev) -{ - float var1 = 0; - float var2 = 0; - float calc_temp = 0; - - /* calculate var1 data */ - var1 = ((((float)temp_adc / 16384.0f) - ((float)dev->calib.par_t1 / 1024.0f)) - * ((float)dev->calib.par_t2)); - - /* calculate var2 data */ - var2 = (((((float)temp_adc / 131072.0f) - ((float)dev->calib.par_t1 / 8192.0f)) * - (((float)temp_adc / 131072.0f) - ((float)dev->calib.par_t1 / 8192.0f))) * - ((float)dev->calib.par_t3 * 16.0f)); - - /* t_fine value*/ - dev->calib.t_fine = (var1 + var2); - - /* compensated temperature data*/ - calc_temp = ((dev->calib.t_fine) / 5120.0f); - - return calc_temp; -} - -/*! - * @brief This internal API is used to calculate the - * pressure value in float format - */ -static float calc_pressure(uint32_t pres_adc, const struct bme680_dev *dev) -{ - float var1 = 0; - float var2 = 0; - float var3 = 0; - float calc_pres = 0; - - var1 = (((float)dev->calib.t_fine / 2.0f) - 64000.0f); - var2 = var1 * var1 * (((float)dev->calib.par_p6) / (131072.0f)); - var2 = var2 + (var1 * ((float)dev->calib.par_p5) * 2.0f); - var2 = (var2 / 4.0f) + (((float)dev->calib.par_p4) * 65536.0f); - var1 = (((((float)dev->calib.par_p3 * var1 * var1) / 16384.0f) - + ((float)dev->calib.par_p2 * var1)) / 524288.0f); - var1 = ((1.0f + (var1 / 32768.0f)) * ((float)dev->calib.par_p1)); - calc_pres = (1048576.0f - ((float)pres_adc)); - - /* Avoid exception caused by division by zero */ - if ((int)var1 != 0) { - calc_pres = (((calc_pres - (var2 / 4096.0f)) * 6250.0f) / var1); - var1 = (((float)dev->calib.par_p9) * calc_pres * calc_pres) / 2147483648.0f; - var2 = calc_pres * (((float)dev->calib.par_p8) / 32768.0f); - var3 = ((calc_pres / 256.0f) * (calc_pres / 256.0f) * (calc_pres / 256.0f) - * (dev->calib.par_p10 / 131072.0f)); - calc_pres = (calc_pres + (var1 + var2 + var3 + ((float)dev->calib.par_p7 * 128.0f)) / 16.0f); - } else { - calc_pres = 0; - } - - return calc_pres; -} - -/*! - * @brief This internal API is used to calculate the - * humidity value in float format - */ -static float calc_humidity(uint16_t hum_adc, const struct bme680_dev *dev) -{ - float calc_hum = 0; - float var1 = 0; - float var2 = 0; - float var3 = 0; - float var4 = 0; - float temp_comp; - - /* compensated temperature data*/ - temp_comp = ((dev->calib.t_fine) / 5120.0f); - - var1 = (float)((float)hum_adc) - (((float)dev->calib.par_h1 * 16.0f) + (((float)dev->calib.par_h3 / 2.0f) - * temp_comp)); - - var2 = var1 * ((float)(((float) dev->calib.par_h2 / 262144.0f) * (1.0f + (((float)dev->calib.par_h4 / 16384.0f) - * temp_comp) + (((float)dev->calib.par_h5 / 1048576.0f) * temp_comp * temp_comp)))); - - var3 = (float) dev->calib.par_h6 / 16384.0f; - - var4 = (float) dev->calib.par_h7 / 2097152.0f; - - calc_hum = var2 + ((var3 + (var4 * temp_comp)) * var2 * var2); - - if (calc_hum > 100.0f) - calc_hum = 100.0f; - else if (calc_hum < 0.0f) - calc_hum = 0.0f; - - return calc_hum; -} - -/*! - * @brief This internal API is used to calculate the - * gas resistance value in float format - */ -static float calc_gas_resistance(uint16_t gas_res_adc, uint8_t gas_range, const struct bme680_dev *dev) -{ - float calc_gas_res; - float var1 = 0; - float var2 = 0; - float var3 = 0; - - const float lookup_k1_range[16] = { - 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, -0.8, - 0.0, 0.0, -0.2, -0.5, 0.0, -1.0, 0.0, 0.0}; - const float lookup_k2_range[16] = { - 0.0, 0.0, 0.0, 0.0, 0.1, 0.7, 0.0, -0.8, - -0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; - - var1 = (1340.0f + (5.0f * dev->calib.range_sw_err)); - var2 = (var1) * (1.0f + lookup_k1_range[gas_range]/100.0f); - var3 = 1.0f + (lookup_k2_range[gas_range]/100.0f); - - calc_gas_res = 1.0f / (float)(var3 * (0.000000125f) * (float)(1 << gas_range) * (((((float)gas_res_adc) - - 512.0f)/var2) + 1.0f)); - - return calc_gas_res; -} - -/*! - * @brief This internal API is used to calculate the - * heater resistance value in float format - */ -static float calc_heater_res(uint16_t temp, const struct bme680_dev *dev) -{ - float var1 = 0; - float var2 = 0; - float var3 = 0; - float var4 = 0; - float var5 = 0; - float res_heat = 0; - - if (temp > 400) /* Cap temperature */ - temp = 400; - - var1 = (((float)dev->calib.par_gh1 / (16.0f)) + 49.0f); - var2 = ((((float)dev->calib.par_gh2 / (32768.0f)) * (0.0005f)) + 0.00235f); - var3 = ((float)dev->calib.par_gh3 / (1024.0f)); - var4 = (var1 * (1.0f + (var2 * (float)temp))); - var5 = (var4 + (var3 * (float)dev->amb_temp)); - res_heat = (uint8_t)(3.4f * ((var5 * (4 / (4 + (float)dev->calib.res_heat_range)) * - (1/(1 + ((float) dev->calib.res_heat_val * 0.002f)))) - 25)); - - return res_heat; -} - -#endif - -/*! - * @brief This internal API is used to calculate the Heat duration value. - */ -static uint8_t calc_heater_dur(uint16_t dur) -{ - uint8_t factor = 0; - uint8_t durval; - - if (dur >= 0xfc0) { - durval = 0xff; /* Max duration*/ - } else { - while (dur > 0x3F) { - dur = dur / 4; - factor += 1; - } - durval = (uint8_t) (dur + (factor * 64)); - } - - return durval; -} - -/*! - * @brief This internal API is used to calculate the field data of sensor. - */ -static int8_t read_field_data(struct bme680_field_data *data, struct bme680_dev *dev) -{ - int8_t rslt; - uint8_t buff[BME680_FIELD_LENGTH] = { 0 }; - uint8_t gas_range; - uint32_t adc_temp; - uint32_t adc_pres; - uint16_t adc_hum; - uint16_t adc_gas_res; - uint8_t tries = 10; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - do { - if (rslt == BME680_OK) { - rslt = bme680_get_regs(((uint8_t) (BME680_FIELD0_ADDR)), buff, (uint16_t) BME680_FIELD_LENGTH, - dev); - - data->status = buff[0] & BME680_NEW_DATA_MSK; - data->gas_index = buff[0] & BME680_GAS_INDEX_MSK; - data->meas_index = buff[1]; - - /* read the raw data from the sensor */ - adc_pres = (uint32_t) (((uint32_t) buff[2] * 4096) | ((uint32_t) buff[3] * 16) - | ((uint32_t) buff[4] / 16)); - adc_temp = (uint32_t) (((uint32_t) buff[5] * 4096) | ((uint32_t) buff[6] * 16) - | ((uint32_t) buff[7] / 16)); - adc_hum = (uint16_t) (((uint32_t) buff[8] * 256) | (uint32_t) buff[9]); - adc_gas_res = (uint16_t) ((uint32_t) buff[13] * 4 | (((uint32_t) buff[14]) / 64)); - gas_range = buff[14] & BME680_GAS_RANGE_MSK; - - data->status |= buff[14] & BME680_GASM_VALID_MSK; - data->status |= buff[14] & BME680_HEAT_STAB_MSK; - - if (data->status & BME680_NEW_DATA_MSK) { - data->temperature = calc_temperature(adc_temp, dev); - data->pressure = calc_pressure(adc_pres, dev); - data->humidity = calc_humidity(adc_hum, dev); - data->gas_resistance = calc_gas_resistance(adc_gas_res, gas_range, dev); - break; - } - /* Delay to poll the data */ - dev->delay_ms(BME680_POLL_PERIOD_MS); - } - tries--; - } while (tries); - - if (!tries) - rslt = BME680_W_NO_NEW_DATA; - - return rslt; -} - -/*! - * @brief This internal API is used to set the memory page based on register address. - */ -static int8_t set_mem_page(uint8_t reg_addr, struct bme680_dev *dev) -{ - int8_t rslt; - uint8_t reg; - uint8_t mem_page; - - /* Check for null pointers in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - if (reg_addr > 0x7f) - mem_page = BME680_MEM_PAGE1; - else - mem_page = BME680_MEM_PAGE0; - - if (mem_page != dev->mem_page) { - dev->mem_page = mem_page; - - dev->com_rslt = dev->read(dev->dev_id, BME680_MEM_PAGE_ADDR | BME680_SPI_RD_MSK, ®, 1); - if (dev->com_rslt != 0) - rslt = BME680_E_COM_FAIL; - - if (rslt == BME680_OK) { - reg = reg & (~BME680_MEM_PAGE_MSK); - reg = reg | (dev->mem_page & BME680_MEM_PAGE_MSK); - - dev->com_rslt = dev->write(dev->dev_id, BME680_MEM_PAGE_ADDR & BME680_SPI_WR_MSK, - ®, 1); - if (dev->com_rslt != 0) - rslt = BME680_E_COM_FAIL; - } - } - } - - return rslt; -} - -/*! - * @brief This internal API is used to get the memory page based on register address. - */ -static int8_t get_mem_page(struct bme680_dev *dev) -{ - int8_t rslt; - uint8_t reg; - - /* Check for null pointer in the device structure*/ - rslt = null_ptr_check(dev); - if (rslt == BME680_OK) { - dev->com_rslt = dev->read(dev->dev_id, BME680_MEM_PAGE_ADDR | BME680_SPI_RD_MSK, ®, 1); - if (dev->com_rslt != 0) - rslt = BME680_E_COM_FAIL; - else - dev->mem_page = reg & BME680_MEM_PAGE_MSK; - } - - return rslt; -} - -/*! - * @brief This internal API is used to validate the boundary - * conditions. - */ -static int8_t boundary_check(uint8_t *value, uint8_t min, uint8_t max, struct bme680_dev *dev) -{ - int8_t rslt = BME680_OK; - - if (value != NULL) { - /* Check if value is below minimum value */ - if (*value < min) { - /* Auto correct the invalid value to minimum value */ - *value = min; - dev->info_msg |= BME680_I_MIN_CORRECTION; - } - /* Check if value is above maximum value */ - if (*value > max) { - /* Auto correct the invalid value to maximum value */ - *value = max; - dev->info_msg |= BME680_I_MAX_CORRECTION; - } - } else { - rslt = BME680_E_NULL_PTR; - } - - return rslt; -} - -/*! - * @brief This internal API is used to validate the device structure pointer for - * null conditions. - */ -static int8_t null_ptr_check(const struct bme680_dev *dev) -{ - int8_t rslt; - - if ((dev == NULL) || (dev->read == NULL) || (dev->write == NULL) || (dev->delay_ms == NULL)) { - /* Device structure pointer is not valid */ - rslt = BME680_E_NULL_PTR; - } else { - /* Device structure is fine */ - rslt = BME680_OK; - } - - return rslt; -} diff --git a/lib/Adafruit_BME680/bme680.h b/lib/Adafruit_BME680/bme680.h deleted file mode 100644 index 95a87c8d6..000000000 --- a/lib/Adafruit_BME680/bme680.h +++ /dev/null @@ -1,222 +0,0 @@ -/** - * Copyright (C) 2017 - 2018 Bosch Sensortec GmbH - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * Neither the name of the copyright holder nor the names of the - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER - * OR CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - * OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE - * - * The information provided is believed to be accurate and reliable. - * The copyright holder assumes no responsibility - * for the consequences of use - * of such information nor for any infringement of patents or - * other rights of third parties which may result from its use. - * No license is granted by implication or otherwise under any patent or - * patent rights of the copyright holder. - * - * @file bme680.h - * @date 19 Jun 2018 - * @version 3.5.9 - * @brief Sensor driver for BME680 sensor - * - */ -#ifndef BME680_H_ -#define BME680_H_ - -/*! CPP guard */ -#ifdef __cplusplus -extern "C" -{ -#endif - -/* Header includes */ -#include "bme680_defs.h" - -/** function prototype declarations **/ - -/*! - * @brief This API is the entry point. - * It reads the chip-id and calibration data from the sensor. - * @param[in,out] dev - * Structure instance of bme680_dev - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -int8_t bme680_init(struct bme680_dev *dev); - -/*! - * @brief This API writes the given data to the register address - * of the sensor. - * @param[in] reg_addr - * Register address from where the data to be written. - * @param[in] reg_data - * Pointer to data buffer which is to be written - * in the sensor. - * @param[in] len - * No of bytes of data to write.. - * @param[in] dev - * Structure instance of bme680_dev. - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -int8_t bme680_set_regs(const uint8_t *reg_addr, const uint8_t *reg_data, uint8_t len, struct bme680_dev *dev); - -/*! - * @brief This API reads the data from the given register address of the sensor. - * @param[in] reg_addr - * Register address from where the data to be read - * @param[out] reg_data - * Pointer to data buffer to store the read data. - * @param[in] len - * No of bytes of data to be read. - * @param[in] dev - * Structure instance of bme680_dev. - * - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -int8_t bme680_get_regs(uint8_t reg_addr, uint8_t *reg_data, uint16_t len, struct bme680_dev *dev); - -/*! - * @brief This API performs the soft reset of the sensor. - * @param[in] dev - * Structure instance of bme680_dev. - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error. - */ -int8_t bme680_soft_reset(struct bme680_dev *dev); - -/*! - * @brief This API is used to set the power mode of the sensor. - * @param[in] dev - * Structure instance of bme680_dev - * @note Pass the value to bme680_dev.power_mode structure variable. - * value | mode - * -------------|------------------ - * 0x00 | BME680_SLEEP_MODE - * 0x01 | BME680_FORCED_MODE - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -int8_t bme680_set_sensor_mode(struct bme680_dev *dev); - -/*! - * @brief This API is used to get the power mode of the sensor. - * - * @param[in] dev : Structure instance of bme680_dev - * @note : bme680_dev.power_mode structure variable hold the power mode. - * - * value | mode - * ---------|------------------ - * 0x00 | BME680_SLEEP_MODE - * 0x01 | BME680_FORCED_MODE - * - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -int8_t bme680_get_sensor_mode(struct bme680_dev *dev); - -/*! - * @brief This API is used to set the profile duration of the sensor. - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] duration - * Duration of the measurement in ms. - * @return Nothing - */ -void bme680_set_profile_dur(uint16_t duration, struct bme680_dev *dev); - -/*! - * @brief This API is used to get the profile duration of the sensor. - * - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] duration - * Duration of the measurement in ms. - * @return Nothing - */ -void bme680_get_profile_dur(uint16_t *duration, const struct bme680_dev *dev); - -/*! - * @brief This API reads the pressure, temperature and humidity and gas data - * from the sensor, compensates the data and store it in the bme680_data - * structure instance passed by the user. - * @param[out] data - * Structure instance to hold the data. - * @param[in] dev - * Structure instance of bme680_dev. - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error - */ -int8_t bme680_get_sensor_data(struct bme680_field_data *data, struct bme680_dev *dev); - -/*! - * @brief This API is used to set the oversampling, filter and T,P,H, gas selection - * settings in the sensor. - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] desired_settings - * Variable used to select the settings which are to be set in the sensor. - * - * Macros | Functionality - * ----------------------------|---------------------------------------------- - * BME680_OST_SEL | To set temperature oversampling. - * BME680_OSP_SEL | To set pressure oversampling. - * BME680_OSH_SEL | To set humidity oversampling. - * BME680_GAS_MEAS_SEL | To set gas measurement setting. - * BME680_FILTER_SEL | To set filter setting. - * BME680_HCNTRL_SEL | To set humidity control setting. - * BME680_RUN_GAS_SEL | To set run gas setting. - * BME680_NBCONV_SEL | To set NB conversion setting. - * BME680_GAS_SENSOR_SEL | To set all gas sensor related settings - * - * @note Below are the macros to be used by the user for selecting the - * desired settings. User can do OR operation of these macros for configuring - * multiple settings. - * - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error. - */ -int8_t bme680_set_sensor_settings(uint16_t desired_settings, struct bme680_dev *dev); - -/*! - * @brief This API is used to get the oversampling, filter and T,P,H, gas selection - * settings in the sensor. - * @param[in] dev - * Structure instance of bme680_dev. - * @param[in] desired_settings - * Variable used to select the settings which are to be get from the sensor. - * @return Result of API execution status - * @retval zero -> Success / +ve value -> Warning / -ve value -> Error. - */ -int8_t bme680_get_sensor_settings(uint16_t desired_settings, struct bme680_dev *dev); -#ifdef __cplusplus -} -#endif /* End of CPP guard */ -#endif /* BME680_H_ */ -/** @}*/ diff --git a/lib/Adafruit_BME680/bme680_defs.h b/lib/Adafruit_BME680/bme680_defs.h deleted file mode 100644 index 9c7044182..000000000 --- a/lib/Adafruit_BME680/bme680_defs.h +++ /dev/null @@ -1,538 +0,0 @@ -/** - * Copyright (C) 2017 - 2018 Bosch Sensortec GmbH - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * Neither the name of the copyright holder nor the names of the - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER - * OR CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - * OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE - * - * The information provided is believed to be accurate and reliable. - * The copyright holder assumes no responsibility - * for the consequences of use - * of such information nor for any infringement of patents or - * other rights of third parties which may result from its use. - * No license is granted by implication or otherwise under any patent or - * patent rights of the copyright holder. - * - * @file bme680_defs.h - * @date 19 Jun 2018 - * @version 3.5.9 - * @brief Sensor driver for BME680 sensor - */ - -#ifndef BME680_DEFS_H_ -#define BME680_DEFS_H_ - -/** header includes **/ -#ifdef __KERNEL__ -#include -#include -#else -#include -#include -#endif - -/** Common macros **/ - -#if !defined(UINT8_C) && !defined(INT8_C) -#define INT8_C(x) S8_C(x) -#define UINT8_C(x) U8_C(x) -#endif - -#if !defined(UINT16_C) && !defined(INT16_C) -#define INT16_C(x) S16_C(x) -#define UINT16_C(x) U16_C(x) -#endif - -#if !defined(INT32_C) && !defined(UINT32_C) -#define INT32_C(x) S32_C(x) -#define UINT32_C(x) U32_C(x) -#endif - -#if !defined(INT64_C) && !defined(UINT64_C) -#define INT64_C(x) S64_C(x) -#define UINT64_C(x) U64_C(x) -#endif - -/** C standard macros **/ -#ifndef NULL -#ifdef __cplusplus -#define NULL nullptr -#else -#define NULL nullptr -#endif -#endif - -/** BME680 configuration macros */ -/** Enable or un-comment the macro to provide floating point data output **/ -#ifndef BME680_FLOAT_POINT_COMPENSATION -/* #define BME680_FLOAT_POINT_COMPENSATION **/ -#endif - -/** BME680 General config **/ -#define BME680_POLL_PERIOD_MS UINT8_C(10) - -/** BME680 I2C addresses **/ -#define BME680_I2C_ADDR_PRIMARY UINT8_C(0x76) -#define BME680_I2C_ADDR_SECONDARY UINT8_C(0x77) - -/** BME680 unique chip identifier **/ -#define BME680_CHIP_ID UINT8_C(0x61) - -/** BME680 coefficients related defines **/ -#define BME680_COEFF_SIZE UINT8_C(41) -#define BME680_COEFF_ADDR1_LEN UINT8_C(25) -#define BME680_COEFF_ADDR2_LEN UINT8_C(16) - -/** BME680 field_x related defines **/ -#define BME680_FIELD_LENGTH UINT8_C(15) -#define BME680_FIELD_ADDR_OFFSET UINT8_C(17) - -/** Soft reset command **/ -#define BME680_SOFT_RESET_CMD UINT8_C(0xb6) - -/** Error code definitions **/ -#define BME680_OK INT8_C(0) -/* Errors */ -#define BME680_E_NULL_PTR INT8_C(-1) -#define BME680_E_COM_FAIL INT8_C(-2) -#define BME680_E_DEV_NOT_FOUND INT8_C(-3) -#define BME680_E_INVALID_LENGTH INT8_C(-4) - -/* Warnings */ -#define BME680_W_DEFINE_PWR_MODE INT8_C(1) -#define BME680_W_NO_NEW_DATA INT8_C(2) - -/* Info's */ -#define BME680_I_MIN_CORRECTION UINT8_C(1) -#define BME680_I_MAX_CORRECTION UINT8_C(2) - -/** Register map **/ -/** Other coefficient's address **/ -#define BME680_ADDR_RES_HEAT_VAL_ADDR UINT8_C(0x00) -#define BME680_ADDR_RES_HEAT_RANGE_ADDR UINT8_C(0x02) -#define BME680_ADDR_RANGE_SW_ERR_ADDR UINT8_C(0x04) -#define BME680_ADDR_SENS_CONF_START UINT8_C(0x5A) -#define BME680_ADDR_GAS_CONF_START UINT8_C(0x64) - -/** Field settings **/ -#define BME680_FIELD0_ADDR UINT8_C(0x1d) - -/** Heater settings **/ -#define BME680_RES_HEAT0_ADDR UINT8_C(0x5a) -#define BME680_GAS_WAIT0_ADDR UINT8_C(0x64) - -/** Sensor configuration registers **/ -#define BME680_CONF_HEAT_CTRL_ADDR UINT8_C(0x70) -#define BME680_CONF_ODR_RUN_GAS_NBC_ADDR UINT8_C(0x71) -#define BME680_CONF_OS_H_ADDR UINT8_C(0x72) -#define BME680_MEM_PAGE_ADDR UINT8_C(0xf3) -#define BME680_CONF_T_P_MODE_ADDR UINT8_C(0x74) -#define BME680_CONF_ODR_FILT_ADDR UINT8_C(0x75) - -/** Coefficient's address **/ -#define BME680_COEFF_ADDR1 UINT8_C(0x89) -#define BME680_COEFF_ADDR2 UINT8_C(0xe1) - -/** Chip identifier **/ -#define BME680_CHIP_ID_ADDR UINT8_C(0xd0) - -/** Soft reset register **/ -#define BME680_SOFT_RESET_ADDR UINT8_C(0xe0) - -/** Heater control settings **/ -#define BME680_ENABLE_HEATER UINT8_C(0x00) -#define BME680_DISABLE_HEATER UINT8_C(0x08) - -/** Gas measurement settings **/ -#define BME680_DISABLE_GAS_MEAS UINT8_C(0x00) -#define BME680_ENABLE_GAS_MEAS UINT8_C(0x01) - -/** Over-sampling settings **/ -#define BME680_OS_NONE UINT8_C(0) -#define BME680_OS_1X UINT8_C(1) -#define BME680_OS_2X UINT8_C(2) -#define BME680_OS_4X UINT8_C(3) -#define BME680_OS_8X UINT8_C(4) -#define BME680_OS_16X UINT8_C(5) - -/** IIR filter settings **/ -#define BME680_FILTER_SIZE_0 UINT8_C(0) -#define BME680_FILTER_SIZE_1 UINT8_C(1) -#define BME680_FILTER_SIZE_3 UINT8_C(2) -#define BME680_FILTER_SIZE_7 UINT8_C(3) -#define BME680_FILTER_SIZE_15 UINT8_C(4) -#define BME680_FILTER_SIZE_31 UINT8_C(5) -#define BME680_FILTER_SIZE_63 UINT8_C(6) -#define BME680_FILTER_SIZE_127 UINT8_C(7) - -/** Power mode settings */ -#define BME680_SLEEP_MODE UINT8_C(0) -#define BME680_FORCED_MODE UINT8_C(1) - -/** Delay related macro declaration **/ -#define BME680_RESET_PERIOD UINT32_C(10) - -/** SPI memory page settings **/ -#define BME680_MEM_PAGE0 UINT8_C(0x10) -#define BME680_MEM_PAGE1 UINT8_C(0x00) - -/** Ambient humidity shift value for compensation **/ -#define BME680_HUM_REG_SHIFT_VAL UINT8_C(4) - -/** Run gas enable and disable settings **/ -#define BME680_RUN_GAS_DISABLE UINT8_C(0) -#define BME680_RUN_GAS_ENABLE UINT8_C(1) - -/** Buffer length macro declaration **/ -#define BME680_TMP_BUFFER_LENGTH UINT8_C(40) -#define BME680_REG_BUFFER_LENGTH UINT8_C(6) -#define BME680_FIELD_DATA_LENGTH UINT8_C(3) -#define BME680_GAS_REG_BUF_LENGTH UINT8_C(20) - -/** Settings selector **/ -#define BME680_OST_SEL UINT16_C(1) -#define BME680_OSP_SEL UINT16_C(2) -#define BME680_OSH_SEL UINT16_C(4) -#define BME680_GAS_MEAS_SEL UINT16_C(8) -#define BME680_FILTER_SEL UINT16_C(16) -#define BME680_HCNTRL_SEL UINT16_C(32) -#define BME680_RUN_GAS_SEL UINT16_C(64) -#define BME680_NBCONV_SEL UINT16_C(128) -#define BME680_GAS_SENSOR_SEL (BME680_GAS_MEAS_SEL | BME680_RUN_GAS_SEL | BME680_NBCONV_SEL) - -/** Number of conversion settings **/ -#define BME680_NBCONV_MIN UINT8_C(0) -#define BME680_NBCONV_MAX UINT8_C(10) - -/** Mask definitions **/ -#define BME680_GAS_MEAS_MSK UINT8_C(0x30) -#define BME680_NBCONV_MSK UINT8_C(0X0F) -#define BME680_FILTER_MSK UINT8_C(0X1C) -#define BME680_OST_MSK UINT8_C(0XE0) -#define BME680_OSP_MSK UINT8_C(0X1C) -#define BME680_OSH_MSK UINT8_C(0X07) -#define BME680_HCTRL_MSK UINT8_C(0x08) -#define BME680_RUN_GAS_MSK UINT8_C(0x10) -#define BME680_MODE_MSK UINT8_C(0x03) -#define BME680_RHRANGE_MSK UINT8_C(0x30) -#define BME680_RSERROR_MSK UINT8_C(0xf0) -#define BME680_NEW_DATA_MSK UINT8_C(0x80) -#define BME680_GAS_INDEX_MSK UINT8_C(0x0f) -#define BME680_GAS_RANGE_MSK UINT8_C(0x0f) -#define BME680_GASM_VALID_MSK UINT8_C(0x20) -#define BME680_HEAT_STAB_MSK UINT8_C(0x10) -#define BME680_MEM_PAGE_MSK UINT8_C(0x10) -#define BME680_SPI_RD_MSK UINT8_C(0x80) -#define BME680_SPI_WR_MSK UINT8_C(0x7f) -#define BME680_BIT_H1_DATA_MSK UINT8_C(0x0F) - -/** Bit position definitions for sensor settings **/ -#define BME680_GAS_MEAS_POS UINT8_C(4) -#define BME680_FILTER_POS UINT8_C(2) -#define BME680_OST_POS UINT8_C(5) -#define BME680_OSP_POS UINT8_C(2) -#define BME680_RUN_GAS_POS UINT8_C(4) - -/** Array Index to Field data mapping for Calibration Data **/ -#define BME680_T2_LSB_REG (1) -#define BME680_T2_MSB_REG (2) -#define BME680_T3_REG (3) -#define BME680_P1_LSB_REG (5) -#define BME680_P1_MSB_REG (6) -#define BME680_P2_LSB_REG (7) -#define BME680_P2_MSB_REG (8) -#define BME680_P3_REG (9) -#define BME680_P4_LSB_REG (11) -#define BME680_P4_MSB_REG (12) -#define BME680_P5_LSB_REG (13) -#define BME680_P5_MSB_REG (14) -#define BME680_P7_REG (15) -#define BME680_P6_REG (16) -#define BME680_P8_LSB_REG (19) -#define BME680_P8_MSB_REG (20) -#define BME680_P9_LSB_REG (21) -#define BME680_P9_MSB_REG (22) -#define BME680_P10_REG (23) -#define BME680_H2_MSB_REG (25) -#define BME680_H2_LSB_REG (26) -#define BME680_H1_LSB_REG (26) -#define BME680_H1_MSB_REG (27) -#define BME680_H3_REG (28) -#define BME680_H4_REG (29) -#define BME680_H5_REG (30) -#define BME680_H6_REG (31) -#define BME680_H7_REG (32) -#define BME680_T1_LSB_REG (33) -#define BME680_T1_MSB_REG (34) -#define BME680_GH2_LSB_REG (35) -#define BME680_GH2_MSB_REG (36) -#define BME680_GH1_REG (37) -#define BME680_GH3_REG (38) - -/** BME680 register buffer index settings **/ -#define BME680_REG_FILTER_INDEX UINT8_C(5) -#define BME680_REG_TEMP_INDEX UINT8_C(4) -#define BME680_REG_PRES_INDEX UINT8_C(4) -#define BME680_REG_HUM_INDEX UINT8_C(2) -#define BME680_REG_NBCONV_INDEX UINT8_C(1) -#define BME680_REG_RUN_GAS_INDEX UINT8_C(1) -#define BME680_REG_HCTRL_INDEX UINT8_C(0) - -/** BME680 pressure calculation macros **/ -/*! This max value is used to provide precedence to multiplication or division - * in pressure compensation equation to achieve least loss of precision and - * avoiding overflows. - * i.e Comparing value, BME680_MAX_OVERFLOW_VAL = INT32_C(1 << 30) - */ -#define BME680_MAX_OVERFLOW_VAL INT32_C(0x40000000) - -/** Macro to combine two 8 bit data's to form a 16 bit data **/ -#define BME680_CONCAT_BYTES(msb, lsb) (((uint16_t)msb << 8) | (uint16_t)lsb) - -/** Macro to SET and GET BITS of a register **/ -#define BME680_SET_BITS(reg_data, bitname, data) \ - ((reg_data & ~(bitname##_MSK)) | \ - ((data << bitname##_POS) & bitname##_MSK)) -#define BME680_GET_BITS(reg_data, bitname) ((reg_data & (bitname##_MSK)) >> \ - (bitname##_POS)) - -/** Macro variant to handle the bitname position if it is zero **/ -#define BME680_SET_BITS_POS_0(reg_data, bitname, data) \ - ((reg_data & ~(bitname##_MSK)) | \ - (data & bitname##_MSK)) -#define BME680_GET_BITS_POS_0(reg_data, bitname) (reg_data & (bitname##_MSK)) - -/** Type definitions **/ -/*! - * @brief Generic communication function pointer - * @param[in] dev_id - * Place holder to store the id of the device structure - * Can be used to store the index of the Chip select or - * I2C address of the device. - * @param[in] reg_addr - * Used to select the register the where data needs to - * be read from or written to. - * @param[in/out] reg_data - * Data array to read/write - * @param[in] len - * Length of the data array - */ -typedef int8_t (*bme680_com_fptr_t)(uint8_t dev_id, uint8_t reg_addr, uint8_t *data, uint16_t len); - -/*! - * @brief Delay function pointer - * @param[in] period - * Time period in milliseconds - */ -typedef void (*bme680_delay_fptr_t)(uint32_t period); - -/*! - * @brief Interface selection Enumerations - */ -enum bme680_intf { - /*! SPI interface */ - BME680_SPI_INTF, - /*! I2C interface */ - BME680_I2C_INTF -}; - -/** structure definitions **/ -/*! - * @brief Sensor field data structure - */ -struct bme680_field_data { - /*! Contains new_data, gasm_valid & heat_stab */ - uint8_t status; - /*! The index of the heater profile used */ - uint8_t gas_index; - /*! Measurement index to track order */ - uint8_t meas_index; - -#ifndef BME680_FLOAT_POINT_COMPENSATION - /*! Temperature in degree celsius x100 */ - int16_t temperature; - /*! Pressure in Pascal */ - uint32_t pressure; - /*! Humidity in % relative humidity x1000 */ - uint32_t humidity; - /*! Gas resistance in Ohms */ - uint32_t gas_resistance; -#else - /*! Temperature in degree celsius */ - float temperature; - /*! Pressure in Pascal */ - float pressure; - /*! Humidity in % relative humidity x1000 */ - float humidity; - /*! Gas resistance in Ohms */ - float gas_resistance; - -#endif - -}; - -/*! - * @brief Structure to hold the Calibration data - */ -struct bme680_calib_data { - /*! Variable to store calibrated humidity data */ - uint16_t par_h1; - /*! Variable to store calibrated humidity data */ - uint16_t par_h2; - /*! Variable to store calibrated humidity data */ - int8_t par_h3; - /*! Variable to store calibrated humidity data */ - int8_t par_h4; - /*! Variable to store calibrated humidity data */ - int8_t par_h5; - /*! Variable to store calibrated humidity data */ - uint8_t par_h6; - /*! Variable to store calibrated humidity data */ - int8_t par_h7; - /*! Variable to store calibrated gas data */ - int8_t par_gh1; - /*! Variable to store calibrated gas data */ - int16_t par_gh2; - /*! Variable to store calibrated gas data */ - int8_t par_gh3; - /*! Variable to store calibrated temperature data */ - uint16_t par_t1; - /*! Variable to store calibrated temperature data */ - int16_t par_t2; - /*! Variable to store calibrated temperature data */ - int8_t par_t3; - /*! Variable to store calibrated pressure data */ - uint16_t par_p1; - /*! Variable to store calibrated pressure data */ - int16_t par_p2; - /*! Variable to store calibrated pressure data */ - int8_t par_p3; - /*! Variable to store calibrated pressure data */ - int16_t par_p4; - /*! Variable to store calibrated pressure data */ - int16_t par_p5; - /*! Variable to store calibrated pressure data */ - int8_t par_p6; - /*! Variable to store calibrated pressure data */ - int8_t par_p7; - /*! Variable to store calibrated pressure data */ - int16_t par_p8; - /*! Variable to store calibrated pressure data */ - int16_t par_p9; - /*! Variable to store calibrated pressure data */ - uint8_t par_p10; - -#ifndef BME680_FLOAT_POINT_COMPENSATION - /*! Variable to store t_fine size */ - int32_t t_fine; -#else - /*! Variable to store t_fine size */ - float t_fine; -#endif - /*! Variable to store heater resistance range */ - uint8_t res_heat_range; - /*! Variable to store heater resistance value */ - int8_t res_heat_val; - /*! Variable to store error range */ - int8_t range_sw_err; -}; - -/*! - * @brief BME680 sensor settings structure which comprises of ODR, - * over-sampling and filter settings. - */ -struct bme680_tph_sett { - /*! Humidity oversampling */ - uint8_t os_hum; - /*! Temperature oversampling */ - uint8_t os_temp; - /*! Pressure oversampling */ - uint8_t os_pres; - /*! Filter coefficient */ - uint8_t filter; -}; - -/*! - * @brief BME680 gas sensor which comprises of gas settings - * and status parameters - */ -struct bme680_gas_sett { - /*! Variable to store nb conversion */ - uint8_t nb_conv; - /*! Variable to store heater control */ - uint8_t heatr_ctrl; - /*! Run gas enable value */ - uint8_t run_gas; - /*! Heater temperature value */ - uint16_t heatr_temp; - /*! Duration profile value */ - uint16_t heatr_dur; -}; - -/*! - * @brief BME680 device structure - */ -struct bme680_dev { - /*! Chip Id */ - uint8_t chip_id; - /*! Device Id */ - uint8_t dev_id; - /*! SPI/I2C interface */ - enum bme680_intf intf; - /*! Memory page used */ - uint8_t mem_page; - /*! Ambient temperature in Degree C */ - int8_t amb_temp; - /*! Sensor calibration data */ - struct bme680_calib_data calib; - /*! Sensor settings */ - struct bme680_tph_sett tph_sett; - /*! Gas Sensor settings */ - struct bme680_gas_sett gas_sett; - /*! Sensor power modes */ - uint8_t power_mode; - /*! New sensor fields */ - uint8_t new_fields; - /*! Store the info messages */ - uint8_t info_msg; - /*! Bus read function pointer */ - bme680_com_fptr_t read; - /*! Bus write function pointer */ - bme680_com_fptr_t write; - /*! delay function pointer */ - bme680_delay_fptr_t delay_ms; - /*! Communication function result */ - int8_t com_rslt; -}; - - - -#endif /* BME680_DEFS_H_ */ -/** @}*/ -/** @}*/ diff --git a/lib/Adafruit_BME680/bme68x.c b/lib/Adafruit_BME680/bme68x.c new file mode 100644 index 000000000..95e1a9876 --- /dev/null +++ b/lib/Adafruit_BME680/bme68x.c @@ -0,0 +1,1848 @@ +/** +* Copyright (c) 2021 Bosch Sensortec GmbH. All rights reserved. +* +* BSD-3-Clause +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* +* 3. Neither the name of the copyright holder nor the names of its +* contributors may be used to endorse or promote products derived from +* this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* +* @file bme68x.c +* @date 2021-05-24 +* @version v4.4.6 +* +*/ + +#include "bme68x.h" +#include + +/* This internal API is used to read the calibration coefficients */ +static int8_t get_calib_data(struct bme68x_dev *dev); + +/* This internal API is used to read variant ID information register status */ +static int8_t read_variant_id(struct bme68x_dev *dev); + +/* This internal API is used to calculate the gas wait */ +static uint8_t calc_gas_wait(uint16_t dur); + +#ifndef BME68X_USE_FPU + +/* This internal API is used to calculate the temperature in integer */ +static int16_t calc_temperature(uint32_t temp_adc, struct bme68x_dev *dev); + +/* This internal API is used to calculate the pressure in integer */ +static uint32_t calc_pressure(uint32_t pres_adc, const struct bme68x_dev *dev); + +/* This internal API is used to calculate the humidity in integer */ +static uint32_t calc_humidity(uint16_t hum_adc, const struct bme68x_dev *dev); + +/* This internal API is used to calculate the gas resistance high */ +static uint32_t calc_gas_resistance_high(uint16_t gas_res_adc, uint8_t gas_range); + +/* This internal API is used to calculate the gas resistance low */ +static uint32_t calc_gas_resistance_low(uint16_t gas_res_adc, uint8_t gas_range, const struct bme68x_dev *dev); + +/* This internal API is used to calculate the heater resistance using integer */ +static uint8_t calc_res_heat(uint16_t temp, const struct bme68x_dev *dev); + +#else + +/* This internal API is used to calculate the temperature value in float */ +static float calc_temperature(uint32_t temp_adc, struct bme68x_dev *dev); + +/* This internal API is used to calculate the pressure value in float */ +static float calc_pressure(uint32_t pres_adc, const struct bme68x_dev *dev); + +/* This internal API is used to calculate the humidity value in float */ +static float calc_humidity(uint16_t hum_adc, const struct bme68x_dev *dev); + +/* This internal API is used to calculate the gas resistance high value in float */ +static float calc_gas_resistance_high(uint16_t gas_res_adc, uint8_t gas_range); + +/* This internal API is used to calculate the gas resistance low value in float */ +static float calc_gas_resistance_low(uint16_t gas_res_adc, uint8_t gas_range, const struct bme68x_dev *dev); + +/* This internal API is used to calculate the heater resistance value using float */ +static uint8_t calc_res_heat(uint16_t temp, const struct bme68x_dev *dev); + +#endif + +/* This internal API is used to read a single data of the sensor */ +static int8_t read_field_data(uint8_t index, struct bme68x_data *data, struct bme68x_dev *dev); + +/* This internal API is used to read all data fields of the sensor */ +static int8_t read_all_field_data(struct bme68x_data * const data[], struct bme68x_dev *dev); + +/* This internal API is used to switch between SPI memory pages */ +static int8_t set_mem_page(uint8_t reg_addr, struct bme68x_dev *dev); + +/* This internal API is used to get the current SPI memory page */ +static int8_t get_mem_page(struct bme68x_dev *dev); + +/* This internal API is used to check the bme68x_dev for null pointers */ +static int8_t null_ptr_check(const struct bme68x_dev *dev); + +/* This internal API is used to set heater configurations */ +static int8_t set_conf(const struct bme68x_heatr_conf *conf, uint8_t op_mode, uint8_t *nb_conv, struct bme68x_dev *dev); + +/* This internal API is used to limit the max value of a parameter */ +static int8_t boundary_check(uint8_t *value, uint8_t max, struct bme68x_dev *dev); + +/* This internal API is used to calculate the register value for + * shared heater duration */ +static uint8_t calc_heatr_dur_shared(uint16_t dur); + +/* This internal API is used to swap two fields */ +static void swap_fields(uint8_t index1, uint8_t index2, struct bme68x_data *field[]); + +/* This internal API is used sort the sensor data */ +static void sort_sensor_data(uint8_t low_index, uint8_t high_index, struct bme68x_data *field[]); + +/* + * @brief Function to analyze the sensor data + * + * @param[in] data Array of measurement data + * @param[in] n_meas Number of measurements + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +static int8_t analyze_sensor_data(const struct bme68x_data *data, uint8_t n_meas); + +/******************************************************************************************/ +/* Global API definitions */ +/******************************************************************************************/ + +/* @brief This API reads the chip-id of the sensor which is the first step to +* verify the sensor and also calibrates the sensor +* As this API is the entry point, call this API before using other APIs. +*/ +int8_t bme68x_init(struct bme68x_dev *dev) +{ + int8_t rslt; + + rslt = bme68x_soft_reset(dev); + if (rslt == BME68X_OK) + { + rslt = bme68x_get_regs(BME68X_REG_CHIP_ID, &dev->chip_id, 1, dev); + if (rslt == BME68X_OK) + { + if (dev->chip_id == BME68X_CHIP_ID) + { + /* Read Variant ID */ + rslt = read_variant_id(dev); + + if (rslt == BME68X_OK) + { + /* Get the Calibration data */ + rslt = get_calib_data(dev); + } + } + else + { + rslt = BME68X_E_DEV_NOT_FOUND; + } + } + } + + return rslt; +} + +/* + * @brief This API writes the given data to the register address of the sensor + */ +int8_t bme68x_set_regs(const uint8_t *reg_addr, const uint8_t *reg_data, uint32_t len, struct bme68x_dev *dev) +{ + int8_t rslt; + + /* Length of the temporary buffer is 2*(length of register)*/ + uint8_t tmp_buff[BME68X_LEN_INTERLEAVE_BUFF] = { 0 }; + uint16_t index; + + /* Check for null pointer in the device structure*/ + rslt = null_ptr_check(dev); + if ((rslt == BME68X_OK) && reg_addr && reg_data) + { + if ((len > 0) && (len <= (BME68X_LEN_INTERLEAVE_BUFF / 2))) + { + /* Interleave the 2 arrays */ + for (index = 0; index < len; index++) + { + if (dev->intf == BME68X_SPI_INTF) + { + /* Set the memory page */ + rslt = set_mem_page(reg_addr[index], dev); + tmp_buff[(2 * index)] = reg_addr[index] & BME68X_SPI_WR_MSK; + } + else + { + tmp_buff[(2 * index)] = reg_addr[index]; + } + + tmp_buff[(2 * index) + 1] = reg_data[index]; + } + + /* Write the interleaved array */ + if (rslt == BME68X_OK) + { + dev->intf_rslt = dev->write(tmp_buff[0], &tmp_buff[1], (2 * len) - 1, dev->intf_ptr); + if (dev->intf_rslt != 0) + { + rslt = BME68X_E_COM_FAIL; + } + } + } + else + { + rslt = BME68X_E_INVALID_LENGTH; + } + } + else + { + rslt = BME68X_E_NULL_PTR; + } + + return rslt; +} + +/* + * @brief This API reads the data from the given register address of sensor. + */ +int8_t bme68x_get_regs(uint8_t reg_addr, uint8_t *reg_data, uint32_t len, struct bme68x_dev *dev) +{ + int8_t rslt; + + /* Check for null pointer in the device structure*/ + rslt = null_ptr_check(dev); + if ((rslt == BME68X_OK) && reg_data) + { + if (dev->intf == BME68X_SPI_INTF) + { + /* Set the memory page */ + rslt = set_mem_page(reg_addr, dev); + if (rslt == BME68X_OK) + { + reg_addr = reg_addr | BME68X_SPI_RD_MSK; + } + } + + dev->intf_rslt = dev->read(reg_addr, reg_data, len, dev->intf_ptr); + if (dev->intf_rslt != 0) + { + rslt = BME68X_E_COM_FAIL; + } + } + else + { + rslt = BME68X_E_NULL_PTR; + } + + return rslt; +} + +/* + * @brief This API soft-resets the sensor. + */ +int8_t bme68x_soft_reset(struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t reg_addr = BME68X_REG_SOFT_RESET; + + /* 0xb6 is the soft reset command */ + uint8_t soft_rst_cmd = BME68X_SOFT_RESET_CMD; + + /* Check for null pointer in the device structure*/ + rslt = null_ptr_check(dev); + if (rslt == BME68X_OK) + { + if (dev->intf == BME68X_SPI_INTF) + { + rslt = get_mem_page(dev); + } + + /* Reset the device */ + if (rslt == BME68X_OK) + { + rslt = bme68x_set_regs(®_addr, &soft_rst_cmd, 1, dev); + + /* Wait for 5ms */ + dev->delay_us(BME68X_PERIOD_RESET, dev->intf_ptr); + if (rslt == BME68X_OK) + { + /* After reset get the memory page */ + if (dev->intf == BME68X_SPI_INTF) + { + rslt = get_mem_page(dev); + } + } + } + } + + return rslt; +} + +/* + * @brief This API is used to set the oversampling, filter and odr configuration + */ +int8_t bme68x_set_conf(struct bme68x_conf *conf, struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t odr20 = 0, odr3 = 1; + uint8_t current_op_mode; + + /* Register data starting from BME68X_REG_CTRL_GAS_1(0x71) up to BME68X_REG_CONFIG(0x75) */ + uint8_t reg_array[BME68X_LEN_CONFIG] = { 0x71, 0x72, 0x73, 0x74, 0x75 }; + uint8_t data_array[BME68X_LEN_CONFIG] = { 0 }; + + rslt = bme68x_get_op_mode(¤t_op_mode, dev); + if (rslt == BME68X_OK) + { + /* Configure only in the sleep mode */ + rslt = bme68x_set_op_mode(BME68X_SLEEP_MODE, dev); + } + + if (conf == NULL) + { + rslt = BME68X_E_NULL_PTR; + } + else if (rslt == BME68X_OK) + { + /* Read the whole configuration and write it back once later */ + rslt = bme68x_get_regs(reg_array[0], data_array, BME68X_LEN_CONFIG, dev); + dev->info_msg = BME68X_OK; + if (rslt == BME68X_OK) + { + rslt = boundary_check(&conf->filter, BME68X_FILTER_SIZE_127, dev); + } + + if (rslt == BME68X_OK) + { + rslt = boundary_check(&conf->os_temp, BME68X_OS_16X, dev); + } + + if (rslt == BME68X_OK) + { + rslt = boundary_check(&conf->os_pres, BME68X_OS_16X, dev); + } + + if (rslt == BME68X_OK) + { + rslt = boundary_check(&conf->os_hum, BME68X_OS_16X, dev); + } + + if (rslt == BME68X_OK) + { + rslt = boundary_check(&conf->odr, BME68X_ODR_NONE, dev); + } + + if (rslt == BME68X_OK) + { + data_array[4] = BME68X_SET_BITS(data_array[4], BME68X_FILTER, conf->filter); + data_array[3] = BME68X_SET_BITS(data_array[3], BME68X_OST, conf->os_temp); + data_array[3] = BME68X_SET_BITS(data_array[3], BME68X_OSP, conf->os_pres); + data_array[1] = BME68X_SET_BITS_POS_0(data_array[1], BME68X_OSH, conf->os_hum); + if (conf->odr != BME68X_ODR_NONE) + { + odr20 = conf->odr; + odr3 = 0; + } + + data_array[4] = BME68X_SET_BITS(data_array[4], BME68X_ODR20, odr20); + data_array[0] = BME68X_SET_BITS(data_array[0], BME68X_ODR3, odr3); + } + } + + if (rslt == BME68X_OK) + { + rslt = bme68x_set_regs(reg_array, data_array, BME68X_LEN_CONFIG, dev); + } + + if ((current_op_mode != BME68X_SLEEP_MODE) && (rslt == BME68X_OK)) + { + rslt = bme68x_set_op_mode(current_op_mode, dev); + } + + return rslt; +} + +/* + * @brief This API is used to get the oversampling, filter and odr + */ +int8_t bme68x_get_conf(struct bme68x_conf *conf, struct bme68x_dev *dev) +{ + int8_t rslt; + + /* starting address of the register array for burst read*/ + uint8_t reg_addr = BME68X_REG_CTRL_GAS_1; + uint8_t data_array[BME68X_LEN_CONFIG]; + + rslt = bme68x_get_regs(reg_addr, data_array, 5, dev); + if (!conf) + { + rslt = BME68X_E_NULL_PTR; + } + else if (rslt == BME68X_OK) + { + conf->os_hum = BME68X_GET_BITS_POS_0(data_array[1], BME68X_OSH); + conf->filter = BME68X_GET_BITS(data_array[4], BME68X_FILTER); + conf->os_temp = BME68X_GET_BITS(data_array[3], BME68X_OST); + conf->os_pres = BME68X_GET_BITS(data_array[3], BME68X_OSP); + if (BME68X_GET_BITS(data_array[0], BME68X_ODR3)) + { + conf->odr = BME68X_ODR_NONE; + } + else + { + conf->odr = BME68X_GET_BITS(data_array[4], BME68X_ODR20); + } + } + + return rslt; +} + +/* + * @brief This API is used to set the operation mode of the sensor + */ +int8_t bme68x_set_op_mode(const uint8_t op_mode, struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t tmp_pow_mode; + uint8_t pow_mode = 0; + uint8_t reg_addr = BME68X_REG_CTRL_MEAS; + + /* Call until in sleep */ + do + { + rslt = bme68x_get_regs(BME68X_REG_CTRL_MEAS, &tmp_pow_mode, 1, dev); + if (rslt == BME68X_OK) + { + /* Put to sleep before changing mode */ + pow_mode = (tmp_pow_mode & BME68X_MODE_MSK); + if (pow_mode != BME68X_SLEEP_MODE) + { + tmp_pow_mode &= ~BME68X_MODE_MSK; /* Set to sleep */ + rslt = bme68x_set_regs(®_addr, &tmp_pow_mode, 1, dev); + dev->delay_us(BME68X_PERIOD_POLL, dev->intf_ptr); + } + } + } while ((pow_mode != BME68X_SLEEP_MODE) && (rslt == BME68X_OK)); + + /* Already in sleep */ + if ((op_mode != BME68X_SLEEP_MODE) && (rslt == BME68X_OK)) + { + tmp_pow_mode = (tmp_pow_mode & ~BME68X_MODE_MSK) | (op_mode & BME68X_MODE_MSK); + rslt = bme68x_set_regs(®_addr, &tmp_pow_mode, 1, dev); + } + + return rslt; +} + +/* + * @brief This API is used to get the operation mode of the sensor. + */ +int8_t bme68x_get_op_mode(uint8_t *op_mode, struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t mode; + + if (op_mode) + { + rslt = bme68x_get_regs(BME68X_REG_CTRL_MEAS, &mode, 1, dev); + + /* Masking the other register bit info*/ + *op_mode = mode & BME68X_MODE_MSK; + } + else + { + rslt = BME68X_E_NULL_PTR; + } + + return rslt; +} + +/* + * @brief This API is used to get the remaining duration that can be used for heating. + */ +uint32_t bme68x_get_meas_dur(const uint8_t op_mode, struct bme68x_conf *conf, struct bme68x_dev *dev) +{ + int8_t rslt; + uint32_t meas_dur = 0; /* Calculate in us */ + uint32_t meas_cycles; + uint8_t os_to_meas_cycles[6] = { 0, 1, 2, 4, 8, 16 }; + + if (conf != NULL) + { + /* Boundary check for temperature oversampling */ + rslt = boundary_check(&conf->os_temp, BME68X_OS_16X, dev); + + if (rslt == BME68X_OK) + { + /* Boundary check for pressure oversampling */ + rslt = boundary_check(&conf->os_pres, BME68X_OS_16X, dev); + } + + if (rslt == BME68X_OK) + { + /* Boundary check for humidity oversampling */ + rslt = boundary_check(&conf->os_hum, BME68X_OS_16X, dev); + } + + if (rslt == BME68X_OK) + { + meas_cycles = os_to_meas_cycles[conf->os_temp]; + meas_cycles += os_to_meas_cycles[conf->os_pres]; + meas_cycles += os_to_meas_cycles[conf->os_hum]; + + /* TPH measurement duration */ + meas_dur = meas_cycles * UINT32_C(1963); + meas_dur += UINT32_C(477 * 4); /* TPH switching duration */ + meas_dur += UINT32_C(477 * 5); /* Gas measurement duration */ + + if (op_mode != BME68X_PARALLEL_MODE) + { + meas_dur += UINT32_C(1000); /* Wake up duration of 1ms */ + } + } + } + + return meas_dur; +} + +/* + * @brief This API reads the pressure, temperature and humidity and gas data + * from the sensor, compensates the data and store it in the bme68x_data + * structure instance passed by the user. + */ +int8_t bme68x_get_data(uint8_t op_mode, struct bme68x_data *data, uint8_t *n_data, struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t i = 0, j = 0, new_fields = 0; + struct bme68x_data *field_ptr[3] = { 0 }; + struct bme68x_data field_data[3] = { { 0 } }; + + field_ptr[0] = &field_data[0]; + field_ptr[1] = &field_data[1]; + field_ptr[2] = &field_data[2]; + + rslt = null_ptr_check(dev); + if ((rslt == BME68X_OK) && (data != NULL)) + { + /* Reading the sensor data in forced mode only */ + if (op_mode == BME68X_FORCED_MODE) + { + rslt = read_field_data(0, data, dev); + if (rslt == BME68X_OK) + { + if (data->status & BME68X_NEW_DATA_MSK) + { + new_fields = 1; + } + else + { + new_fields = 0; + rslt = BME68X_W_NO_NEW_DATA; + } + } + } + else if ((op_mode == BME68X_PARALLEL_MODE) || (op_mode == BME68X_SEQUENTIAL_MODE)) + { + /* Read the 3 fields and count the number of new data fields */ + rslt = read_all_field_data(field_ptr, dev); + + new_fields = 0; + for (i = 0; (i < 3) && (rslt == BME68X_OK); i++) + { + if (field_ptr[i]->status & BME68X_NEW_DATA_MSK) + { + new_fields++; + } + } + + /* Sort the sensor data in parallel & sequential modes*/ + for (i = 0; (i < 2) && (rslt == BME68X_OK); i++) + { + for (j = i + 1; j < 3; j++) + { + sort_sensor_data(i, j, field_ptr); + } + } + + /* Copy the sorted data */ + for (i = 0; ((i < 3) && (rslt == BME68X_OK)); i++) + { + data[i] = *field_ptr[i]; + } + + if (new_fields == 0) + { + rslt = BME68X_W_NO_NEW_DATA; + } + } + else + { + rslt = BME68X_W_DEFINE_OP_MODE; + } + + if (n_data == NULL) + { + rslt = BME68X_E_NULL_PTR; + } + else + { + *n_data = new_fields; + } + } + else + { + rslt = BME68X_E_NULL_PTR; + } + + return rslt; +} + +/* + * @brief This API is used to set the gas configuration of the sensor. + */ +int8_t bme68x_set_heatr_conf(uint8_t op_mode, const struct bme68x_heatr_conf *conf, struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t nb_conv = 0; + uint8_t hctrl, run_gas = 0; + uint8_t ctrl_gas_data[2]; + uint8_t ctrl_gas_addr[2] = { BME68X_REG_CTRL_GAS_0, BME68X_REG_CTRL_GAS_1 }; + + if (conf != NULL) + { + rslt = bme68x_set_op_mode(BME68X_SLEEP_MODE, dev); + if (rslt == BME68X_OK) + { + rslt = set_conf(conf, op_mode, &nb_conv, dev); + } + + if (rslt == BME68X_OK) + { + rslt = bme68x_get_regs(BME68X_REG_CTRL_GAS_0, ctrl_gas_data, 2, dev); + if (rslt == BME68X_OK) + { + if (conf->enable == BME68X_ENABLE) + { + hctrl = BME68X_ENABLE_HEATER; + if (dev->variant_id == BME68X_VARIANT_GAS_HIGH) + { + run_gas = BME68X_ENABLE_GAS_MEAS_H; + } + else + { + run_gas = BME68X_ENABLE_GAS_MEAS_L; + } + } + else + { + hctrl = BME68X_DISABLE_HEATER; + run_gas = BME68X_DISABLE_GAS_MEAS; + } + + ctrl_gas_data[0] = BME68X_SET_BITS(ctrl_gas_data[0], BME68X_HCTRL, hctrl); + ctrl_gas_data[1] = BME68X_SET_BITS_POS_0(ctrl_gas_data[1], BME68X_NBCONV, nb_conv); + ctrl_gas_data[1] = BME68X_SET_BITS(ctrl_gas_data[1], BME68X_RUN_GAS, run_gas); + rslt = bme68x_set_regs(ctrl_gas_addr, ctrl_gas_data, 2, dev); + } + } + } + else + { + rslt = BME68X_E_NULL_PTR; + } + + return rslt; +} + +/* + * @brief This API is used to get the gas configuration of the sensor. + */ +int8_t bme68x_get_heatr_conf(const struct bme68x_heatr_conf *conf, struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t data_array[10] = { 0 }; + uint8_t i; + + /* FIXME: Add conversion to deg C and ms and add the other parameters */ + rslt = bme68x_get_regs(BME68X_REG_RES_HEAT0, data_array, 10, dev); + if (rslt == BME68X_OK) + { + if (conf && conf->heatr_dur_prof && conf->heatr_temp_prof) + { + for (i = 0; i < 10; i++) + { + conf->heatr_temp_prof[i] = data_array[i]; + } + + rslt = bme68x_get_regs(BME68X_REG_GAS_WAIT0, data_array, 10, dev); + if (rslt == BME68X_OK) + { + for (i = 0; i < 10; i++) + { + conf->heatr_dur_prof[i] = data_array[i]; + } + } + } + else + { + rslt = BME68X_E_NULL_PTR; + } + } + + return rslt; +} + +/* + * @brief This API performs Self-test of low gas variant of BME68X + */ +int8_t bme68x_low_gas_selftest_check(const struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t n_fields; + uint8_t i = 0; + struct bme68x_data data[BME68X_N_MEAS] = { { 0 } }; + struct bme68x_dev t_dev; + struct bme68x_conf conf; + struct bme68x_heatr_conf heatr_conf; + + /* Copy required parameters from reference bme68x_dev struct */ + t_dev.amb_temp = 25; + t_dev.read = dev->read; + t_dev.write = dev->write; + t_dev.intf = dev->intf; + t_dev.delay_us = dev->delay_us; + t_dev.intf_ptr = dev->intf_ptr; + rslt = bme68x_init(&t_dev); + if (rslt == BME68X_OK) + { + /* Set the temperature, pressure and humidity & filter settings */ + conf.os_hum = BME68X_OS_1X; + conf.os_pres = BME68X_OS_16X; + conf.os_temp = BME68X_OS_2X; + + /* Set the remaining gas sensor settings and link the heating profile */ + heatr_conf.enable = BME68X_ENABLE; + heatr_conf.heatr_dur = BME68X_HEATR_DUR1; + heatr_conf.heatr_temp = BME68X_HIGH_TEMP; + rslt = bme68x_set_heatr_conf(BME68X_FORCED_MODE, &heatr_conf, &t_dev); + if (rslt == BME68X_OK) + { + rslt = bme68x_set_conf(&conf, &t_dev); + if (rslt == BME68X_OK) + { + rslt = bme68x_set_op_mode(BME68X_FORCED_MODE, &t_dev); /* Trigger a measurement */ + if (rslt == BME68X_OK) + { + /* Wait for the measurement to complete */ + t_dev.delay_us(BME68X_HEATR_DUR1_DELAY, t_dev.intf_ptr); + rslt = bme68x_get_data(BME68X_FORCED_MODE, &data[0], &n_fields, &t_dev); + if (rslt == BME68X_OK) + { + if ((data[0].idac != 0x00) && (data[0].idac != 0xFF) && + (data[0].status & BME68X_GASM_VALID_MSK)) + { + rslt = BME68X_OK; + } + else + { + rslt = BME68X_E_SELF_TEST; + } + } + } + } + } + + heatr_conf.heatr_dur = BME68X_HEATR_DUR2; + while ((rslt == BME68X_OK) && (i < BME68X_N_MEAS)) + { + if (i % 2 == 0) + { + heatr_conf.heatr_temp = BME68X_HIGH_TEMP; /* Higher temperature */ + } + else + { + heatr_conf.heatr_temp = BME68X_LOW_TEMP; /* Lower temperature */ + } + + rslt = bme68x_set_heatr_conf(BME68X_FORCED_MODE, &heatr_conf, &t_dev); + if (rslt == BME68X_OK) + { + rslt = bme68x_set_conf(&conf, &t_dev); + if (rslt == BME68X_OK) + { + rslt = bme68x_set_op_mode(BME68X_FORCED_MODE, &t_dev); /* Trigger a measurement */ + if (rslt == BME68X_OK) + { + /* Wait for the measurement to complete */ + t_dev.delay_us(BME68X_HEATR_DUR2_DELAY, t_dev.intf_ptr); + rslt = bme68x_get_data(BME68X_FORCED_MODE, &data[i], &n_fields, &t_dev); + } + } + } + + i++; + } + + if (rslt == BME68X_OK) + { + rslt = analyze_sensor_data(data, BME68X_N_MEAS); + } + } + + return rslt; +} + +/*****************************INTERNAL APIs***********************************************/ +#ifndef BME68X_USE_FPU + +/* @brief This internal API is used to calculate the temperature value. */ +static int16_t calc_temperature(uint32_t temp_adc, struct bme68x_dev *dev) +{ + int64_t var1; + int64_t var2; + int64_t var3; + int16_t calc_temp; + + /*lint -save -e701 -e702 -e704 */ + var1 = ((int32_t)temp_adc >> 3) - ((int32_t)dev->calib.par_t1 << 1); + var2 = (var1 * (int32_t)dev->calib.par_t2) >> 11; + var3 = ((var1 >> 1) * (var1 >> 1)) >> 12; + var3 = ((var3) * ((int32_t)dev->calib.par_t3 << 4)) >> 14; + dev->calib.t_fine = (int32_t)(var2 + var3); + calc_temp = (int16_t)(((dev->calib.t_fine * 5) + 128) >> 8); + + /*lint -restore */ + return calc_temp; +} + +/* @brief This internal API is used to calculate the pressure value. */ +static uint32_t calc_pressure(uint32_t pres_adc, const struct bme68x_dev *dev) +{ + int32_t var1; + int32_t var2; + int32_t var3; + int32_t pressure_comp; + + /* This value is used to check precedence to multiplication or division + * in the pressure compensation equation to achieve least loss of precision and + * avoiding overflows. + * i.e Comparing value, pres_ovf_check = (1 << 31) >> 1 + */ + const int32_t pres_ovf_check = INT32_C(0x40000000); + + /*lint -save -e701 -e702 -e713 */ + var1 = (((int32_t)dev->calib.t_fine) >> 1) - 64000; + var2 = ((((var1 >> 2) * (var1 >> 2)) >> 11) * (int32_t)dev->calib.par_p6) >> 2; + var2 = var2 + ((var1 * (int32_t)dev->calib.par_p5) << 1); + var2 = (var2 >> 2) + ((int32_t)dev->calib.par_p4 << 16); + var1 = (((((var1 >> 2) * (var1 >> 2)) >> 13) * ((int32_t)dev->calib.par_p3 << 5)) >> 3) + + (((int32_t)dev->calib.par_p2 * var1) >> 1); + var1 = var1 >> 18; + var1 = ((32768 + var1) * (int32_t)dev->calib.par_p1) >> 15; + pressure_comp = 1048576 - pres_adc; + pressure_comp = (int32_t)((pressure_comp - (var2 >> 12)) * ((uint32_t)3125)); + if (pressure_comp >= pres_ovf_check) + { + pressure_comp = ((pressure_comp / var1) << 1); + } + else + { + pressure_comp = ((pressure_comp << 1) / var1); + } + + var1 = ((int32_t)dev->calib.par_p9 * (int32_t)(((pressure_comp >> 3) * (pressure_comp >> 3)) >> 13)) >> 12; + var2 = ((int32_t)(pressure_comp >> 2) * (int32_t)dev->calib.par_p8) >> 13; + var3 = + ((int32_t)(pressure_comp >> 8) * (int32_t)(pressure_comp >> 8) * (int32_t)(pressure_comp >> 8) * + (int32_t)dev->calib.par_p10) >> 17; + pressure_comp = (int32_t)(pressure_comp) + ((var1 + var2 + var3 + ((int32_t)dev->calib.par_p7 << 7)) >> 4); + + /*lint -restore */ + return (uint32_t)pressure_comp; +} + +/* This internal API is used to calculate the humidity in integer */ +static uint32_t calc_humidity(uint16_t hum_adc, const struct bme68x_dev *dev) +{ + int32_t var1; + int32_t var2; + int32_t var3; + int32_t var4; + int32_t var5; + int32_t var6; + int32_t temp_scaled; + int32_t calc_hum; + + /*lint -save -e702 -e704 */ + temp_scaled = (((int32_t)dev->calib.t_fine * 5) + 128) >> 8; + var1 = (int32_t)(hum_adc - ((int32_t)((int32_t)dev->calib.par_h1 * 16))) - + (((temp_scaled * (int32_t)dev->calib.par_h3) / ((int32_t)100)) >> 1); + var2 = + ((int32_t)dev->calib.par_h2 * + (((temp_scaled * (int32_t)dev->calib.par_h4) / ((int32_t)100)) + + (((temp_scaled * ((temp_scaled * (int32_t)dev->calib.par_h5) / ((int32_t)100))) >> 6) / ((int32_t)100)) + + (int32_t)(1 << 14))) >> 10; + var3 = var1 * var2; + var4 = (int32_t)dev->calib.par_h6 << 7; + var4 = ((var4) + ((temp_scaled * (int32_t)dev->calib.par_h7) / ((int32_t)100))) >> 4; + var5 = ((var3 >> 14) * (var3 >> 14)) >> 10; + var6 = (var4 * var5) >> 1; + calc_hum = (((var3 + var6) >> 10) * ((int32_t)1000)) >> 12; + if (calc_hum > 100000) /* Cap at 100%rH */ + { + calc_hum = 100000; + } + else if (calc_hum < 0) + { + calc_hum = 0; + } + + /*lint -restore */ + return (uint32_t)calc_hum; +} + +/* This internal API is used to calculate the gas resistance low */ +static uint32_t calc_gas_resistance_low(uint16_t gas_res_adc, uint8_t gas_range, const struct bme68x_dev *dev) +{ + int64_t var1; + uint64_t var2; + int64_t var3; + uint32_t calc_gas_res; + uint32_t lookup_table1[16] = { + UINT32_C(2147483647), UINT32_C(2147483647), UINT32_C(2147483647), UINT32_C(2147483647), UINT32_C(2147483647), + UINT32_C(2126008810), UINT32_C(2147483647), UINT32_C(2130303777), UINT32_C(2147483647), UINT32_C(2147483647), + UINT32_C(2143188679), UINT32_C(2136746228), UINT32_C(2147483647), UINT32_C(2126008810), UINT32_C(2147483647), + UINT32_C(2147483647) + }; + uint32_t lookup_table2[16] = { + UINT32_C(4096000000), UINT32_C(2048000000), UINT32_C(1024000000), UINT32_C(512000000), UINT32_C(255744255), + UINT32_C(127110228), UINT32_C(64000000), UINT32_C(32258064), UINT32_C(16016016), UINT32_C(8000000), UINT32_C( + 4000000), UINT32_C(2000000), UINT32_C(1000000), UINT32_C(500000), UINT32_C(250000), UINT32_C(125000) + }; + + /*lint -save -e704 */ + var1 = (int64_t)((1340 + (5 * (int64_t)dev->calib.range_sw_err)) * ((int64_t)lookup_table1[gas_range])) >> 16; + var2 = (((int64_t)((int64_t)gas_res_adc << 15) - (int64_t)(16777216)) + var1); + var3 = (((int64_t)lookup_table2[gas_range] * (int64_t)var1) >> 9); + calc_gas_res = (uint32_t)((var3 + ((int64_t)var2 >> 1)) / (int64_t)var2); + + /*lint -restore */ + return calc_gas_res; +} + +/* This internal API is used to calculate the gas resistance */ +static uint32_t calc_gas_resistance_high(uint16_t gas_res_adc, uint8_t gas_range) +{ + uint32_t calc_gas_res; + uint32_t var1 = UINT32_C(262144) >> gas_range; + int32_t var2 = (int32_t)gas_res_adc - INT32_C(512); + + var2 *= INT32_C(3); + var2 = INT32_C(4096) + var2; + + /* multiplying 10000 then dividing then multiplying by 100 instead of multiplying by 1000000 to prevent overflow */ + calc_gas_res = (UINT32_C(10000) * var1) / (uint32_t)var2; + calc_gas_res = calc_gas_res * 100; + + return calc_gas_res; +} + +/* This internal API is used to calculate the heater resistance value using float */ +static uint8_t calc_res_heat(uint16_t temp, const struct bme68x_dev *dev) +{ + uint8_t heatr_res; + int32_t var1; + int32_t var2; + int32_t var3; + int32_t var4; + int32_t var5; + int32_t heatr_res_x100; + + if (temp > 400) /* Cap temperature */ + { + temp = 400; + } + + var1 = (((int32_t)dev->amb_temp * dev->calib.par_gh3) / 1000) * 256; + var2 = (dev->calib.par_gh1 + 784) * (((((dev->calib.par_gh2 + 154009) * temp * 5) / 100) + 3276800) / 10); + var3 = var1 + (var2 / 2); + var4 = (var3 / (dev->calib.res_heat_range + 4)); + var5 = (131 * dev->calib.res_heat_val) + 65536; + heatr_res_x100 = (int32_t)(((var4 / var5) - 250) * 34); + heatr_res = (uint8_t)((heatr_res_x100 + 50) / 100); + + return heatr_res; +} + +#else + +/* @brief This internal API is used to calculate the temperature value. */ +static float calc_temperature(uint32_t temp_adc, struct bme68x_dev *dev) +{ + float var1; + float var2; + float calc_temp; + + /* calculate var1 data */ + var1 = ((((float)temp_adc / 16384.0f) - ((float)dev->calib.par_t1 / 1024.0f)) * ((float)dev->calib.par_t2)); + + /* calculate var2 data */ + var2 = + (((((float)temp_adc / 131072.0f) - ((float)dev->calib.par_t1 / 8192.0f)) * + (((float)temp_adc / 131072.0f) - ((float)dev->calib.par_t1 / 8192.0f))) * ((float)dev->calib.par_t3 * 16.0f)); + + /* t_fine value*/ + dev->calib.t_fine = (var1 + var2); + + /* compensated temperature data*/ + calc_temp = ((dev->calib.t_fine) / 5120.0f); + + return calc_temp; +} + +/* @brief This internal API is used to calculate the pressure value. */ +static float calc_pressure(uint32_t pres_adc, const struct bme68x_dev *dev) +{ + float var1; + float var2; + float var3; + float calc_pres; + + var1 = (((float)dev->calib.t_fine / 2.0f) - 64000.0f); + var2 = var1 * var1 * (((float)dev->calib.par_p6) / (131072.0f)); + var2 = var2 + (var1 * ((float)dev->calib.par_p5) * 2.0f); + var2 = (var2 / 4.0f) + (((float)dev->calib.par_p4) * 65536.0f); + var1 = (((((float)dev->calib.par_p3 * var1 * var1) / 16384.0f) + ((float)dev->calib.par_p2 * var1)) / 524288.0f); + var1 = ((1.0f + (var1 / 32768.0f)) * ((float)dev->calib.par_p1)); + calc_pres = (1048576.0f - ((float)pres_adc)); + + /* Avoid exception caused by division by zero */ + if ((int)var1 != 0) + { + calc_pres = (((calc_pres - (var2 / 4096.0f)) * 6250.0f) / var1); + var1 = (((float)dev->calib.par_p9) * calc_pres * calc_pres) / 2147483648.0f; + var2 = calc_pres * (((float)dev->calib.par_p8) / 32768.0f); + var3 = ((calc_pres / 256.0f) * (calc_pres / 256.0f) * (calc_pres / 256.0f) * (dev->calib.par_p10 / 131072.0f)); + calc_pres = (calc_pres + (var1 + var2 + var3 + ((float)dev->calib.par_p7 * 128.0f)) / 16.0f); + } + else + { + calc_pres = 0; + } + + return calc_pres; +} + +/* This internal API is used to calculate the humidity in integer */ +static float calc_humidity(uint16_t hum_adc, const struct bme68x_dev *dev) +{ + float calc_hum; + float var1; + float var2; + float var3; + float var4; + float temp_comp; + + /* compensated temperature data*/ + temp_comp = ((dev->calib.t_fine) / 5120.0f); + var1 = (float)((float)hum_adc) - + (((float)dev->calib.par_h1 * 16.0f) + (((float)dev->calib.par_h3 / 2.0f) * temp_comp)); + var2 = var1 * + ((float)(((float)dev->calib.par_h2 / 262144.0f) * + (1.0f + (((float)dev->calib.par_h4 / 16384.0f) * temp_comp) + + (((float)dev->calib.par_h5 / 1048576.0f) * temp_comp * temp_comp)))); + var3 = (float)dev->calib.par_h6 / 16384.0f; + var4 = (float)dev->calib.par_h7 / 2097152.0f; + calc_hum = var2 + ((var3 + (var4 * temp_comp)) * var2 * var2); + if (calc_hum > 100.0f) + { + calc_hum = 100.0f; + } + else if (calc_hum < 0.0f) + { + calc_hum = 0.0f; + } + + return calc_hum; +} + +/* This internal API is used to calculate the gas resistance low value in float */ +static float calc_gas_resistance_low(uint16_t gas_res_adc, uint8_t gas_range, const struct bme68x_dev *dev) +{ + float calc_gas_res; + float var1; + float var2; + float var3; + float gas_res_f = gas_res_adc; + float gas_range_f = (1U << gas_range); /*lint !e790 / Suspicious truncation, integral to float */ + const float lookup_k1_range[16] = { + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, -0.8f, 0.0f, 0.0f, -0.2f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f + }; + const float lookup_k2_range[16] = { + 0.0f, 0.0f, 0.0f, 0.0f, 0.1f, 0.7f, 0.0f, -0.8f, -0.1f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f + }; + + var1 = (1340.0f + (5.0f * dev->calib.range_sw_err)); + var2 = (var1) * (1.0f + lookup_k1_range[gas_range] / 100.0f); + var3 = 1.0f + (lookup_k2_range[gas_range] / 100.0f); + calc_gas_res = 1.0f / (float)(var3 * (0.000000125f) * gas_range_f * (((gas_res_f - 512.0f) / var2) + 1.0f)); + + return calc_gas_res; +} + +/* This internal API is used to calculate the gas resistance value in float */ +static float calc_gas_resistance_high(uint16_t gas_res_adc, uint8_t gas_range) +{ + float calc_gas_res; + uint32_t var1 = UINT32_C(262144) >> gas_range; + int32_t var2 = (int32_t)gas_res_adc - INT32_C(512); + + var2 *= INT32_C(3); + var2 = INT32_C(4096) + var2; + + calc_gas_res = 1000000.0f * (float)var1 / (float)var2; + + return calc_gas_res; +} + +/* This internal API is used to calculate the heater resistance value */ +static uint8_t calc_res_heat(uint16_t temp, const struct bme68x_dev *dev) +{ + float var1; + float var2; + float var3; + float var4; + float var5; + uint8_t res_heat; + + if (temp > 400) /* Cap temperature */ + { + temp = 400; + } + + var1 = (((float)dev->calib.par_gh1 / (16.0f)) + 49.0f); + var2 = ((((float)dev->calib.par_gh2 / (32768.0f)) * (0.0005f)) + 0.00235f); + var3 = ((float)dev->calib.par_gh3 / (1024.0f)); + var4 = (var1 * (1.0f + (var2 * (float)temp))); + var5 = (var4 + (var3 * (float)dev->amb_temp)); + res_heat = + (uint8_t)(3.4f * + ((var5 * (4 / (4 + (float)dev->calib.res_heat_range)) * + (1 / (1 + ((float)dev->calib.res_heat_val * 0.002f)))) - + 25)); + + return res_heat; +} + +#endif + +/* This internal API is used to calculate the gas wait */ +static uint8_t calc_gas_wait(uint16_t dur) +{ + uint8_t factor = 0; + uint8_t durval; + + if (dur >= 0xfc0) + { + durval = 0xff; /* Max duration*/ + } + else + { + while (dur > 0x3F) + { + dur = dur / 4; + factor += 1; + } + + durval = (uint8_t)(dur + (factor * 64)); + } + + return durval; +} + +/* This internal API is used to read a single data of the sensor */ +static int8_t read_field_data(uint8_t index, struct bme68x_data *data, struct bme68x_dev *dev) +{ + int8_t rslt = BME68X_OK; + uint8_t buff[BME68X_LEN_FIELD] = { 0 }; + uint8_t gas_range_l, gas_range_h; + uint32_t adc_temp; + uint32_t adc_pres; + uint16_t adc_hum; + uint16_t adc_gas_res_low, adc_gas_res_high; + uint8_t tries = 5; + + while ((tries) && (rslt == BME68X_OK)) + { + rslt = bme68x_get_regs(((uint8_t)(BME68X_REG_FIELD0 + (index * BME68X_LEN_FIELD_OFFSET))), + buff, + (uint16_t)BME68X_LEN_FIELD, + dev); + if (!data) + { + rslt = BME68X_E_NULL_PTR; + break; + } + + data->status = buff[0] & BME68X_NEW_DATA_MSK; + data->gas_index = buff[0] & BME68X_GAS_INDEX_MSK; + data->meas_index = buff[1]; + + /* read the raw data from the sensor */ + adc_pres = (uint32_t)(((uint32_t)buff[2] * 4096) | ((uint32_t)buff[3] * 16) | ((uint32_t)buff[4] / 16)); + adc_temp = (uint32_t)(((uint32_t)buff[5] * 4096) | ((uint32_t)buff[6] * 16) | ((uint32_t)buff[7] / 16)); + adc_hum = (uint16_t)(((uint32_t)buff[8] * 256) | (uint32_t)buff[9]); + adc_gas_res_low = (uint16_t)((uint32_t)buff[13] * 4 | (((uint32_t)buff[14]) / 64)); + adc_gas_res_high = (uint16_t)((uint32_t)buff[15] * 4 | (((uint32_t)buff[16]) / 64)); + gas_range_l = buff[14] & BME68X_GAS_RANGE_MSK; + gas_range_h = buff[16] & BME68X_GAS_RANGE_MSK; + if (dev->variant_id == BME68X_VARIANT_GAS_HIGH) + { + data->status |= buff[16] & BME68X_GASM_VALID_MSK; + data->status |= buff[16] & BME68X_HEAT_STAB_MSK; + } + else + { + data->status |= buff[14] & BME68X_GASM_VALID_MSK; + data->status |= buff[14] & BME68X_HEAT_STAB_MSK; + } + + if ((data->status & BME68X_NEW_DATA_MSK) && (rslt == BME68X_OK)) + { + rslt = bme68x_get_regs(BME68X_REG_RES_HEAT0 + data->gas_index, &data->res_heat, 1, dev); + if (rslt == BME68X_OK) + { + rslt = bme68x_get_regs(BME68X_REG_IDAC_HEAT0 + data->gas_index, &data->idac, 1, dev); + } + + if (rslt == BME68X_OK) + { + rslt = bme68x_get_regs(BME68X_REG_GAS_WAIT0 + data->gas_index, &data->gas_wait, 1, dev); + } + + if (rslt == BME68X_OK) + { + data->temperature = calc_temperature(adc_temp, dev); + data->pressure = calc_pressure(adc_pres, dev); + data->humidity = calc_humidity(adc_hum, dev); + if (dev->variant_id == BME68X_VARIANT_GAS_HIGH) + { + data->gas_resistance = calc_gas_resistance_high(adc_gas_res_high, gas_range_h); + } + else + { + data->gas_resistance = calc_gas_resistance_low(adc_gas_res_low, gas_range_l, dev); + } + + break; + } + } + + if (rslt == BME68X_OK) + { + dev->delay_us(BME68X_PERIOD_POLL, dev->intf_ptr); + } + + tries--; + } + + return rslt; +} + +/* This internal API is used to read all data fields of the sensor */ +static int8_t read_all_field_data(struct bme68x_data * const data[], struct bme68x_dev *dev) +{ + int8_t rslt = BME68X_OK; + uint8_t buff[BME68X_LEN_FIELD * 3] = { 0 }; + uint8_t gas_range_l, gas_range_h; + uint32_t adc_temp; + uint32_t adc_pres; + uint16_t adc_hum; + uint16_t adc_gas_res_low, adc_gas_res_high; + uint8_t off; + uint8_t set_val[30] = { 0 }; /* idac, res_heat, gas_wait */ + uint8_t i; + + if (!data[0] && !data[1] && !data[2]) + { + rslt = BME68X_E_NULL_PTR; + } + + if (rslt == BME68X_OK) + { + rslt = bme68x_get_regs(BME68X_REG_FIELD0, buff, (uint32_t) BME68X_LEN_FIELD * 3, dev); + } + + if (rslt == BME68X_OK) + { + rslt = bme68x_get_regs(BME68X_REG_IDAC_HEAT0, set_val, 30, dev); + } + + for (i = 0; ((i < 3) && (rslt == BME68X_OK)); i++) + { + off = (uint8_t)(i * BME68X_LEN_FIELD); + data[i]->status = buff[off] & BME68X_NEW_DATA_MSK; + data[i]->gas_index = buff[off] & BME68X_GAS_INDEX_MSK; + data[i]->meas_index = buff[off + 1]; + + /* read the raw data from the sensor */ + adc_pres = + (uint32_t) (((uint32_t) buff[off + 2] * 4096) | ((uint32_t) buff[off + 3] * 16) | + ((uint32_t) buff[off + 4] / 16)); + adc_temp = + (uint32_t) (((uint32_t) buff[off + 5] * 4096) | ((uint32_t) buff[off + 6] * 16) | + ((uint32_t) buff[off + 7] / 16)); + adc_hum = (uint16_t) (((uint32_t) buff[off + 8] * 256) | (uint32_t) buff[off + 9]); + adc_gas_res_low = (uint16_t) ((uint32_t) buff[off + 13] * 4 | (((uint32_t) buff[off + 14]) / 64)); + adc_gas_res_high = (uint16_t) ((uint32_t) buff[off + 15] * 4 | (((uint32_t) buff[off + 16]) / 64)); + gas_range_l = buff[off + 14] & BME68X_GAS_RANGE_MSK; + gas_range_h = buff[off + 16] & BME68X_GAS_RANGE_MSK; + if (dev->variant_id == BME68X_VARIANT_GAS_HIGH) + { + data[i]->status |= buff[off + 16] & BME68X_GASM_VALID_MSK; + data[i]->status |= buff[off + 16] & BME68X_HEAT_STAB_MSK; + } + else + { + data[i]->status |= buff[off + 14] & BME68X_GASM_VALID_MSK; + data[i]->status |= buff[off + 14] & BME68X_HEAT_STAB_MSK; + } + + data[i]->idac = set_val[data[i]->gas_index]; + data[i]->res_heat = set_val[10 + data[i]->gas_index]; + data[i]->gas_wait = set_val[20 + data[i]->gas_index]; + data[i]->temperature = calc_temperature(adc_temp, dev); + data[i]->pressure = calc_pressure(adc_pres, dev); + data[i]->humidity = calc_humidity(adc_hum, dev); + if (dev->variant_id == BME68X_VARIANT_GAS_HIGH) + { + data[i]->gas_resistance = calc_gas_resistance_high(adc_gas_res_high, gas_range_h); + } + else + { + data[i]->gas_resistance = calc_gas_resistance_low(adc_gas_res_low, gas_range_l, dev); + } + } + + return rslt; +} + +/* This internal API is used to switch between SPI memory pages */ +static int8_t set_mem_page(uint8_t reg_addr, struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t reg; + uint8_t mem_page; + + /* Check for null pointers in the device structure*/ + rslt = null_ptr_check(dev); + if (rslt == BME68X_OK) + { + if (reg_addr > 0x7f) + { + mem_page = BME68X_MEM_PAGE1; + } + else + { + mem_page = BME68X_MEM_PAGE0; + } + + if (mem_page != dev->mem_page) + { + dev->mem_page = mem_page; + dev->intf_rslt = dev->read(BME68X_REG_MEM_PAGE | BME68X_SPI_RD_MSK, ®, 1, dev->intf_ptr); + if (dev->intf_rslt != 0) + { + rslt = BME68X_E_COM_FAIL; + } + + if (rslt == BME68X_OK) + { + reg = reg & (~BME68X_MEM_PAGE_MSK); + reg = reg | (dev->mem_page & BME68X_MEM_PAGE_MSK); + dev->intf_rslt = dev->write(BME68X_REG_MEM_PAGE & BME68X_SPI_WR_MSK, ®, 1, dev->intf_ptr); + if (dev->intf_rslt != 0) + { + rslt = BME68X_E_COM_FAIL; + } + } + } + } + + return rslt; +} + +/* This internal API is used to get the current SPI memory page */ +static int8_t get_mem_page(struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t reg; + + /* Check for null pointer in the device structure*/ + rslt = null_ptr_check(dev); + if (rslt == BME68X_OK) + { + dev->intf_rslt = dev->read(BME68X_REG_MEM_PAGE | BME68X_SPI_RD_MSK, ®, 1, dev->intf_ptr); + if (dev->intf_rslt != 0) + { + rslt = BME68X_E_COM_FAIL; + } + else + { + dev->mem_page = reg & BME68X_MEM_PAGE_MSK; + } + } + + return rslt; +} + +/* This internal API is used to limit the max value of a parameter */ +static int8_t boundary_check(uint8_t *value, uint8_t max, struct bme68x_dev *dev) +{ + int8_t rslt; + + rslt = null_ptr_check(dev); + if ((value != NULL) && (rslt == BME68X_OK)) + { + /* Check if value is above maximum value */ + if (*value > max) + { + /* Auto correct the invalid value to maximum value */ + *value = max; + dev->info_msg |= BME68X_I_PARAM_CORR; + } + } + else + { + rslt = BME68X_E_NULL_PTR; + } + + return rslt; +} + +/* This internal API is used to check the bme68x_dev for null pointers */ +static int8_t null_ptr_check(const struct bme68x_dev *dev) +{ + int8_t rslt = BME68X_OK; + + if ((dev == NULL) || (dev->read == NULL) || (dev->write == NULL) || (dev->delay_us == NULL)) + { + /* Device structure pointer is not valid */ + rslt = BME68X_E_NULL_PTR; + } + + return rslt; +} + +/* This internal API is used to set heater configurations */ +static int8_t set_conf(const struct bme68x_heatr_conf *conf, uint8_t op_mode, uint8_t *nb_conv, struct bme68x_dev *dev) +{ + int8_t rslt = BME68X_OK; + uint8_t i; + uint8_t shared_dur; + uint8_t write_len = 0; + uint8_t heater_dur_shared_addr = BME68X_REG_SHD_HEATR_DUR; + uint8_t rh_reg_addr[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + uint8_t rh_reg_data[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + uint8_t gw_reg_addr[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + uint8_t gw_reg_data[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + + switch (op_mode) + { + case BME68X_FORCED_MODE: + rh_reg_addr[0] = BME68X_REG_RES_HEAT0; + rh_reg_data[0] = calc_res_heat(conf->heatr_temp, dev); + gw_reg_addr[0] = BME68X_REG_GAS_WAIT0; + gw_reg_data[0] = calc_gas_wait(conf->heatr_dur); + (*nb_conv) = 0; + write_len = 1; + break; + case BME68X_SEQUENTIAL_MODE: + if ((!conf->heatr_dur_prof) || (!conf->heatr_temp_prof)) + { + rslt = BME68X_E_NULL_PTR; + break; + } + + for (i = 0; i < conf->profile_len; i++) + { + rh_reg_addr[i] = BME68X_REG_RES_HEAT0 + i; + rh_reg_data[i] = calc_res_heat(conf->heatr_temp_prof[i], dev); + gw_reg_addr[i] = BME68X_REG_GAS_WAIT0 + i; + gw_reg_data[i] = calc_gas_wait(conf->heatr_dur_prof[i]); + } + + (*nb_conv) = conf->profile_len; + write_len = conf->profile_len; + break; + case BME68X_PARALLEL_MODE: + if ((!conf->heatr_dur_prof) || (!conf->heatr_temp_prof)) + { + rslt = BME68X_E_NULL_PTR; + break; + } + + if (conf->shared_heatr_dur == 0) + { + rslt = BME68X_W_DEFINE_SHD_HEATR_DUR; + } + + for (i = 0; i < conf->profile_len; i++) + { + rh_reg_addr[i] = BME68X_REG_RES_HEAT0 + i; + rh_reg_data[i] = calc_res_heat(conf->heatr_temp_prof[i], dev); + gw_reg_addr[i] = BME68X_REG_GAS_WAIT0 + i; + gw_reg_data[i] = (uint8_t) conf->heatr_dur_prof[i]; + } + + (*nb_conv) = conf->profile_len; + write_len = conf->profile_len; + shared_dur = calc_heatr_dur_shared(conf->shared_heatr_dur); + if (rslt == BME68X_OK) + { + rslt = bme68x_set_regs(&heater_dur_shared_addr, &shared_dur, 1, dev); + } + + break; + default: + rslt = BME68X_W_DEFINE_OP_MODE; + } + + if (rslt == BME68X_OK) + { + rslt = bme68x_set_regs(rh_reg_addr, rh_reg_data, write_len, dev); + } + + if (rslt == BME68X_OK) + { + rslt = bme68x_set_regs(gw_reg_addr, gw_reg_data, write_len, dev); + } + + return rslt; +} + +/* This internal API is used to calculate the register value for + * shared heater duration */ +static uint8_t calc_heatr_dur_shared(uint16_t dur) +{ + uint8_t factor = 0; + uint8_t heatdurval; + + if (dur >= 0x783) + { + heatdurval = 0xff; /* Max duration */ + } + else + { + /* Step size of 0.477ms */ + dur = (uint16_t)(((uint32_t)dur * 1000) / 477); + while (dur > 0x3F) + { + dur = dur >> 2; + factor += 1; + } + + heatdurval = (uint8_t)(dur + (factor * 64)); + } + + return heatdurval; +} + +/* This internal API is used sort the sensor data */ +static void sort_sensor_data(uint8_t low_index, uint8_t high_index, struct bme68x_data *field[]) +{ + int16_t meas_index1; + int16_t meas_index2; + + meas_index1 = (int16_t)field[low_index]->meas_index; + meas_index2 = (int16_t)field[high_index]->meas_index; + if ((field[low_index]->status & BME68X_NEW_DATA_MSK) && (field[high_index]->status & BME68X_NEW_DATA_MSK)) + { + int16_t diff = meas_index2 - meas_index1; + if (((diff > -3) && (diff < 0)) || (diff > 2)) + { + swap_fields(low_index, high_index, field); + } + } + else if (field[high_index]->status & BME68X_NEW_DATA_MSK) + { + swap_fields(low_index, high_index, field); + } + + /* Sorting field data + * + * The 3 fields are filled in a fixed order with data in an incrementing + * 8-bit sub-measurement index which looks like + * Field index | Sub-meas index + * 0 | 0 + * 1 | 1 + * 2 | 2 + * 0 | 3 + * 1 | 4 + * 2 | 5 + * ... + * 0 | 252 + * 1 | 253 + * 2 | 254 + * 0 | 255 + * 1 | 0 + * 2 | 1 + * + * The fields are sorted in a way so as to always deal with only a snapshot + * of comparing 2 fields at a time. The order being + * field0 & field1 + * field0 & field2 + * field1 & field2 + * Here the oldest data should be in field0 while the newest is in field2. + * In the following documentation, field0's position would referred to as + * the lowest and field2 as the highest. + * + * In order to sort we have to consider the following cases, + * + * Case A: No fields have new data + * Then do not sort, as this data has already been read. + * + * Case B: Higher field has new data + * Then the new field get's the lowest position. + * + * Case C: Both fields have new data + * We have to put the oldest sample in the lowest position. Since the + * sub-meas index contains in essence the age of the sample, we calculate + * the difference between the higher field and the lower field. + * Here we have 3 sub-cases, + * Case 1: Regular read without overwrite + * Field index | Sub-meas index + * 0 | 3 + * 1 | 4 + * + * Field index | Sub-meas index + * 0 | 3 + * 2 | 5 + * + * The difference is always <= 2. There is no need to swap as the + * oldest sample is already in the lowest position. + * + * Case 2: Regular read with an overflow and without an overwrite + * Field index | Sub-meas index + * 0 | 255 + * 1 | 0 + * + * Field index | Sub-meas index + * 0 | 254 + * 2 | 0 + * + * The difference is always <= -3. There is no need to swap as the + * oldest sample is already in the lowest position. + * + * Case 3: Regular read with overwrite + * Field index | Sub-meas index + * 0 | 6 + * 1 | 4 + * + * Field index | Sub-meas index + * 0 | 6 + * 2 | 5 + * + * The difference is always > -3. There is a need to swap as the + * oldest sample is not in the lowest position. + * + * Case 4: Regular read with overwrite and overflow + * Field index | Sub-meas index + * 0 | 0 + * 1 | 254 + * + * Field index | Sub-meas index + * 0 | 0 + * 2 | 255 + * + * The difference is always > 2. There is a need to swap as the + * oldest sample is not in the lowest position. + * + * To summarize, we have to swap when + * - The higher field has new data and the lower field does not. + * - If both fields have new data, then the difference of sub-meas index + * between the higher field and the lower field creates the + * following condition for swapping. + * - (diff > -3) && (diff < 0), combination of cases 1, 2, and 3. + * - diff > 2, case 4. + * + * Here the limits of -3 and 2 derive from the fact that there are 3 fields. + * These values decrease or increase respectively if the number of fields increases. + */ +} + +/* This internal API is used sort the sensor data */ +static void swap_fields(uint8_t index1, uint8_t index2, struct bme68x_data *field[]) +{ + struct bme68x_data *temp; + + temp = field[index1]; + field[index1] = field[index2]; + field[index2] = temp; +} + +/* This Function is to analyze the sensor data */ +static int8_t analyze_sensor_data(const struct bme68x_data *data, uint8_t n_meas) +{ + int8_t rslt = BME68X_OK; + uint8_t self_test_failed = 0, i; + uint32_t cent_res = 0; + + if ((data[0].temperature < BME68X_MIN_TEMPERATURE) || (data[0].temperature > BME68X_MAX_TEMPERATURE)) + { + self_test_failed++; + } + + if ((data[0].pressure < BME68X_MIN_PRESSURE) || (data[0].pressure > BME68X_MAX_PRESSURE)) + { + self_test_failed++; + } + + if ((data[0].humidity < BME68X_MIN_HUMIDITY) || (data[0].humidity > BME68X_MAX_HUMIDITY)) + { + self_test_failed++; + } + + for (i = 0; i < n_meas; i++) /* Every gas measurement should be valid */ + { + if (!(data[i].status & BME68X_GASM_VALID_MSK)) + { + self_test_failed++; + } + } + + if (n_meas >= 6) + { + cent_res = (uint32_t)((5 * (data[3].gas_resistance + data[5].gas_resistance)) / (2 * data[4].gas_resistance)); + } + + if (cent_res < 6) + { + self_test_failed++; + } + + if (self_test_failed) + { + rslt = BME68X_E_SELF_TEST; + } + + return rslt; +} + +/* This internal API is used to read the calibration coefficients */ +static int8_t get_calib_data(struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t coeff_array[BME68X_LEN_COEFF_ALL]; + + rslt = bme68x_get_regs(BME68X_REG_COEFF1, coeff_array, BME68X_LEN_COEFF1, dev); + if (rslt == BME68X_OK) + { + rslt = bme68x_get_regs(BME68X_REG_COEFF2, &coeff_array[BME68X_LEN_COEFF1], BME68X_LEN_COEFF2, dev); + } + + if (rslt == BME68X_OK) + { + rslt = bme68x_get_regs(BME68X_REG_COEFF3, + &coeff_array[BME68X_LEN_COEFF1 + BME68X_LEN_COEFF2], + BME68X_LEN_COEFF3, + dev); + } + + if (rslt == BME68X_OK) + { + /* Temperature related coefficients */ + dev->calib.par_t1 = + (uint16_t)(BME68X_CONCAT_BYTES(coeff_array[BME68X_IDX_T1_MSB], coeff_array[BME68X_IDX_T1_LSB])); + dev->calib.par_t2 = + (int16_t)(BME68X_CONCAT_BYTES(coeff_array[BME68X_IDX_T2_MSB], coeff_array[BME68X_IDX_T2_LSB])); + dev->calib.par_t3 = (int8_t)(coeff_array[BME68X_IDX_T3]); + + /* Pressure related coefficients */ + dev->calib.par_p1 = + (uint16_t)(BME68X_CONCAT_BYTES(coeff_array[BME68X_IDX_P1_MSB], coeff_array[BME68X_IDX_P1_LSB])); + dev->calib.par_p2 = + (int16_t)(BME68X_CONCAT_BYTES(coeff_array[BME68X_IDX_P2_MSB], coeff_array[BME68X_IDX_P2_LSB])); + dev->calib.par_p3 = (int8_t)coeff_array[BME68X_IDX_P3]; + dev->calib.par_p4 = + (int16_t)(BME68X_CONCAT_BYTES(coeff_array[BME68X_IDX_P4_MSB], coeff_array[BME68X_IDX_P4_LSB])); + dev->calib.par_p5 = + (int16_t)(BME68X_CONCAT_BYTES(coeff_array[BME68X_IDX_P5_MSB], coeff_array[BME68X_IDX_P5_LSB])); + dev->calib.par_p6 = (int8_t)(coeff_array[BME68X_IDX_P6]); + dev->calib.par_p7 = (int8_t)(coeff_array[BME68X_IDX_P7]); + dev->calib.par_p8 = + (int16_t)(BME68X_CONCAT_BYTES(coeff_array[BME68X_IDX_P8_MSB], coeff_array[BME68X_IDX_P8_LSB])); + dev->calib.par_p9 = + (int16_t)(BME68X_CONCAT_BYTES(coeff_array[BME68X_IDX_P9_MSB], coeff_array[BME68X_IDX_P9_LSB])); + dev->calib.par_p10 = (uint8_t)(coeff_array[BME68X_IDX_P10]); + + /* Humidity related coefficients */ + dev->calib.par_h1 = + (uint16_t)(((uint16_t)coeff_array[BME68X_IDX_H1_MSB] << 4) | + (coeff_array[BME68X_IDX_H1_LSB] & BME68X_BIT_H1_DATA_MSK)); + dev->calib.par_h2 = + (uint16_t)(((uint16_t)coeff_array[BME68X_IDX_H2_MSB] << 4) | ((coeff_array[BME68X_IDX_H2_LSB]) >> 4)); + dev->calib.par_h3 = (int8_t)coeff_array[BME68X_IDX_H3]; + dev->calib.par_h4 = (int8_t)coeff_array[BME68X_IDX_H4]; + dev->calib.par_h5 = (int8_t)coeff_array[BME68X_IDX_H5]; + dev->calib.par_h6 = (uint8_t)coeff_array[BME68X_IDX_H6]; + dev->calib.par_h7 = (int8_t)coeff_array[BME68X_IDX_H7]; + + /* Gas heater related coefficients */ + dev->calib.par_gh1 = (int8_t)coeff_array[BME68X_IDX_GH1]; + dev->calib.par_gh2 = + (int16_t)(BME68X_CONCAT_BYTES(coeff_array[BME68X_IDX_GH2_MSB], coeff_array[BME68X_IDX_GH2_LSB])); + dev->calib.par_gh3 = (int8_t)coeff_array[BME68X_IDX_GH3]; + + /* Other coefficients */ + dev->calib.res_heat_range = ((coeff_array[BME68X_IDX_RES_HEAT_RANGE] & BME68X_RHRANGE_MSK) / 16); + dev->calib.res_heat_val = (int8_t)coeff_array[BME68X_IDX_RES_HEAT_VAL]; + dev->calib.range_sw_err = ((int8_t)(coeff_array[BME68X_IDX_RANGE_SW_ERR] & BME68X_RSERROR_MSK)) / 16; + } + + return rslt; +} + +/* This internal API is used to read variant ID information from the register */ +static int8_t read_variant_id(struct bme68x_dev *dev) +{ + int8_t rslt; + uint8_t reg_data = 0; + + /* Read variant ID information register */ + rslt = bme68x_get_regs(BME68X_REG_VARIANT_ID, ®_data, 1, dev); + + if (rslt == BME68X_OK) + { + dev->variant_id = reg_data; + } + + return rslt; +} diff --git a/lib/Adafruit_BME680/bme68x.h b/lib/Adafruit_BME680/bme68x.h new file mode 100644 index 000000000..317aa99c0 --- /dev/null +++ b/lib/Adafruit_BME680/bme68x.h @@ -0,0 +1,323 @@ +/** +* Copyright (c) 2021 Bosch Sensortec GmbH. All rights reserved. +* +* BSD-3-Clause +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* +* 3. Neither the name of the copyright holder nor the names of its +* contributors may be used to endorse or promote products derived from +* this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* +* @file bme68x.h +* @date 2021-05-24 +* @version v4.4.6 +* +*/ + +/*! + * @defgroup bme68x BME68X + * @brief Product Overview + * and Sensor API Source Code + */ + +#ifndef BME68X_H_ +#define BME68X_H_ + +#include "bme68x_defs.h" + +/* CPP guard */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \ingroup bme68x + * \defgroup bme68xApiInit Initialization + * @brief Initialize the sensor and device structure + */ + +/*! + * \ingroup bme68xApiInit + * \page bme68x_api_bme68x_init bme68x_init + * \code + * int8_t bme68x_init(struct bme68x_dev *dev); + * \endcode + * @details This API reads the chip-id of the sensor which is the first step to + * verify the sensor and also calibrates the sensor + * As this API is the entry point, call this API before using other APIs. + * + * @param[in,out] dev : Structure instance of bme68x_dev + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_init(struct bme68x_dev *dev); + +/** + * \ingroup bme68x + * \defgroup bme68xApiRegister Registers + * @brief Generic API for accessing sensor registers + */ + +/*! + * \ingroup bme68xApiRegister + * \page bme68x_api_bme68x_set_regs bme68x_set_regs + * \code + * int8_t bme68x_set_regs(const uint8_t reg_addr, const uint8_t *reg_data, uint32_t len, struct bme68x_dev *dev) + * \endcode + * @details This API writes the given data to the register address of the sensor + * + * @param[in] reg_addr : Register addresses to where the data is to be written + * @param[in] reg_data : Pointer to data buffer which is to be written + * in the reg_addr of sensor. + * @param[in] len : No of bytes of data to write + * @param[in,out] dev : Structure instance of bme68x_dev + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_set_regs(const uint8_t *reg_addr, const uint8_t *reg_data, uint32_t len, struct bme68x_dev *dev); + +/*! + * \ingroup bme68xApiRegister + * \page bme68x_api_bme68x_get_regs bme68x_get_regs + * \code + * int8_t bme68x_get_regs(uint8_t reg_addr, uint8_t *reg_data, uint32_t len, struct bme68x_dev *dev) + * \endcode + * @details This API reads the data from the given register address of sensor. + * + * @param[in] reg_addr : Register address from where the data to be read + * @param[out] reg_data : Pointer to data buffer to store the read data. + * @param[in] len : No of bytes of data to be read. + * @param[in,out] dev : Structure instance of bme68x_dev. + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_get_regs(uint8_t reg_addr, uint8_t *reg_data, uint32_t len, struct bme68x_dev *dev); + +/** + * \ingroup bme68x + * \defgroup bme68xApiSystem System + * @brief API that performs system-level operations + */ + +/*! + * \ingroup bme68xApiSystem + * \page bme68x_api_bme68x_soft_reset bme68x_soft_reset + * \code + * int8_t bme68x_soft_reset(struct bme68x_dev *dev); + * \endcode + * @details This API soft-resets the sensor. + * + * @param[in,out] dev : Structure instance of bme68x_dev. + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_soft_reset(struct bme68x_dev *dev); + +/** + * \ingroup bme68x + * \defgroup bme68xApiOm Operation mode + * @brief API to configure operation mode + */ + +/*! + * \ingroup bme68xApiOm + * \page bme68x_api_bme68x_set_op_mode bme68x_set_op_mode + * \code + * int8_t bme68x_set_op_mode(const uint8_t op_mode, struct bme68x_dev *dev); + * \endcode + * @details This API is used to set the operation mode of the sensor + * @param[in] op_mode : Desired operation mode. + * @param[in] dev : Structure instance of bme68x_dev + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_set_op_mode(const uint8_t op_mode, struct bme68x_dev *dev); + +/*! + * \ingroup bme68xApiOm + * \page bme68x_api_bme68x_get_op_mode bme68x_get_op_mode + * \code + * int8_t bme68x_get_op_mode(uint8_t *op_mode, struct bme68x_dev *dev); + * \endcode + * @details This API is used to get the operation mode of the sensor. + * + * @param[out] op_mode : Desired operation mode. + * @param[in,out] dev : Structure instance of bme68x_dev + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_get_op_mode(uint8_t *op_mode, struct bme68x_dev *dev); + +/*! + * \ingroup bme68xApiConfig + * \page bme68x_api_bme68x_get_meas_dur bme68x_get_meas_dur + * \code + * uint32_t bme68x_get_meas_dur(const uint8_t op_mode, struct bme68x_conf *conf, struct bme68x_dev *dev); + * \endcode + * @details This API is used to get the remaining duration that can be used for heating. + * + * @param[in] op_mode : Desired operation mode. + * @param[in] conf : Desired sensor configuration. + * @param[in] dev : Structure instance of bme68x_dev + * + * @return Measurement duration calculated in microseconds + */ +uint32_t bme68x_get_meas_dur(const uint8_t op_mode, struct bme68x_conf *conf, struct bme68x_dev *dev); + +/** + * \ingroup bme68x + * \defgroup bme68xApiData Data Read out + * @brief Read our data from the sensor + */ + +/*! + * \ingroup bme68xApiData + * \page bme68x_api_bme68x_get_data bme68x_get_data + * \code + * int8_t bme68x_get_data(uint8_t op_mode, struct bme68x_data *data, uint8_t *n_data, struct bme68x_dev *dev); + * \endcode + * @details This API reads the pressure, temperature and humidity and gas data + * from the sensor, compensates the data and store it in the bme68x_data + * structure instance passed by the user. + * + * @param[in] op_mode : Expected operation mode. + * @param[out] data : Structure instance to hold the data. + * @param[out] n_data : Number of data instances available. + * @param[in,out] dev : Structure instance of bme68x_dev + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_get_data(uint8_t op_mode, struct bme68x_data *data, uint8_t *n_data, struct bme68x_dev *dev); + +/** + * \ingroup bme68x + * \defgroup bme68xApiConfig Configuration + * @brief Configuration API of sensor + */ + +/*! + * \ingroup bme68xApiConfig + * \page bme68x_api_bme68x_set_conf bme68x_set_conf + * \code + * int8_t bme68x_set_conf(struct bme68x_conf *conf, struct bme68x_dev *dev); + * \endcode + * @details This API is used to set the oversampling, filter and odr configuration + * + * @param[in] conf : Desired sensor configuration. + * @param[in,out] dev : Structure instance of bme68x_dev. + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_set_conf(struct bme68x_conf *conf, struct bme68x_dev *dev); + +/*! + * \ingroup bme68xApiConfig + * \page bme68x_api_bme68x_get_conf bme68x_get_conf + * \code + * int8_t bme68x_get_conf(struct bme68x_conf *conf, struct bme68x_dev *dev); + * \endcode + * @details This API is used to get the oversampling, filter and odr + * configuration + * + * @param[out] conf : Present sensor configuration. + * @param[in,out] dev : Structure instance of bme68x_dev. + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_get_conf(struct bme68x_conf *conf, struct bme68x_dev *dev); + +/*! + * \ingroup bme68xApiConfig + * \page bme68x_api_bme68x_set_heatr_conf bme68x_set_heatr_conf + * \code + * int8_t bme68x_set_heatr_conf(uint8_t op_mode, const struct bme68x_heatr_conf *conf, struct bme68x_dev *dev); + * \endcode + * @details This API is used to set the gas configuration of the sensor. + * + * @param[in] op_mode : Expected operation mode of the sensor. + * @param[in] conf : Desired heating configuration. + * @param[in,out] dev : Structure instance of bme68x_dev. + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_set_heatr_conf(uint8_t op_mode, const struct bme68x_heatr_conf *conf, struct bme68x_dev *dev); + +/*! + * \ingroup bme68xApiConfig + * \page bme68x_api_bme68x_get_heatr_conf bme68x_get_heatr_conf + * \code + * int8_t bme68x_get_heatr_conf(const struct bme68x_heatr_conf *conf, struct bme68x_dev *dev); + * \endcode + * @details This API is used to get the gas configuration of the sensor. + * + * @param[out] conf : Current configurations of the gas sensor. + * @param[in,out] dev : Structure instance of bme68x_dev. + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_get_heatr_conf(const struct bme68x_heatr_conf *conf, struct bme68x_dev *dev); + +/*! + * \ingroup bme68xApiSystem + * \page bme68x_api_bme68x_low_gas_selftest_check bme68x_low_gas_selftest_check + * \code + * int8_t bme68x_low_gas_selftest_check(const struct bme68x_dev *dev); + * \endcode + * @details This API performs Self-test of low gas variant of BME68X + * + * @param[in, out] dev : Structure instance of bme68x_dev + * + * @return Result of API execution status + * @retval 0 -> Success + * @retval < 0 -> Fail + */ +int8_t bme68x_low_gas_selftest_check(const struct bme68x_dev *dev); + +#ifdef __cplusplus +} +#endif /* End of CPP guard */ +#endif /* BME68X_H_ */ diff --git a/lib/Adafruit_BME680/bme68x_defs.h b/lib/Adafruit_BME680/bme68x_defs.h new file mode 100644 index 000000000..56b26ac3c --- /dev/null +++ b/lib/Adafruit_BME680/bme68x_defs.h @@ -0,0 +1,972 @@ +/** +* Copyright (c) 2021 Bosch Sensortec GmbH. All rights reserved. +* +* BSD-3-Clause +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* +* 3. Neither the name of the copyright holder nor the names of its +* contributors may be used to endorse or promote products derived from +* this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* +* @file bme68x_defs.h +* @date 2021-05-24 +* @version v4.4.6 +* +*/ + +/*! @cond DOXYGEN_SUPRESS */ + +#ifndef BME68X_DEFS_H_ +#define BME68X_DEFS_H_ + +/********************************************************* */ +/*! Header includes */ +/********************************************************* */ +#ifdef __KERNEL__ +#include +#include +#else +#include +#include +#endif + +/********************************************************* */ +/*! Common Macros */ +/********************************************************* */ +#ifdef __KERNEL__ +#if !defined(UINT8_C) && !defined(INT8_C) +#define INT8_C(x) S8_C(x) +#define UINT8_C(x) U8_C(x) +#endif + +#if !defined(UINT16_C) && !defined(INT16_C) +#define INT16_C(x) S16_C(x) +#define UINT16_C(x) U16_C(x) +#endif + +#if !defined(INT32_C) && !defined(UINT32_C) +#define INT32_C(x) S32_C(x) +#define UINT32_C(x) U32_C(x) +#endif + +#if !defined(INT64_C) && !defined(UINT64_C) +#define INT64_C(x) S64_C(x) +#define UINT64_C(x) U64_C(x) +#endif +#endif + +/*! C standard macros */ +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *) 0) +#endif +#endif + +#ifndef BME68X_DO_NOT_USE_FPU + +/* Comment or un-comment the macro to provide floating point data output */ +#define BME68X_USE_FPU +#endif + +/* Period between two polls (value can be given by user) */ +#ifndef BME68X_PERIOD_POLL +#define BME68X_PERIOD_POLL UINT32_C(10000) +#endif + +/* BME68X unique chip identifier */ +#define BME68X_CHIP_ID UINT8_C(0x61) + +/* Period for a soft reset */ +#define BME68X_PERIOD_RESET UINT32_C(10000) + +/* BME68X lower I2C address */ +#define BME68X_I2C_ADDR_LOW UINT8_C(0x76) + +/* BME68X higher I2C address */ +#define BME68X_I2C_ADDR_HIGH UINT8_C(0x77) + +/* Soft reset command */ +#define BME68X_SOFT_RESET_CMD UINT8_C(0xb6) + +/* Return code definitions */ +/* Success */ +#define BME68X_OK INT8_C(0) + +/* Errors */ +/* Null pointer passed */ +#define BME68X_E_NULL_PTR INT8_C(-1) + +/* Communication failure */ +#define BME68X_E_COM_FAIL INT8_C(-2) + +/* Sensor not found */ +#define BME68X_E_DEV_NOT_FOUND INT8_C(-3) + +/* Incorrect length parameter */ +#define BME68X_E_INVALID_LENGTH INT8_C(-4) + +/* Self test fail error */ +#define BME68X_E_SELF_TEST INT8_C(-5) + +/* Warnings */ +/* Define a valid operation mode */ +#define BME68X_W_DEFINE_OP_MODE INT8_C(1) + +/* No new data was found */ +#define BME68X_W_NO_NEW_DATA INT8_C(2) + +/* Define the shared heating duration */ +#define BME68X_W_DEFINE_SHD_HEATR_DUR INT8_C(3) + +/* Information - only available via bme68x_dev.info_msg */ +#define BME68X_I_PARAM_CORR UINT8_C(1) + +/* Register map addresses in I2C */ +/* Register for 3rd group of coefficients */ +#define BME68X_REG_COEFF3 UINT8_C(0x00) + +/* 0th Field address*/ +#define BME68X_REG_FIELD0 UINT8_C(0x1d) + +/* 0th Current DAC address*/ +#define BME68X_REG_IDAC_HEAT0 UINT8_C(0x50) + +/* 0th Res heat address */ +#define BME68X_REG_RES_HEAT0 UINT8_C(0x5a) + +/* 0th Gas wait address */ +#define BME68X_REG_GAS_WAIT0 UINT8_C(0x64) + +/* Shared heating duration address */ +#define BME68X_REG_SHD_HEATR_DUR UINT8_C(0x6E) + +/* CTRL_GAS_0 address */ +#define BME68X_REG_CTRL_GAS_0 UINT8_C(0x70) + +/* CTRL_GAS_1 address */ +#define BME68X_REG_CTRL_GAS_1 UINT8_C(0x71) + +/* CTRL_HUM address */ +#define BME68X_REG_CTRL_HUM UINT8_C(0x72) + +/* CTRL_MEAS address */ +#define BME68X_REG_CTRL_MEAS UINT8_C(0x74) + +/* CONFIG address */ +#define BME68X_REG_CONFIG UINT8_C(0x75) + +/* MEM_PAGE address */ +#define BME68X_REG_MEM_PAGE UINT8_C(0xf3) + +/* Unique ID address */ +#define BME68X_REG_UNIQUE_ID UINT8_C(0x83) + +/* Register for 1st group of coefficients */ +#define BME68X_REG_COEFF1 UINT8_C(0x8a) + +/* Chip ID address */ +#define BME68X_REG_CHIP_ID UINT8_C(0xd0) + +/* Soft reset address */ +#define BME68X_REG_SOFT_RESET UINT8_C(0xe0) + +/* Register for 2nd group of coefficients */ +#define BME68X_REG_COEFF2 UINT8_C(0xe1) + +/* Variant ID Register */ +#define BME68X_REG_VARIANT_ID UINT8_C(0xF0) + +/* Enable/Disable macros */ + +/* Enable */ +#define BME68X_ENABLE UINT8_C(0x01) + +/* Disable */ +#define BME68X_DISABLE UINT8_C(0x00) + +/* Variant ID macros */ + +/* Low Gas variant */ +#define BME68X_VARIANT_GAS_LOW UINT8_C(0x00) + +/* High Gas variant */ +#define BME68X_VARIANT_GAS_HIGH UINT8_C(0x01) + +/* Oversampling setting macros */ + +/* Switch off measurement */ +#define BME68X_OS_NONE UINT8_C(0) + +/* Perform 1 measurement */ +#define BME68X_OS_1X UINT8_C(1) + +/* Perform 2 measurements */ +#define BME68X_OS_2X UINT8_C(2) + +/* Perform 4 measurements */ +#define BME68X_OS_4X UINT8_C(3) + +/* Perform 8 measurements */ +#define BME68X_OS_8X UINT8_C(4) + +/* Perform 16 measurements */ +#define BME68X_OS_16X UINT8_C(5) + +/* IIR Filter settings */ + +/* Switch off the filter */ +#define BME68X_FILTER_OFF UINT8_C(0) + +/* Filter coefficient of 2 */ +#define BME68X_FILTER_SIZE_1 UINT8_C(1) + +/* Filter coefficient of 4 */ +#define BME68X_FILTER_SIZE_3 UINT8_C(2) + +/* Filter coefficient of 8 */ +#define BME68X_FILTER_SIZE_7 UINT8_C(3) + +/* Filter coefficient of 16 */ +#define BME68X_FILTER_SIZE_15 UINT8_C(4) + +/* Filter coefficient of 32 */ +#define BME68X_FILTER_SIZE_31 UINT8_C(5) + +/* Filter coefficient of 64 */ +#define BME68X_FILTER_SIZE_63 UINT8_C(6) + +/* Filter coefficient of 128 */ +#define BME68X_FILTER_SIZE_127 UINT8_C(7) + +/* ODR/Standby time macros */ + +/* Standby time of 0.59ms */ +#define BME68X_ODR_0_59_MS UINT8_C(0) + +/* Standby time of 62.5ms */ +#define BME68X_ODR_62_5_MS UINT8_C(1) + +/* Standby time of 125ms */ +#define BME68X_ODR_125_MS UINT8_C(2) + +/* Standby time of 250ms */ +#define BME68X_ODR_250_MS UINT8_C(3) + +/* Standby time of 500ms */ +#define BME68X_ODR_500_MS UINT8_C(4) + +/* Standby time of 1s */ +#define BME68X_ODR_1000_MS UINT8_C(5) + +/* Standby time of 10ms */ +#define BME68X_ODR_10_MS UINT8_C(6) + +/* Standby time of 20ms */ +#define BME68X_ODR_20_MS UINT8_C(7) + +/* No standby time */ +#define BME68X_ODR_NONE UINT8_C(8) + +/* Operating mode macros */ + +/* Sleep operation mode */ +#define BME68X_SLEEP_MODE UINT8_C(0) + +/* Forced operation mode */ +#define BME68X_FORCED_MODE UINT8_C(1) + +/* Parallel operation mode */ +#define BME68X_PARALLEL_MODE UINT8_C(2) + +/* Sequential operation mode */ +#define BME68X_SEQUENTIAL_MODE UINT8_C(3) + +/* SPI page macros */ + +/* SPI memory page 0 */ +#define BME68X_MEM_PAGE0 UINT8_C(0x10) + +/* SPI memory page 1 */ +#define BME68X_MEM_PAGE1 UINT8_C(0x00) + +/* Coefficient index macros */ + +/* Length for all coefficients */ +#define BME68X_LEN_COEFF_ALL UINT8_C(42) + +/* Length for 1st group of coefficients */ +#define BME68X_LEN_COEFF1 UINT8_C(23) + +/* Length for 2nd group of coefficients */ +#define BME68X_LEN_COEFF2 UINT8_C(14) + +/* Length for 3rd group of coefficients */ +#define BME68X_LEN_COEFF3 UINT8_C(5) + +/* Length of the field */ +#define BME68X_LEN_FIELD UINT8_C(17) + +/* Length between two fields */ +#define BME68X_LEN_FIELD_OFFSET UINT8_C(17) + +/* Length of the configuration register */ +#define BME68X_LEN_CONFIG UINT8_C(5) + +/* Length of the interleaved buffer */ +#define BME68X_LEN_INTERLEAVE_BUFF UINT8_C(20) + +/* Coefficient index macros */ + +/* Coefficient T2 LSB position */ +#define BME68X_IDX_T2_LSB (0) + +/* Coefficient T2 MSB position */ +#define BME68X_IDX_T2_MSB (1) + +/* Coefficient T3 position */ +#define BME68X_IDX_T3 (2) + +/* Coefficient P1 LSB position */ +#define BME68X_IDX_P1_LSB (4) + +/* Coefficient P1 MSB position */ +#define BME68X_IDX_P1_MSB (5) + +/* Coefficient P2 LSB position */ +#define BME68X_IDX_P2_LSB (6) + +/* Coefficient P2 MSB position */ +#define BME68X_IDX_P2_MSB (7) + +/* Coefficient P3 position */ +#define BME68X_IDX_P3 (8) + +/* Coefficient P4 LSB position */ +#define BME68X_IDX_P4_LSB (10) + +/* Coefficient P4 MSB position */ +#define BME68X_IDX_P4_MSB (11) + +/* Coefficient P5 LSB position */ +#define BME68X_IDX_P5_LSB (12) + +/* Coefficient P5 MSB position */ +#define BME68X_IDX_P5_MSB (13) + +/* Coefficient P7 position */ +#define BME68X_IDX_P7 (14) + +/* Coefficient P6 position */ +#define BME68X_IDX_P6 (15) + +/* Coefficient P8 LSB position */ +#define BME68X_IDX_P8_LSB (18) + +/* Coefficient P8 MSB position */ +#define BME68X_IDX_P8_MSB (19) + +/* Coefficient P9 LSB position */ +#define BME68X_IDX_P9_LSB (20) + +/* Coefficient P9 MSB position */ +#define BME68X_IDX_P9_MSB (21) + +/* Coefficient P10 position */ +#define BME68X_IDX_P10 (22) + +/* Coefficient H2 MSB position */ +#define BME68X_IDX_H2_MSB (23) + +/* Coefficient H2 LSB position */ +#define BME68X_IDX_H2_LSB (24) + +/* Coefficient H1 LSB position */ +#define BME68X_IDX_H1_LSB (24) + +/* Coefficient H1 MSB position */ +#define BME68X_IDX_H1_MSB (25) + +/* Coefficient H3 position */ +#define BME68X_IDX_H3 (26) + +/* Coefficient H4 position */ +#define BME68X_IDX_H4 (27) + +/* Coefficient H5 position */ +#define BME68X_IDX_H5 (28) + +/* Coefficient H6 position */ +#define BME68X_IDX_H6 (29) + +/* Coefficient H7 position */ +#define BME68X_IDX_H7 (30) + +/* Coefficient T1 LSB position */ +#define BME68X_IDX_T1_LSB (31) + +/* Coefficient T1 MSB position */ +#define BME68X_IDX_T1_MSB (32) + +/* Coefficient GH2 LSB position */ +#define BME68X_IDX_GH2_LSB (33) + +/* Coefficient GH2 MSB position */ +#define BME68X_IDX_GH2_MSB (34) + +/* Coefficient GH1 position */ +#define BME68X_IDX_GH1 (35) + +/* Coefficient GH3 position */ +#define BME68X_IDX_GH3 (36) + +/* Coefficient res heat value position */ +#define BME68X_IDX_RES_HEAT_VAL (37) + +/* Coefficient res heat range position */ +#define BME68X_IDX_RES_HEAT_RANGE (39) + +/* Coefficient range switching error position */ +#define BME68X_IDX_RANGE_SW_ERR (41) + +/* Gas measurement macros */ + +/* Disable gas measurement */ +#define BME68X_DISABLE_GAS_MEAS UINT8_C(0x00) + +/* Enable gas measurement low */ +#define BME68X_ENABLE_GAS_MEAS_L UINT8_C(0x01) + +/* Enable gas measurement high */ +#define BME68X_ENABLE_GAS_MEAS_H UINT8_C(0x02) + +/* Heater control macros */ + +/* Enable heater */ +#define BME68X_ENABLE_HEATER UINT8_C(0x00) + +/* Disable heater */ +#define BME68X_DISABLE_HEATER UINT8_C(0x01) + +#ifdef BME68X_USE_FPU + +/* 0 degree Celsius */ +#define BME68X_MIN_TEMPERATURE INT16_C(0) + +/* 60 degree Celsius */ +#define BME68X_MAX_TEMPERATURE INT16_C(60) + +/* 900 hecto Pascals */ +#define BME68X_MIN_PRESSURE UINT32_C(90000) + +/* 1100 hecto Pascals */ +#define BME68X_MAX_PRESSURE UINT32_C(110000) + +/* 20% relative humidity */ +#define BME68X_MIN_HUMIDITY UINT32_C(20) + +/* 80% relative humidity*/ +#define BME68X_MAX_HUMIDITY UINT32_C(80) +#else + +/* 0 degree Celsius */ +#define BME68X_MIN_TEMPERATURE INT16_C(0) + +/* 60 degree Celsius */ +#define BME68X_MAX_TEMPERATURE INT16_C(6000) + +/* 900 hecto Pascals */ +#define BME68X_MIN_PRESSURE UINT32_C(90000) + +/* 1100 hecto Pascals */ +#define BME68X_MAX_PRESSURE UINT32_C(110000) + +/* 20% relative humidity */ +#define BME68X_MIN_HUMIDITY UINT32_C(20000) + +/* 80% relative humidity*/ +#define BME68X_MAX_HUMIDITY UINT32_C(80000) + +#endif + +#define BME68X_HEATR_DUR1 UINT16_C(1000) +#define BME68X_HEATR_DUR2 UINT16_C(2000) +#define BME68X_HEATR_DUR1_DELAY UINT32_C(1000000) +#define BME68X_HEATR_DUR2_DELAY UINT32_C(2000000) +#define BME68X_N_MEAS UINT8_C(6) +#define BME68X_LOW_TEMP UINT8_C(150) +#define BME68X_HIGH_TEMP UINT16_C(350) + +/* Mask macros */ +/* Mask for number of conversions */ +#define BME68X_NBCONV_MSK UINT8_C(0X0f) + +/* Mask for IIR filter */ +#define BME68X_FILTER_MSK UINT8_C(0X1c) + +/* Mask for ODR[3] */ +#define BME68X_ODR3_MSK UINT8_C(0x80) + +/* Mask for ODR[2:0] */ +#define BME68X_ODR20_MSK UINT8_C(0xe0) + +/* Mask for temperature oversampling */ +#define BME68X_OST_MSK UINT8_C(0Xe0) + +/* Mask for pressure oversampling */ +#define BME68X_OSP_MSK UINT8_C(0X1c) + +/* Mask for humidity oversampling */ +#define BME68X_OSH_MSK UINT8_C(0X07) + +/* Mask for heater control */ +#define BME68X_HCTRL_MSK UINT8_C(0x08) + +/* Mask for run gas */ +#define BME68X_RUN_GAS_MSK UINT8_C(0x30) + +/* Mask for operation mode */ +#define BME68X_MODE_MSK UINT8_C(0x03) + +/* Mask for res heat range */ +#define BME68X_RHRANGE_MSK UINT8_C(0x30) + +/* Mask for range switching error */ +#define BME68X_RSERROR_MSK UINT8_C(0xf0) + +/* Mask for new data */ +#define BME68X_NEW_DATA_MSK UINT8_C(0x80) + +/* Mask for gas index */ +#define BME68X_GAS_INDEX_MSK UINT8_C(0x0f) + +/* Mask for gas range */ +#define BME68X_GAS_RANGE_MSK UINT8_C(0x0f) + +/* Mask for gas measurement valid */ +#define BME68X_GASM_VALID_MSK UINT8_C(0x20) + +/* Mask for heater stability */ +#define BME68X_HEAT_STAB_MSK UINT8_C(0x10) + +/* Mask for SPI memory page */ +#define BME68X_MEM_PAGE_MSK UINT8_C(0x10) + +/* Mask for reading a register in SPI */ +#define BME68X_SPI_RD_MSK UINT8_C(0x80) + +/* Mask for writing a register in SPI */ +#define BME68X_SPI_WR_MSK UINT8_C(0x7f) + +/* Mask for the H1 calibration coefficient */ +#define BME68X_BIT_H1_DATA_MSK UINT8_C(0x0f) + +/* Position macros */ + +/* Filter bit position */ +#define BME68X_FILTER_POS UINT8_C(2) + +/* Temperature oversampling bit position */ +#define BME68X_OST_POS UINT8_C(5) + +/* Pressure oversampling bit position */ +#define BME68X_OSP_POS UINT8_C(2) + +/* ODR[3] bit position */ +#define BME68X_ODR3_POS UINT8_C(7) + +/* ODR[2:0] bit position */ +#define BME68X_ODR20_POS UINT8_C(5) + +/* Run gas bit position */ +#define BME68X_RUN_GAS_POS UINT8_C(4) + +/* Heater control bit position */ +#define BME68X_HCTRL_POS UINT8_C(3) + +/* Macro to combine two 8 bit data's to form a 16 bit data */ +#define BME68X_CONCAT_BYTES(msb, lsb) (((uint16_t)msb << 8) | (uint16_t)lsb) + +/* Macro to set bits */ +#define BME68X_SET_BITS(reg_data, bitname, data) \ + ((reg_data & ~(bitname##_MSK)) | \ + ((data << bitname##_POS) & bitname##_MSK)) + +/* Macro to get bits */ +#define BME68X_GET_BITS(reg_data, bitname) ((reg_data & (bitname##_MSK)) >> \ + (bitname##_POS)) + +/* Macro to set bits starting from position 0 */ +#define BME68X_SET_BITS_POS_0(reg_data, bitname, data) \ + ((reg_data & ~(bitname##_MSK)) | \ + (data & bitname##_MSK)) + +/* Macro to get bits starting from position 0 */ +#define BME68X_GET_BITS_POS_0(reg_data, bitname) (reg_data & (bitname##_MSK)) + +/** + * BME68X_INTF_RET_TYPE is the read/write interface return type which can be overwritten by the build system. + * The default is set to int8_t. + */ +#ifndef BME68X_INTF_RET_TYPE +#define BME68X_INTF_RET_TYPE int8_t +#endif + +/** + * BME68X_INTF_RET_SUCCESS is the success return value read/write interface return type which can be + * overwritten by the build system. The default is set to 0. It is used to check for a successful + * execution of the read/write functions + */ +#ifndef BME68X_INTF_RET_SUCCESS +#define BME68X_INTF_RET_SUCCESS INT8_C(0) +#endif + +/********************************************************* */ +/*! Function Pointers */ +/********************************************************* */ + +/*! + * @brief Bus communication function pointer which should be mapped to + * the platform specific read functions of the user + * + * @param[in] reg_addr : 8bit register address of the sensor + * @param[out] reg_data : Data from the specified address + * @param[in] length : Length of the reg_data array + * @param[in,out] intf_ptr : Void pointer that can enable the linking of descriptors + * for interface related callbacks + * @retval 0 for Success + * @retval Non-zero for Failure + */ +typedef BME68X_INTF_RET_TYPE (*bme68x_read_fptr_t)(uint8_t reg_addr, uint8_t *reg_data, uint32_t length, + void *intf_ptr); + +/*! + * @brief Bus communication function pointer which should be mapped to + * the platform specific write functions of the user + * + * @param[in] reg_addr : 8bit register address of the sensor + * @param[out] reg_data : Data to the specified address + * @param[in] length : Length of the reg_data array + * @param[in,out] intf_ptr : Void pointer that can enable the linking of descriptors + * for interface related callbacks + * @retval 0 for Success + * @retval Non-zero for Failure + * + */ +typedef BME68X_INTF_RET_TYPE (*bme68x_write_fptr_t)(uint8_t reg_addr, const uint8_t *reg_data, uint32_t length, + void *intf_ptr); + +/*! + * @brief Delay function pointer which should be mapped to + * delay function of the user + * + * @param period - The time period in microseconds + * @param[in,out] intf_ptr : Void pointer that can enable the linking of descriptors + * for interface related callbacks + */ +typedef void (*bme68x_delay_us_fptr_t)(uint32_t period, void *intf_ptr); + +/* + * @brief Generic communication function pointer + * @param[in] dev_id: Place holder to store the id of the device structure + * Can be used to store the index of the Chip select or + * I2C address of the device. + * @param[in] reg_addr: Used to select the register the where data needs to + * be read from or written to. + * @param[in,out] reg_data: Data array to read/write + * @param[in] len: Length of the data array + */ + +/* + * @brief Interface selection Enumerations + */ +enum bme68x_intf { + /*! SPI interface */ + BME68X_SPI_INTF, + /*! I2C interface */ + BME68X_I2C_INTF +}; + +/* Structure definitions */ + +/* + * @brief Sensor field data structure + */ +struct bme68x_data +{ + /*! Contains new_data, gasm_valid & heat_stab */ + uint8_t status; + + /*! The index of the heater profile used */ + uint8_t gas_index; + + /*! Measurement index to track order */ + uint8_t meas_index; + + /*! Heater resistance */ + uint8_t res_heat; + + /*! Current DAC */ + uint8_t idac; + + /*! Gas wait period */ + uint8_t gas_wait; +#ifndef BME68X_USE_FPU + + /*! Temperature in degree celsius x100 */ + int16_t temperature; + + /*! Pressure in Pascal */ + uint32_t pressure; + + /*! Humidity in % relative humidity x1000 */ + uint32_t humidity; + + /*! Gas resistance in Ohms */ + uint32_t gas_resistance; +#else + + /*! Temperature in degree celsius */ + float temperature; + + /*! Pressure in Pascal */ + float pressure; + + /*! Humidity in % relative humidity x1000 */ + float humidity; + + /*! Gas resistance in Ohms */ + float gas_resistance; + +#endif + +}; + +/* + * @brief Structure to hold the calibration coefficients + */ +struct bme68x_calib_data +{ + /*! Calibration coefficient for the humidity sensor */ + uint16_t par_h1; + + /*! Calibration coefficient for the humidity sensor */ + uint16_t par_h2; + + /*! Calibration coefficient for the humidity sensor */ + int8_t par_h3; + + /*! Calibration coefficient for the humidity sensor */ + int8_t par_h4; + + /*! Calibration coefficient for the humidity sensor */ + int8_t par_h5; + + /*! Calibration coefficient for the humidity sensor */ + uint8_t par_h6; + + /*! Calibration coefficient for the humidity sensor */ + int8_t par_h7; + + /*! Calibration coefficient for the gas sensor */ + int8_t par_gh1; + + /*! Calibration coefficient for the gas sensor */ + int16_t par_gh2; + + /*! Calibration coefficient for the gas sensor */ + int8_t par_gh3; + + /*! Calibration coefficient for the temperature sensor */ + uint16_t par_t1; + + /*! Calibration coefficient for the temperature sensor */ + int16_t par_t2; + + /*! Calibration coefficient for the temperature sensor */ + int8_t par_t3; + + /*! Calibration coefficient for the pressure sensor */ + uint16_t par_p1; + + /*! Calibration coefficient for the pressure sensor */ + int16_t par_p2; + + /*! Calibration coefficient for the pressure sensor */ + int8_t par_p3; + + /*! Calibration coefficient for the pressure sensor */ + int16_t par_p4; + + /*! Calibration coefficient for the pressure sensor */ + int16_t par_p5; + + /*! Calibration coefficient for the pressure sensor */ + int8_t par_p6; + + /*! Calibration coefficient for the pressure sensor */ + int8_t par_p7; + + /*! Calibration coefficient for the pressure sensor */ + int16_t par_p8; + + /*! Calibration coefficient for the pressure sensor */ + int16_t par_p9; + + /*! Calibration coefficient for the pressure sensor */ + uint8_t par_p10; +#ifndef BME68X_USE_FPU + + /*! Variable to store the intermediate temperature coefficient */ + int32_t t_fine; +#else + + /*! Variable to store the intermediate temperature coefficient */ + float t_fine; +#endif + + /*! Heater resistance range coefficient */ + uint8_t res_heat_range; + + /*! Heater resistance value coefficient */ + int8_t res_heat_val; + + /*! Gas resistance range switching error coefficient */ + int8_t range_sw_err; +}; + +/* + * @brief BME68X sensor settings structure which comprises of ODR, + * over-sampling and filter settings. + */ +struct bme68x_conf +{ + /*! Humidity oversampling. Refer @ref osx*/ + uint8_t os_hum; + + /*! Temperature oversampling. Refer @ref osx */ + uint8_t os_temp; + + /*! Pressure oversampling. Refer @ref osx */ + uint8_t os_pres; + + /*! Filter coefficient. Refer @ref filter*/ + uint8_t filter; + + /*! + * Standby time between sequential mode measurement profiles. + * Refer @ref odr + */ + uint8_t odr; +}; + +/* + * @brief BME68X gas heater configuration + */ +struct bme68x_heatr_conf +{ + /*! Enable gas measurement. Refer @ref en_dis */ + uint8_t enable; + + /*! Store the heater temperature for forced mode degree Celsius */ + uint16_t heatr_temp; + + /*! Store the heating duration for forced mode in milliseconds */ + uint16_t heatr_dur; + + /*! Store the heater temperature profile in degree Celsius */ + uint16_t *heatr_temp_prof; + + /*! Store the heating duration profile in milliseconds */ + uint16_t *heatr_dur_prof; + + /*! Variable to store the length of the heating profile */ + uint8_t profile_len; + + /*! + * Variable to store heating duration for parallel mode + * in milliseconds + */ + uint16_t shared_heatr_dur; +}; + +/* + * @brief BME68X device structure + */ +struct bme68x_dev +{ + /*! Chip Id */ + uint8_t chip_id; + + /*! + * The interface pointer is used to enable the user + * to link their interface descriptors for reference during the + * implementation of the read and write interfaces to the + * hardware. + */ + void *intf_ptr; + + /*! + * Variant id + * ---------------------------------------- + * Value | Variant + * ---------------------------------------- + * 0 | BME68X_VARIANT_GAS_LOW + * 1 | BME68X_VARIANT_GAS_HIGH + * ---------------------------------------- + */ + uint32_t variant_id; + + /*! SPI/I2C interface */ + enum bme68x_intf intf; + + /*! Memory page used */ + uint8_t mem_page; + + /*! Ambient temperature in Degree C*/ + int8_t amb_temp; + + /*! Sensor calibration data */ + struct bme68x_calib_data calib; + + /*! Read function pointer */ + bme68x_read_fptr_t read; + + /*! Write function pointer */ + bme68x_write_fptr_t write; + + /*! Delay function pointer */ + bme68x_delay_us_fptr_t delay_us; + + /*! To store interface pointer error */ + BME68X_INTF_RET_TYPE intf_rslt; + + /*! Store the info messages */ + uint8_t info_msg; +}; + +#endif /* BME68X_DEFS_H_ */ +/*! @endcond */ diff --git a/lib/Adafruit_BME680/library.properties b/lib/Adafruit_BME680/library.properties index 08496da20..6277aa1be 100644 --- a/lib/Adafruit_BME680/library.properties +++ b/lib/Adafruit_BME680/library.properties @@ -1,10 +1,10 @@ name=Adafruit BME680 Library -version=1.1.1 +version=2.0.2 author=Adafruit maintainer=Adafruit -sentence=Arduino library for BME680 sensors. -paragraph=Arduino library for BME680 humidity and pressure sensors. +sentence=Arduino library for BME680 and BME688 sensors. +paragraph=Arduino library for BME680 and BME688 humidity and pressure sensors. category=Sensors url=https://github.com/adafruit/Adafruit_BME680 architectures=* -depends=Adafruit Unified Sensor, Adafruit GFX Library, Adafruit SSD1306 +depends=Adafruit Unified Sensor, Adafruit GFX Library, Adafruit SSD1306, Adafruit BusIO diff --git a/src/_P102_PZEM004Tv3.ino b/src/_P102_PZEM004Tv3.ino index 6d39c1955..1376f688c 100644 --- a/src/_P102_PZEM004Tv3.ino +++ b/src/_P102_PZEM004Tv3.ino @@ -17,7 +17,7 @@ # define PLUGIN_102 # define PLUGIN_ID_102 102 # define PLUGIN_102_DEBUG true // activate extra log info in the debug -# define PLUGIN_NAME_102 "PZEM-004Tv30-Multiple" +# define PLUGIN_NAME_102 "Energy (AC) - PZEM-004Tv30-Multiple" # define P102_PZEM_mode PCONFIG(1) // 0=read value ; 1=reset energy; 2=programm address # define P102_PZEM_ADDR PCONFIG(2) @@ -38,9 +38,9 @@ # define P102_NR_OUTPUT_OPTIONS 6 # define P102_QUERY1_CONFIG_POS 3 -# define P102_PZEM_MAX_ATTEMPT 3 // Number of tentative before declaring NAN value +# define P102_PZEM_MAX_ATTEMPT 3 // Number of tentative before declaring NAN value -PZEM004Tv30 *P102_PZEM_sensor = nullptr; +PZEM004Tv30 * P102_PZEM_sensor = nullptr; boolean Plugin_102_init = false; uint8_t P102_PZEM_ADDR_SET = 0; // Flag for status of programmation/Energy reset: 0=Reading / 1=Prog confirmed / 3=Prog done / 4=Reset diff --git a/src/_P106_BME680.ino b/src/_P106_BME680.ino index 90f856e1a..3fdf9703b 100644 --- a/src/_P106_BME680.ino +++ b/src/_P106_BME680.ino @@ -14,13 +14,22 @@ Adafruit_BME680 Library v1.0.5 required (https://github.com/adafruit/Adafruit_BME680/tree/1.0.5) /******************************************************************************/ +/** Changelog: + * 2023-04-16 tonhuisman: Add option to present Gas(resistance) as Ohm instead of kOhm + * Rename sensor to BME68x from BME680, as BME688 is backward compatible. + * NB: AI-features of BME688 are not supported! + * Use updated #defines since BME680 library update + * 2023-04-15 tonhuisman: Fix copy/paste error for FEATURE_I2C_GET_ADDRESS + * Update Adafruit_BME680 library to v2.0.2 + * 2023-04-15 tonhuisman: Started Changelog + */ # include "src/PluginStructs/P106_data_struct.h" # define PLUGIN_106 # define PLUGIN_ID_106 106 -# define PLUGIN_NAME_106 "Environment - BME680" +# define PLUGIN_NAME_106 "Environment - BME68x" # define PLUGIN_VALUENAME1_106 "Temperature" # define PLUGIN_VALUENAME2_106 "Humidity" # define PLUGIN_VALUENAME3_106 "Pressure" @@ -69,8 +78,9 @@ boolean Plugin_106(uint8_t function, struct EventStruct *event, String& string) case PLUGIN_WEBFORM_SHOW_I2C_PARAMS: { const uint8_t i2cAddressValues[] = { 0x77, 0x76 }; + if (function == PLUGIN_WEBFORM_SHOW_I2C_PARAMS) { - addFormSelectorI2C(F("i2c_addr"), 2, i2cAddressValues, PCONFIG(0)); + addFormSelectorI2C(F("i2c_addr"), 2, i2cAddressValues, P106_I2C_ADDRESS); addFormNote(F("SDO Low=0x76, High=0x77")); } else { success = intArrayContains(2, i2cAddressValues, event->Par1); @@ -78,10 +88,10 @@ boolean Plugin_106(uint8_t function, struct EventStruct *event, String& string) break; } - # if FEATURE_I2FEATURE_I2C_GET_ADDRESSC_DEVICE_CHECK + # if FEATURE_I2C_GET_ADDRESS case PLUGIN_I2C_GET_ADDRESS: { - event->Par1 = PCONFIG(0); + event->Par1 = P106_I2C_ADDRESS; success = true; break; } @@ -89,18 +99,21 @@ boolean Plugin_106(uint8_t function, struct EventStruct *event, String& string) case PLUGIN_WEBFORM_LOAD: { - addFormNumericBox(F("Altitude"), F("elev"), PCONFIG(1)); + addFormNumericBox(F("Altitude"), F("elev"), P106_ALTITUDE); addUnit('m'); + addFormCheckBox(F("Present `Gas` in Ohm (not kOhm)"), F("gas"), P106_GET_OPT_GAS_OHM); + success = true; break; } case PLUGIN_WEBFORM_SAVE: { - PCONFIG(0) = getFormItemInt(F("i2c_addr")); - PCONFIG(1) = getFormItemInt(F("elev")); - success = true; + P106_I2C_ADDRESS = getFormItemInt(F("i2c_addr")); + P106_ALTITUDE = getFormItemInt(F("elev")); + P106_SET_OPT_GAS_OHM(isFormItemChecked(F("gas"))); + success = true; break; } @@ -112,7 +125,7 @@ boolean Plugin_106(uint8_t function, struct EventStruct *event, String& string) if (nullptr != P106_data) { P106_data->initialized = false; // Force re-init just in case the address changed. - success = P106_data->begin(PCONFIG(0)); + success = P106_data->begin(P106_I2C_ADDRESS); } break; } @@ -124,7 +137,7 @@ boolean Plugin_106(uint8_t function, struct EventStruct *event, String& string) if (nullptr != P106_data) { - P106_data->begin(PCONFIG(0)); + P106_data->begin(P106_I2C_ADDRESS); if (!P106_data->initialized) { break; @@ -132,15 +145,16 @@ boolean Plugin_106(uint8_t function, struct EventStruct *event, String& string) if (!P106_data->bme.performReading()) { P106_data->initialized = false; - addLog(LOG_LEVEL_ERROR, F("BME680 : Failed to perform reading!")); + addLog(LOG_LEVEL_ERROR, F("BME68x : Failed to perform reading!")); break; } UserVar[event->BaseVarIndex + 0] = P106_data->bme.temperature; UserVar[event->BaseVarIndex + 1] = P106_data->bme.humidity; - UserVar[event->BaseVarIndex + 3] = P106_data->bme.gas_resistance / 1000.0f; + UserVar[event->BaseVarIndex + 3] = P106_GET_OPT_GAS_OHM ? P106_data->bme.gas_resistance : P106_data->bme.gas_resistance / 1000.0f; + + const int elev = P106_ALTITUDE; - const int elev = PCONFIG(1); if (elev != 0) { UserVar[event->BaseVarIndex + 2] = pressureElevation(P106_data->bme.pressure / 100.0f, elev); diff --git a/src/_P150_TMP117.ino b/src/_P150_TMP117.ino new file mode 100644 index 000000000..3cb0f3edb --- /dev/null +++ b/src/_P150_TMP117.ino @@ -0,0 +1,265 @@ +#include "_Plugin_Helper.h" +#ifdef USES_P150 + +// ####################################################################################################### +// ######################## Plugin-150: TMP117 High precision temperature sensor I2C #################### +// ####################################################################################################### + +/** Changelog: + * 2023-04-15 tonhuisman: Correctly apply configuration bits (clear first), add optional low-level logging, improve configuration page + * 2023-04-13 tonhuisman: Switch to check the sensor once a second, and read when data is available, return last value every interval + * Make one-shot mode work as intended, one-shot is started from last read, so based on the interval + * 2023-04-09 tonhuisman: Rename configuration options (compile-time), add optional output logging (default on), + * use more I2C_access functions, make Raw value optional (default on), + * 2023-04-08 tonhuisman: Basic workings for setting configuration and temperature offset, then reading the temperature + * only when data is available. + * 2023-04-08 tonhuisman: Initial work on new plugin for TMP117, available in Collection F, Climate and MAX builds + */ + +# include "src/PluginStructs/P150_data_struct.h" + +# define PLUGIN_150 +# define PLUGIN_ID_150 150 +# define PLUGIN_NAME_150 "Environment - TMP117 Temperature" +# define PLUGIN_VALUENAME1_150 "Temperature" +# define PLUGIN_VALUENAME2_150 "Raw" + +boolean Plugin_150(uint8_t function, struct EventStruct *event, String& string) +{ + boolean success = false; + + switch (function) + { + case PLUGIN_DEVICE_ADD: + { + Device[++deviceCount].Number = PLUGIN_ID_150; + Device[deviceCount].Type = DEVICE_TYPE_I2C; + Device[deviceCount].VType = Sensor_VType::SENSOR_TYPE_DUAL; + Device[deviceCount].Ports = 0; + Device[deviceCount].PullUpOption = false; + Device[deviceCount].InverseLogicOption = false; + Device[deviceCount].FormulaOption = true; + Device[deviceCount].ValueCount = 2; + Device[deviceCount].SendDataOption = true; + Device[deviceCount].TimerOption = true; + Device[deviceCount].GlobalSyncOption = true; + Device[deviceCount].PluginStats = true; + + break; + } + + case PLUGIN_GET_DEVICENAME: + { + string = F(PLUGIN_NAME_150); + + break; + } + + case PLUGIN_GET_DEVICEVALUENAMES: + { + strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[0], PSTR(PLUGIN_VALUENAME1_150)); + strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[1], PSTR(PLUGIN_VALUENAME2_150)); + + break; + } + + case PLUGIN_GET_DEVICEVALUECOUNT: + { + event->Par1 = P150_GET_OPT_ENABLE_RAW ? 2 : 1; + success = true; + + break; + } + + case PLUGIN_GET_DEVICEVTYPE: + { + event->sensorType = P150_GET_OPT_ENABLE_RAW ? Sensor_VType::SENSOR_TYPE_DUAL : Sensor_VType::SENSOR_TYPE_SINGLE; + event->idx = P150_GET_OPT_ENABLE_RAW ? 2 : 1; + success = true; + + break; + } + + case PLUGIN_I2C_HAS_ADDRESS: + case PLUGIN_WEBFORM_SHOW_I2C_PARAMS: + { + const uint8_t i2cAddressValues[] = { 0x48, 0x49, 0x4A, 0x4B }; + + if (PLUGIN_WEBFORM_SHOW_I2C_PARAMS == function) { + addFormSelectorI2C(F("i2c_addr"), 4, i2cAddressValues, P150_I2C_ADDRESS); + } else { + success = intArrayContains(4, i2cAddressValues, event->Par1); + } + + break; + } + + # if FEATURE_I2C_GET_ADDRESS + case PLUGIN_I2C_GET_ADDRESS: + { + event->Par1 = P150_I2C_ADDRESS; + success = true; + + break; + } + # endif // if FEATURE_I2C_GET_ADDRESS + + case PLUGIN_SET_DEFAULTS: + { + P150_SET_CONF_AVERAGING(P150_AVERAGING_8_SAMPLES); + P150_SET_CONF_CONVERSION_MODE(P150_CONVERSION_CONTINUOUS); + P150_SET_CONF_CYCLE_BITS(P150_CYCLE_1_SEC); + P150_SET_OPT_ENABLE_RAW(1); // Enable Raw by default + P150_SET_OPT_ENABLE_LOG(1); // Enable logging by default + ExtraTaskSettings.TaskDeviceValueDecimals[1] = 0; // No decimals for the Raw value + + break; + } + + case PLUGIN_WEBFORM_LOAD: + { + addFormNumericBox(F("Temperature offset"), F("offset"), P150_TEMPERATURE_OFFSET); + addUnit(F("x 0.1C")); + addFormNote(F("Offset in units of 0.1 degree Celsius!")); + + { + const __FlashStringHelper *averagingCaptions[] = { + F("No averaging"), + F("8 sample average"), + F("32 sample average"), + F("64 sample average"), + }; + const int averagingOptions[] = { + P150_AVERAGING_NONE, + P150_AVERAGING_8_SAMPLES, + P150_AVERAGING_32_SAMPLES, + P150_AVERAGING_64_SAMPLES, + }; + addFormSelector(F("Averaging"), F("avg"), 4, averagingCaptions, averagingOptions, P150_GET_CONF_AVERAGING); + } + + { + const __FlashStringHelper *conversionCaptions[] = { + F("Continuous"), + F("One-shot"), + }; + const int conversionOptions[] = { + P150_CONVERSION_CONTINUOUS, + P150_CONVERSION_ONE_SHOT, + }; + addFormSelector(F("Conversion mode"), F("conv"), 2, conversionCaptions, conversionOptions, P150_GET_CONF_CONVERSION_MODE, true); + addFormNote(F("Changing this setting will save and reload this page.")); + } + + if (P150_GET_CONF_CONVERSION_MODE == P150_CONVERSION_CONTINUOUS) { + const __FlashStringHelper *cycleCaptions[] = { + F("15.5 msec"), + F("125 msec"), + F("250 msec"), + F("500 msec"), + F("1 sec"), + F("4 sec"), + F("8 sec"), + F("16 sec"), + }; + const int cycleOptions[] = { + P150_CYCLE_15_5_MSEC, + P150_CYCLE_125_MSEC, + P150_CYCLE_250_MSEC, + P150_CYCLE_500_MSEC, + P150_CYCLE_1_SEC, + P150_CYCLE_4_SEC, + P150_CYCLE_8_SEC, + P150_CYCLE_16_SEC, + }; + addFormSelector(F("Continuous conversion cycle time"), F("cycle"), 8, cycleCaptions, cycleOptions, P150_GET_CONF_CYCLE_BITS); + } + + addFormSubHeader(F("Output")); + + addFormSelector_YesNo(F("Enable 'Raw' value"), F("raw"), P150_GET_OPT_ENABLE_RAW ? 1 : 0, true); + addFormNote(F("Changing this setting will save and reload this page.")); + + addFormCheckBox(F("Log measured values (INFO)"), F("log"), P150_GET_OPT_ENABLE_LOG); + + # if P150_USE_EXTRA_LOG + addFormCheckBox(F("Log low-level values (INFO)"), F("xlog"), P150_GET_OPT_EXTRA_LOG); + # endif // if P150_USE_EXTRA_LOG + + success = true; + + break; + } + + case PLUGIN_WEBFORM_SAVE: + { + P150_I2C_ADDRESS = getFormItemInt(F("i2c_addr")); + P150_TEMPERATURE_OFFSET = getFormItemInt(F("offset")); + P150_SET_CONF_AVERAGING(getFormItemInt(F("avg"))); + uint8_t prvConv = P150_GET_CONF_CONVERSION_MODE; + P150_SET_CONF_CONVERSION_MODE(getFormItemInt(F("conv"))); + + if ((P150_GET_CONF_CONVERSION_MODE == P150_CONVERSION_CONTINUOUS) && (prvConv == P150_CONVERSION_CONTINUOUS)) { + P150_SET_CONF_CYCLE_BITS(getFormItemInt(F("cycle"))); + } else { + P150_SET_CONF_CYCLE_BITS(P150_CYCLE_1_SEC); // Default + } + + uint8_t raw = getFormItemInt(F("raw")); + + if (P150_GET_OPT_ENABLE_RAW != raw) { + if (raw) { + strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[1], PSTR(PLUGIN_VALUENAME2_150)); + ExtraTaskSettings.TaskDeviceValueDecimals[1] = 0; // No decimals for the Raw value + } + P150_SET_OPT_ENABLE_RAW(raw); + } + P150_SET_OPT_ENABLE_LOG(isFormItemChecked(F("log"))); + # if P150_USE_EXTRA_LOG + P150_SET_OPT_EXTRA_LOG(isFormItemChecked(F("xlog"))); + # endif // if P150_USE_EXTRA_LOG + + success = true; + + break; + } + + case PLUGIN_INIT: + { + initPluginTaskData(event->TaskIndex, new (std::nothrow) P150_data_struct(event)); + P150_data_struct *P150_data = + static_cast(getPluginTaskData(event->TaskIndex)); + + success = (nullptr != P150_data && P150_data->init()); + + break; + } + + case PLUGIN_READ: + { + P150_data_struct *P150_data = + static_cast(getPluginTaskData(event->TaskIndex)); + + if (nullptr != P150_data) { + success = P150_data->plugin_read(event); + } + + break; + } + + case PLUGIN_ONCE_A_SECOND: + { + P150_data_struct *P150_data = + static_cast(getPluginTaskData(event->TaskIndex)); + + if (nullptr != P150_data) { + success = P150_data->plugin_once_a_second(event); + } + + break; + } + } + return success; +} + +#endif // ifdef USES_P150 diff --git a/src/src/Commands/Common.cpp b/src/src/Commands/Common.cpp index f81bac80d..f8157275e 100644 --- a/src/src/Commands/Common.cpp +++ b/src/src/Commands/Common.cpp @@ -158,6 +158,7 @@ String Command_GetORSetBool(struct EventStruct *event, if (validIntFromString(TmpStr1, tmp_int)) { *value = tmp_int > 0; } + else if (TmpStr1.isEmpty()) {} // Empty string not always handled nicely by strcmp_P else if (strcmp_P(PSTR("on"), TmpStr1.c_str()) == 0) { *value = true; } else if (strcmp_P(PSTR("true"), TmpStr1.c_str()) == 0) { *value = true; } else if (strcmp_P(PSTR("off"), TmpStr1.c_str()) == 0) { *value = false; } diff --git a/src/src/Commands/GPIO.cpp b/src/src/Commands/GPIO.cpp index c42ffabab..eae964d28 100644 --- a/src/src/Commands/GPIO.cpp +++ b/src/src/Commands/GPIO.cpp @@ -215,13 +215,30 @@ const __FlashStringHelper * Command_GPIO_LongPulse_Ms(struct EventStruct *event, } uint32_t runTimeUS = 0; if (event->Par5 > 0) { - // Must set slightly lower than expected duration as it will be rounded up. - runTimeUS = event->Par5 * (timeHighUS + timeLowUS) - ((timeHighUS + timeLowUS) / 2); + runTimeUS = event->Par5 * (timeHighUS + timeLowUS); + if (event->Par2 == 0) { + // When having an inverted state repeat-cycle, add some overshoot to return to the original state + runTimeUS += timeHighUS / 2; + } else { + // Must set slightly lower than expected duration as it will be rounded up. + runTimeUS -= ((timeHighUS + timeLowUS) / 2); + } } pinMode(event->Par1, OUTPUT); usingWaveForm = startWaveform( pin, timeHighUS, timeLowUS, runTimeUS); + + if (event->Par5 > 0 && event->Par2 == 0) { + // Schedule switching pin back to original state + Scheduler.setGPIOTimer( + (runTimeUS / 1000) + 1, // msecFromNow, rounded up + pluginID, + event->Par1, // Pin/port nr + !event->Par2, // pin state + 0, // repeatInterval + 0); // repeatCount + } } #else // waveform function not available on ESP32 diff --git a/src/src/Commands/HTTP.cpp b/src/src/Commands/HTTP.cpp index 382f58dfc..18567310e 100644 --- a/src/src/Commands/HTTP.cpp +++ b/src/src/Commands/HTTP.cpp @@ -17,7 +17,7 @@ #include "../Helpers/Networking.h" #include "../Helpers/StringParser.h" -#if FEATURE_SEND_TO_HTTP || FEATURE_POST_TO_HTTP +#if FEATURE_SEND_TO_HTTP || FEATURE_POST_TO_HTTP || FEATURE_PUT_TO_HTTP const __FlashStringHelper* httpEmitToHTTP(struct EventStruct *event, const __FlashStringHelper *logIdentifier, const __FlashStringHelper *HttpMethod, @@ -125,7 +125,7 @@ const __FlashStringHelper* httpEmitToHTTP(struct EventStruct *event, return return_command_failed(); } -#endif // if FEATURE_SEND_TO_HTTP || FEATURE_POST_TO_HTTP +#endif // if FEATURE_SEND_TO_HTTP || FEATURE_POST_TO_HTTP || FEATURE_PUT_TO_HTTP #if FEATURE_SEND_TO_HTTP @@ -160,3 +160,19 @@ const __FlashStringHelper* Command_HTTP_PostToHTTP(struct EventStruct *event, co } #endif // if FEATURE_POST_TO_HTTP + +#if FEATURE_PUT_TO_HTTP + +// syntax 1: PutToHttp,<[:@],,,
, +// syntax 2: PutToHttp,http://<[:@][:]/,
, +const __FlashStringHelper* Command_HTTP_PutToHTTP(struct EventStruct *event, const char *Line) +{ + // FIXME tonhuisman: Make putToHttp timeout a setting, now using a somewhat sensible default + const int timeout = CONTROLLER_CLIENTTIMEOUT_MAX; + + // FIXME tonhuisman: make PutToHttp_ack a setting, using SendToHttp_ack for now... + + return httpEmitToHTTP(event, F("PutToHTTP"), F("PUT"), Line, timeout, Settings.SendToHttp_ack(), true, true); +} + +#endif // if FEATURE_PUT_TO_HTTP diff --git a/src/src/Commands/HTTP.h b/src/src/Commands/HTTP.h index cab08af23..42d383523 100644 --- a/src/src/Commands/HTTP.h +++ b/src/src/Commands/HTTP.h @@ -3,7 +3,7 @@ #include -#if FEATURE_SEND_TO_HTTP || FEATURE_POST_TO_HTTP +#if FEATURE_SEND_TO_HTTP || FEATURE_POST_TO_HTTP || FEATURE_PUT_TO_HTTP const __FlashStringHelper* httpEmitToHTTP(struct EventStruct *event, const __FlashStringHelper *logIdentifier, const __FlashStringHelper *HttpMethod, @@ -12,7 +12,7 @@ const __FlashStringHelper* httpEmitToHTTP(struct EventStruct *event, const bool waitForAck, const bool useHeader, const bool useBody); -#endif // if FEATURE_SEND_TO_HTTP || FEATURE_POST_TO_HTTP +#endif // if FEATURE_SEND_TO_HTTP || FEATURE_POST_TO_HTTP || FEATURE_PUT_TO_HTTP #if FEATURE_SEND_TO_HTTP const __FlashStringHelper* Command_HTTP_SendToHTTP(struct EventStruct *event, const char *Line); @@ -21,5 +21,9 @@ const __FlashStringHelper* Command_HTTP_SendToHTTP(struct EventStruct *event, const __FlashStringHelper* Command_HTTP_PostToHTTP(struct EventStruct *event, const char *Line); #endif // if FEATURE_POST_TO_HTTP +#if FEATURE_PUT_TO_HTTP +const __FlashStringHelper* Command_HTTP_PutToHTTP(struct EventStruct *event, + const char *Line); +#endif // if FEATURE_PUT_TO_HTTP #endif // COMMAND_HTTP_H diff --git a/src/src/Commands/InternalCommands.cpp b/src/src/Commands/InternalCommands.cpp index 11eedbf91..0d8b8d76f 100644 --- a/src/src/Commands/InternalCommands.cpp +++ b/src/src/Commands/InternalCommands.cpp @@ -320,6 +320,9 @@ bool executeInternalCommand(command_case_data & data) COMMAND_CASE_A("gpiotoggle", Command_GPIO_Toggle, 1); // Gpio.h break; } + case 'h': { + COMMAND_CASE_R("hiddenssid", Command_Wifi_HiddenSSID, 1); // wifi.h + } case 'i': { COMMAND_CASE_R("i2cscanner", Command_i2c_Scanner, -1); // i2c.h COMMAND_CASE_A( "inc", Command_Rules_Inc, -1); // Rules.h @@ -413,6 +416,9 @@ bool executeInternalCommand(command_case_data & data) #if FEATURE_MQTT COMMAND_CASE_A( "publish", Command_MQTT_Publish, -1); // MQTT.h #endif // if FEATURE_MQTT + #if FEATURE_PUT_TO_HTTP + COMMAND_CASE_A("puttohttp", Command_HTTP_PutToHTTP, -1); // HTTP.h + #endif // if FEATURE_PUT_TO_HTTP COMMAND_CASE_A( "pwm", Command_GPIO_PWM, 4); // GPIO.h break; } diff --git a/src/src/Commands/WiFi.cpp b/src/src/Commands/WiFi.cpp index 365e5ae0e..bb43966d1 100644 --- a/src/src/Commands/WiFi.cpp +++ b/src/src/Commands/WiFi.cpp @@ -55,19 +55,33 @@ String Command_Wifi_Key2(struct EventStruct *event, const char *Line) 1); } -const __FlashStringHelper * Command_Wifi_Scan(struct EventStruct *event, const char *Line) +String Command_Wifi_HiddenSSID(struct EventStruct *event, const char *Line) +{ + bool includeHiddenSSID = Settings.IncludeHiddenSSID(); + String result = Command_GetORSetBool(event, F("Include Hidden SSID:"), + Line, + (bool *)&includeHiddenSSID, + 1); + + if (Settings.IncludeHiddenSSID() != includeHiddenSSID) { // Update if changed + Settings.IncludeHiddenSSID(includeHiddenSSID); + } + return result; +} + +const __FlashStringHelper* Command_Wifi_Scan(struct EventStruct *event, const char *Line) { WiFiScan_log_to_serial(); return return_command_success(); } -const __FlashStringHelper * Command_Wifi_Connect(struct EventStruct *event, const char *Line) +const __FlashStringHelper* Command_Wifi_Connect(struct EventStruct *event, const char *Line) { WiFiEventData.wifiConnectAttemptNeeded = true; return return_command_success(); } -const __FlashStringHelper * Command_Wifi_Disconnect(struct EventStruct *event, const char *Line) +const __FlashStringHelper* Command_Wifi_Disconnect(struct EventStruct *event, const char *Line) { RTC.clearLastWiFi(); // Force a WiFi scan WifiDisconnect(); @@ -75,13 +89,13 @@ const __FlashStringHelper * Command_Wifi_Disconnect(struct EventStruct *event, c return return_command_success(); } -const __FlashStringHelper * Command_Wifi_APMode(struct EventStruct *event, const char *Line) +const __FlashStringHelper* Command_Wifi_APMode(struct EventStruct *event, const char *Line) { setAP(true); return return_command_success(); } -const __FlashStringHelper * Command_Wifi_STAMode(struct EventStruct *event, const char *Line) +const __FlashStringHelper* Command_Wifi_STAMode(struct EventStruct *event, const char *Line) { setSTA(true); return return_command_success(); @@ -94,7 +108,7 @@ String Command_Wifi_Mode(struct EventStruct *event, const char *Line) if (GetArgv(Line, TmpStr1, 2)) { WiFiMode_t mode = WIFI_MODE_MAX; - if (event->Par1 > 0 && event->Par1 < WIFI_MODE_MAX) { + if ((event->Par1 > 0) && (event->Par1 < WIFI_MODE_MAX)) { mode = static_cast(event->Par1 - 1); } else { TmpStr1.toLowerCase(); @@ -116,7 +130,7 @@ String Command_Wifi_Mode(struct EventStruct *event, const char *Line) return return_command_success_str(); } -const __FlashStringHelper * Command_Wifi_AllowAP(struct EventStruct *event, const char* Line) +const __FlashStringHelper* Command_Wifi_AllowAP(struct EventStruct *event, const char *Line) { Settings.DoNotStartAP(false); return return_command_success(); @@ -124,7 +138,7 @@ const __FlashStringHelper * Command_Wifi_AllowAP(struct EventStruct *event, cons // FIXME: TD-er This is not an erase, but actually storing the current settings // in the wifi settings of the core library -const __FlashStringHelper * Command_WiFi_Erase(struct EventStruct *event, const char *Line) +const __FlashStringHelper* Command_WiFi_Erase(struct EventStruct *event, const char *Line) { WiFi.persistent(true); // use SDK storage of SSID/WPA parameters WifiDisconnect(); // this will store empty ssid/wpa into sdk storage diff --git a/src/src/Commands/WiFi.h b/src/src/Commands/WiFi.h index a7ad2e511..6cf4acf65 100644 --- a/src/src/Commands/WiFi.h +++ b/src/src/Commands/WiFi.h @@ -5,20 +5,34 @@ class String; -String Command_Wifi_SSID(struct EventStruct *event, const char* Line); -String Command_Wifi_Key(struct EventStruct *event, const char* Line); -String Command_Wifi_SSID2(struct EventStruct *event, const char* Line); -String Command_Wifi_Key2(struct EventStruct *event, const char* Line); -const __FlashStringHelper * Command_Wifi_Scan(struct EventStruct *event, const char* Line); -const __FlashStringHelper * Command_Wifi_Connect(struct EventStruct *event, const char* Line); -const __FlashStringHelper * Command_Wifi_Disconnect(struct EventStruct *event, const char* Line); -const __FlashStringHelper * Command_Wifi_APMode(struct EventStruct *event, const char* Line); -const __FlashStringHelper * Command_Wifi_STAMode(struct EventStruct *event, const char* Line); -String Command_Wifi_Mode(struct EventStruct *event, const char* Line); -const __FlashStringHelper * Command_Wifi_AllowAP(struct EventStruct *event, const char* Line); +String Command_Wifi_SSID(struct EventStruct *event, + const char *Line); +String Command_Wifi_Key(struct EventStruct *event, + const char *Line); +String Command_Wifi_SSID2(struct EventStruct *event, + const char *Line); +String Command_Wifi_Key2(struct EventStruct *event, + const char *Line); +String Command_Wifi_HiddenSSID(struct EventStruct *event, + const char *Line); +const __FlashStringHelper* Command_Wifi_Scan(struct EventStruct *event, + const char *Line); +const __FlashStringHelper* Command_Wifi_Connect(struct EventStruct *event, + const char *Line); +const __FlashStringHelper* Command_Wifi_Disconnect(struct EventStruct *event, + const char *Line); +const __FlashStringHelper* Command_Wifi_APMode(struct EventStruct *event, + const char *Line); +const __FlashStringHelper* Command_Wifi_STAMode(struct EventStruct *event, + const char *Line); +String Command_Wifi_Mode(struct EventStruct *event, + const char *Line); +const __FlashStringHelper* Command_Wifi_AllowAP(struct EventStruct *event, + const char *Line); // FIXME: TD-er This is not an erase, but actually storing the current settings // in the wifi settings of the core library -const __FlashStringHelper * Command_WiFi_Erase(struct EventStruct *event, const char* Line); +const __FlashStringHelper* Command_WiFi_Erase(struct EventStruct *event, + const char *Line); #endif // COMMAND_WIFI_H diff --git a/src/src/CustomBuild/define_plugin_sets.h b/src/src/CustomBuild/define_plugin_sets.h index 0a5517962..a53ef1cef 100644 --- a/src/src/CustomBuild/define_plugin_sets.h +++ b/src/src/CustomBuild/define_plugin_sets.h @@ -443,6 +443,11 @@ To create/register a plugin, you have to : #endif #define FEATURE_POST_TO_HTTP 0 // Disabled + #ifdef FEATURE_PUT_TO_HTTP + #undef FEATURE_PUT_TO_HTTP + #endif + #define FEATURE_PUT_TO_HTTP 0 // Disabled + #ifndef PLUGIN_SET_NONE #define PLUGIN_SET_NONE #endif @@ -1518,6 +1523,9 @@ To create/register a plugin, you have to : #ifndef USES_P145 #define USES_P145 // gasses MQxxx (MQ135, MQ3, etc) #endif + #ifndef USES_P150 + #define USES_P150 // TMP117 Temperature + #endif #ifndef USES_P151 #define USES_P151 // Environment - I2C Honeywell Pressure #endif @@ -1774,6 +1782,9 @@ To create/register a plugin, you have to : #ifndef USES_P148 #define USES_P148 // Sonoff POWR3xxD and THR3xxD display #endif + #ifndef USES_P150 + #define USES_P150 // TMP117 Temperature + #endif #ifndef USES_P151 #define USES_P151 // Environment - I2C Honeywell Pressure #endif @@ -2122,6 +2133,9 @@ To create/register a plugin, you have to : #ifndef USES_P146 #define USES_P146 // Cache Controller Reader #endif + #ifndef USES_P150 + #define USES_P150 // TMP117 Temperature + #endif #ifndef USES_P151 #define USES_P151 // Environment - I2C Honeywell Pressure #endif @@ -2245,6 +2259,10 @@ To create/register a plugin, you have to : #undef FEATURE_POST_TO_HTTP #endif #define FEATURE_POST_TO_HTTP 0 // Disabled + #ifdef FEATURE_PUT_TO_HTTP + #undef FEATURE_PUT_TO_HTTP + #endif + #define FEATURE_PUT_TO_HTTP 0 // Disabled #endif @@ -2775,6 +2793,10 @@ To create/register a plugin, you have to : #define FEATURE_POST_TO_HTTP 1 // Enabled by default #endif +#ifndef FEATURE_PUT_TO_HTTP + #define FEATURE_PUT_TO_HTTP 1 // Enabled by default +#endif + #ifndef FEATURE_HTTP_CLIENT #define FEATURE_HTTP_CLIENT 0 // Disable by default #endif @@ -2804,7 +2826,7 @@ To create/register a plugin, you have to : #define FEATURE_I2C_GET_ADDRESS 1 // Needed by FEATURE_I2C_DEVICE_CHECK #endif -#if !FEATURE_HTTP_CLIENT && (defined(USES_C001) || defined(USES_C008) || defined(USES_C009) || defined(USES_C011) || (defined(FEATURE_SEND_TO_HTTP) && FEATURE_SEND_TO_HTTP) || (defined(FEATURE_POST_TO_HTTP) && FEATURE_POST_TO_HTTP) || (defined(FEATURE_DOWNLOAD) && FEATURE_DOWNLOAD) || (defined(FEATURE_SETTINGS_ARCHIVE) && FEATURE_SETTINGS_ARCHIVE)) +#if !FEATURE_HTTP_CLIENT && (defined(USES_C001) || defined(USES_C008) || defined(USES_C009) || defined(USES_C011) || (defined(FEATURE_SEND_TO_HTTP) && FEATURE_SEND_TO_HTTP) || (defined(FEATURE_POST_TO_HTTP) && FEATURE_POST_TO_HTTP) || (defined(FEATURE_PUT_TO_HTTP) && FEATURE_PUT_TO_HTTP) || (defined(FEATURE_DOWNLOAD) && FEATURE_DOWNLOAD) || (defined(FEATURE_SETTINGS_ARCHIVE) && FEATURE_SETTINGS_ARCHIVE)) #undef FEATURE_HTTP_CLIENT #define FEATURE_HTTP_CLIENT 1 // Enable because required for these controllers/features #endif diff --git a/src/src/PluginStructs/P106_data_struct.cpp b/src/src/PluginStructs/P106_data_struct.cpp index 72037a303..65c7e0efc 100644 --- a/src/src/PluginStructs/P106_data_struct.cpp +++ b/src/src/PluginStructs/P106_data_struct.cpp @@ -16,10 +16,10 @@ bool P106_data_struct::begin(uint8_t addr, bool initSettings) if (initialized) { // Set up oversampling and filter initialization - bme.setTemperatureOversampling(BME680_OS_8X); - bme.setHumidityOversampling(BME680_OS_2X); - bme.setPressureOversampling(BME680_OS_4X); - bme.setIIRFilterSize(BME680_FILTER_SIZE_3); + bme.setTemperatureOversampling(BME68X_OS_8X); + bme.setHumidityOversampling(BME68X_OS_2X); + bme.setPressureOversampling(BME68X_OS_4X); + bme.setIIRFilterSize(BME68X_FILTER_SIZE_3); bme.setGasHeater(320, 150); // 320*C for 150 ms } } diff --git a/src/src/PluginStructs/P106_data_struct.h b/src/src/PluginStructs/P106_data_struct.h index e2057be90..e2c53ca94 100644 --- a/src/src/PluginStructs/P106_data_struct.h +++ b/src/src/PluginStructs/P106_data_struct.h @@ -4,6 +4,14 @@ #include "../../_Plugin_Helper.h" #ifdef USES_P106 +# define P106_I2C_ADDRESS PCONFIG(0) +# define P106_ALTITUDE PCONFIG(1) +# define P106_OPTIONS PCONFIG_ULONG(0) // Plugin options +// Plugin options: +# define P106_OPT_GAS_OHM 0 // Use Raw value, default off + +# define P106_GET_OPT_GAS_OHM bitRead(P106_OPTIONS, P106_OPT_GAS_OHM) +# define P106_SET_OPT_GAS_OHM(x) bitWrite(P106_OPTIONS, P106_OPT_GAS_OHM, x) # include # include diff --git a/src/src/PluginStructs/P145_data_struct.cpp b/src/src/PluginStructs/P145_data_struct.cpp index 164c6f7d2..b3ca1ca00 100644 --- a/src/src/PluginStructs/P145_data_struct.cpp +++ b/src/src/PluginStructs/P145_data_struct.cpp @@ -47,167 +47,167 @@ // This table is stored in PROGMEM to save space in RAM // The data for the selected sensor type is copied to RAM, see P145_data_struct /******************************************************************************/ -const struct P145_SENSORDEF sensorDefs[] PROGMEM = +const P145_SENSORDEF sensorDefs[] PROGMEM { // User defined, output plain ratio (Rsensor/Rzero) { - 0.0f, // cleanRatio - 0.0f, // PARA scaling factor value - 0.0f, // PARB exponent value - 0.0f, // CORA - 0.0f, // CORB - 0.0f, // CORC - 0.0f, // CORD - 0.0f, // CORE - 0.0f, // CORF - 0.0f, // CORG - p145AlgNone, // preferred/tuned algorithm - P145_SENSUSER, // Name - P145_GASUSER, // gas + .cleanRatio = 0.0f, + .para = 0.0f, + .parb = 0.0f, + .cora = 0.0f, + .corb = 0.0f, + .corc = 0.0f, + .cord = 0.0f, + .core = 0.0f, + .corf = 0.0f, + .corg = 0.0f, + .alg = p145AlgNone, + .name = P145_SENSUSER, + .gas = P145_GASUSER, }, // *** MQ-135 - CO2 *** { - 0.0f, // cleanRatio - 116.6020682f, // PARA scaling factor value - 2.769034857f, // PARB exponent value - 0.00035f, // CORA - 0.02718f, // CORB - 1.39538f, // CORC - 0.0018f, // CORD - -0.003333333f,// CORE - -0.001923077f,// CORF - 1.130128205f, // CORG - p145AlgA, // preferred/tuned algorithm - P145_SENSMQ135, // Name - P145_GASCO2, // gas + .cleanRatio = 0.0f, + .para = 116.6020682f, + .parb = 2.769034857f, + .cora = 0.00035f, + .corb = 0.02718f, + .corc = 1.39538f, + .cord = 0.0018f, + .core = -0.003333333f, + .corf = -0.001923077f, + .corg = 1.130128205f, + .alg = p145AlgA, + .name = P145_SENSMQ135, + .gas = P145_GASCO2, }, // *** MQ-2 - H2 *** { - 9.83f, // cleanRatio - 987.99f, // PARA scaling factor - -2.162f, // PARB exponent value - 0.0f, // CORA - 0.0f, // CORB - 0.0f, // CORC - 0.0f, // CORD - 0.0f, // CORE - 0.0f, // CORF - 0.0f, // CORG - p145AlgB, // preferred/tuned algorithm - P145_SENSMQ2, // Name - P145_GASH2, // gas + .cleanRatio = 9.83f, + .para = 987.99f, + .parb = -2.162f, + .cora = 0.0f, + .corb = 0.0f, + .corc = 0.0f, + .cord = 0.0f, + .core = 0.0f, + .corf = 0.0f, + .corg = 0.0f, + .alg = p145AlgB, + .name = P145_SENSMQ2, + .gas = P145_GASH2, }, // *** MQ-3 - alcohol *** { - 60.0f, // cleanRatio - 0.3934f, // PARA scaling factor - -1.504f, // PARB exponent value - 0.0f, // CORA - 0.0f, // CORB - 0.0f, // CORC - 0.0f, // CORD - 0.0f, // CORE - 0.0f, // CORF - 0.0f, // CORG - p145AlgB, // preferred/tuned algorithm - P145_SENSMQ3, // Name - P145_GASALCOHOL, // gas + .cleanRatio = 60.0f, + .para = 0.3934f, + .parb = -1.504f, + .cora = 0.0f, + .corb = 0.0f, + .corc = 0.0f, + .cord = 0.0f, + .core = 0.0f, + .corf = 0.0f, + .corg = 0.0f, + .alg = p145AlgB, + .name = P145_SENSMQ3, + .gas = P145_GASALCOHOL, }, // *** MQ-4 - CH4 *** { - 4.4f, // cleanRatio - 1012.7f, // PARA scaling - -2.786f, // PARB exponent - 0.0f, // CORA - 0.0f, // CORB - 0.0f, // CORC - 0.0f, // CORD - 0.0f, // CORE - 0.0f, // CORF - 0.0f, // CORG - p145AlgB, // preferred/tuned algorithm - P145_SENSMQ4, // Name - P145_GASCH4, // gas + .cleanRatio = 4.4f, + .para = 1012.7f, + .parb = -2.786f, + .cora = 0.0f, + .corb = 0.0f, + .corc = 0.0f, + .cord = 0.0f, + .core = 0.0f, + .corf = 0.0f, + .corg = 0.0f, + .alg = p145AlgB, + .name = P145_SENSMQ4, + .gas = P145_GASCH4, }, // *** MQ-5 - H2 *** { - 5.5f, // cleanRatio - 1163.8f, // PARA scaling - -3.874f, // PARB exponent - 0.0f, // CORA - 0.0f, // CORB - 0.0f, // CORC - 0.0f, // CORD - 0.0f, // CORE - 0.0f, // CORF - 0.0f, // CORG - p145AlgB, // preferred/tuned algorithm - P145_SENSMQ5, // Name - P145_GASCH4, // gas + .cleanRatio = 5.5f, + .para = 1163.8f, + .parb = -3.874f, + .cora = 0.0f, + .corb = 0.0f, + .corc = 0.0f, + .cord = 0.0f, + .core = 0.0f, + .corf = 0.0f, + .corg = 0.0f, + .alg = p145AlgB, + .name = P145_SENSMQ5, + .gas = P145_GASCH4, }, // *** MQ-5 - LPG *** { - 5.5f, // cleanRatio - 80.897f, // PARA scaling - -2.431f, // PARB exponent - 0.0f, // CORA - 0.0f, // CORB - 0.0f, // CORC - 0.0f, // CORD - 0.0f, // CORE - 0.0f, // CORF - 0.0f, // CORG - p145AlgB, // preferred/tuned algorithm - P145_SENSMQ5, // Name - P145_GASLPG, // gas + .cleanRatio = 5.5f, + .para = 80.897f, + .parb = -2.431f, + .cora = 0.0f, + .corb = 0.0f, + .corc = 0.0f, + .cord = 0.0f, + .core = 0.0f, + .corf = 0.0f, + .corg = 0.0f, + .alg = p145AlgB, + .name = P145_SENSMQ5, + .gas = P145_GASLPG, }, // *** MQ-6 - LPG *** { - 10.0f, // cleanRatio - 1009.2f, // PARA scaling - -2.35f, // PARB exponent - 0.0f, // CORA - 0.0f, // CORB - 0.0f, // CORC - 0.0f, // CORD - 0.0f, // CORE - 0.0f, // CORF - 0.0f, // CORG - p145AlgB, // preferred/tuned algorithm - P145_SENSMQ6, // Name - P145_GASLPG, // gas + .cleanRatio = 10.0f, + .para = 1009.2f, + .parb = -2.35f, + .cora = 0.0f, + .corb = 0.0f, + .corc = 0.0f, + .cord = 0.0f, + .core = 0.0f, + .corf = 0.0f, + .corg = 0.0f, + .alg = p145AlgB, + .name = P145_SENSMQ6, + .gas = P145_GASLPG, }, // *** MQ-7 - CO *** { - 27.5f, // cleanRatio - 491204.0f, // PARA scaling - -5.826f, // PARB exponent - 0.0f, // CORA - 0.0f, // CORB - 0.0f, // CORC - 0.0f, // CORD - 0.0f, // CORE - 0.0f, // CORF - 0.0f, // CORG - p145AlgB, // preferred/tuned algorithm - P145_SENSMQ7, // Name - P145_GASCO, // gas + .cleanRatio = 27.5f, + .para = 491204.0f, + .parb = -5.826f, + .cora = 0.0f, + .corb = 0.0f, + .corc = 0.0f, + .cord = 0.0f, + .core = 0.0f, + .corf = 0.0f, + .corg = 0.0f, + .alg = p145AlgB, + .name = P145_SENSMQ7, + .gas = P145_GASCO, }, // *** MQ-8 - H2 *** { - 70.0f, // cleanRatio - 976.97f, // PARA scaling - -0.688f, // PARB exponent - 0.0f, // CORA - 0.0f, // CORB - 0.0f, // CORC - 0.0f, // CORD - 0.0f, // CORE - 0.0f, // CORF - 0.0f, // CORG - p145AlgB, // preferred/tuned algorithm - P145_SENSMQ8, // Name - P145_GASH2, // gas + .cleanRatio = 70.0f, + .para = 976.97f, + .parb = -0.688f, + .cora = 0.0f, + .corb = 0.0f, + .corc = 0.0f, + .cord = 0.0f, + .core = 0.0f, + .corf = 0.0f, + .corg = 0.0f, + .alg = p145AlgB, + .name = P145_SENSMQ8, + .gas = P145_GASH2, } }; /// @brief The number of types stored in the sensorDefs[] table diff --git a/src/src/PluginStructs/P145_data_struct.h b/src/src/PluginStructs/P145_data_struct.h index 42f29e6ad..ec4385de5 100644 --- a/src/src/PluginStructs/P145_data_struct.h +++ b/src/src/PluginStructs/P145_data_struct.h @@ -51,8 +51,8 @@ struct P145_SENSORDEF float corf; // CORF float corg; // CORG P145_algorithm alg; // Preferred/tuned algorithm - int name; // Sensor type name - int gas; // Measured gas + int name; // Sensor type name + int gas; // Measured gas }; // State for heater control algorithm diff --git a/src/src/PluginStructs/P150_data_struct.cpp b/src/src/PluginStructs/P150_data_struct.cpp new file mode 100644 index 000000000..b48b5206e --- /dev/null +++ b/src/src/PluginStructs/P150_data_struct.cpp @@ -0,0 +1,138 @@ +#include "../PluginStructs/P150_data_struct.h" + +#ifdef USES_P150 + +P150_data_struct::P150_data_struct(struct EventStruct *event) { + _deviceAddress = P150_I2C_ADDRESS; + _config = P150_CONFIG; + _temperatureOffset = P150_TEMPERATURE_OFFSET / 10.0f; // Per 0.1 degree + _rawEnabled = P150_GET_OPT_ENABLE_RAW; + _logEnabled = P150_GET_OPT_ENABLE_LOG; + # if P150_USE_EXTRA_LOG + _extraLog = P150_GET_OPT_EXTRA_LOG; + # endif // if P150_USE_EXTRA_LOG +} + +/** + * init(): Initialize sensor + * - Set config + * - Set temperature offset if <> 0 + * Will fail if no sensor is found, or the device id doesn't match (0x0117) + */ +bool P150_data_struct::init() { + // make sure the TMP will acknowledge over I2C + if ((_deviceAddress < 0) || (I2C_wakeup(_deviceAddress) != 0)) { + return false; + } + + uint16_t deviceID = I2C_read16_reg(_deviceAddress, TMP117_DEVICE_ID); // reads registers into rawData + + // make sure the device ID reported by the TMP is correct + // should always be 0x0117 + if (deviceID != TMP117_DEVICE_ID_VALUE) { + addLog(LOG_LEVEL_ERROR, concat(F("TMP117: Device ID mismatch: "), formatToHex(deviceID, 4))); + return false; + } + + setConfig(); + + if (!essentiallyZero(_temperatureOffset)) { + setTemperatureOffset(_temperatureOffset); // set offset + } + + return true; // returns true if all the checks pass +} + +/** + * Set configuration, also used to start a one-shot conversion + */ +void P150_data_struct::setConfig() { + uint16_t config = I2C_read16_reg(_deviceAddress, TMP117_CONFIGURATION); // Read current configuration + + config &= P150_CONFIG_RESET_MASK; // Reset the bits we want to update + config |= _config; // Apply (new) config settings + I2C_write16_reg(_deviceAddress, TMP117_CONFIGURATION, config); // Update config +} + +/** + * plugin_read(): Fetch last read values + */ +bool P150_data_struct::plugin_read(struct EventStruct *event) { + if (_readValid && definitelyGreaterThan(_finalTempC, -256.0f)) { + UserVar[event->BaseVarIndex] = _finalTempC; + UserVar[event->BaseVarIndex + 1] = _digitalTempC; + + if (_logEnabled && loglevelActiveFor(LOG_LEVEL_INFO)) { + String log = concat(F("TMP117: Temperature: "), formatUserVarNoCheck(event, 0)); + log += 'C'; + + if (_rawEnabled) { + log += concat(F(", Raw: "), formatUserVarNoCheck(event, 1)); + } + addLogMove(LOG_LEVEL_INFO, log); + } + + if (P150_GET_CONF_CONVERSION_MODE == P150_CONVERSION_ONE_SHOT) { + setConfig(); // Start the next one-shot measurement + } + return true; + } + return false; +} + +/** + * plugin_once_a_second(): Read sensor if data is available + * Will return true if data is actually available and valid + */ +bool P150_data_struct::plugin_once_a_second(struct EventStruct *event) { + if (dataReady()) { + readTemp(); + _readValid = true; + + # if P150_USE_EXTRA_LOG + + if (_extraLog && loglevelActiveFor(LOG_LEVEL_INFO)) { + String log = concat(F("TMP117: Read temp: "), toString(_finalTempC, 2)); + log += 'C'; + log += concat(F(", raw: "), static_cast(_digitalTempC)); + + if (P150_GET_CONF_CONVERSION_MODE == P150_CONVERSION_ONE_SHOT) { + log += F(" (one-shot)"); + } + addLog(LOG_LEVEL_INFO, log); + } + # endif // if P150_USE_EXTRA_LOG + } + return false; +} + +/** + * Private: readTemp() + * Read raw temperature value and calculate final temperature + */ +float P150_data_struct::readTemp() { + _digitalTempC = I2C_read16_reg(_deviceAddress, TMP117_TEMP_RESULT); + + _finalTempC = _digitalTempC * TMP117_RESOLUTION; // Multiplied by the resolution for digital to final temp + + return _finalTempC; +} + +void P150_data_struct::setTemperatureOffset(float offset) { + int16_t resolutionOffset = offset / TMP117_RESOLUTION; // Divide by resolution to send to the sensor + + I2C_write16_reg(_deviceAddress, TMP117_TEMP_OFFSET, resolutionOffset); // Write to the offset temperature register +} + +/** + * Private: dataReady() + * Check if sensor os ready processing the measurement(s) + */ +bool P150_data_struct::dataReady() { + uint16_t response = I2C_read16_reg(_deviceAddress, TMP117_CONFIGURATION); + + // If statement to see if the 13th bit of the register is 1 or not + return bitRead(response, 13); +} + +#endif // ifdef USES_P150 diff --git a/src/src/PluginStructs/P150_data_struct.h b/src/src/PluginStructs/P150_data_struct.h new file mode 100644 index 000000000..2061126e9 --- /dev/null +++ b/src/src/PluginStructs/P150_data_struct.h @@ -0,0 +1,114 @@ +#ifndef PLUGINSTRUCTS_P150_DATA_STRUCT_H +#define PLUGINSTRUCTS_P150_DATA_STRUCT_H + +#include "../../_Plugin_Helper.h" +#ifdef USES_P150 + +# define P150_I2C_ADDRESS PCONFIG(0) +# define P150_TEMPERATURE_OFFSET PCONFIG(1) +# define P150_CONFIG PCONFIG_ULONG(0) // Sensor config +# define P150_OPTIONS PCONFIG_ULONG(1) // Plugin options + +# define P150_USE_EXTRA_LOG 1 // Enable(1)/disable(0) low-level logging + +# define P150_CONFIG_RESET_MASK 0b1111000000011111 // Reset the bits we need to overwrite + +// Sensor configuration: +# define P150_CONF_CONVERSION_MODE 10 // Conversion mode 00/10 = Continuous, 01 = Shutdown, 11 = One Shot +# define P150_CONVERSION_CONTINUOUS 0b00 +# define P150_CONVERSION_SHUTDOWN 0b01 // Not available in settings +# define P150_CONVERSION_ONE_SHOT 0b11 + +# define P150_CONF_CYCLE_BITS 7 // 3 bits: Cycle mode 000 = 15.5 msec, 001 = 125 msec, 010 = 250 msec, + // 011 = 500 msec, 100 = 1 sec, 101 = 4 sec, 110 = 8 sec, 111 = 16 sec +# define P150_CYCLE_15_5_MSEC 0b000 +# define P150_CYCLE_125_MSEC 0b001 +# define P150_CYCLE_250_MSEC 0b010 +# define P150_CYCLE_500_MSEC 0b011 +# define P150_CYCLE_1_SEC 0b100 +# define P150_CYCLE_4_SEC 0b101 +# define P150_CYCLE_8_SEC 0b110 +# define P150_CYCLE_16_SEC 0b111 + +# define P150_CONF_AVERAGING 5 // 2 bits: Averaging mode 00 = None, 01 = 8 samples, 10 = 32 samples 11 = 64 samples +# define P150_AVERAGING_NONE 0b00 +# define P150_AVERAGING_8_SAMPLES 0b01 +# define P150_AVERAGING_32_SAMPLES 0b10 +# define P150_AVERAGING_64_SAMPLES 0b11 + +# define P150_GET_CONF_CONVERSION_MODE get2BitFromUL(P150_CONFIG, P150_CONF_CONVERSION_MODE) +# define P150_SET_CONF_CONVERSION_MODE(x) set2BitToUL(P150_CONFIG, \ + P150_CONF_CONVERSION_MODE, \ + x ? P150_CONVERSION_ONE_SHOT : P150_CONVERSION_CONTINUOUS) +# define P150_GET_CONF_CYCLE_BITS get3BitFromUL(P150_CONFIG, P150_CONF_CYCLE_BITS) +# define P150_SET_CONF_CYCLE_BITS(x) set3BitToUL(P150_CONFIG, P150_CONF_CYCLE_BITS, x) +# define P150_GET_CONF_AVERAGING get2BitFromUL(P150_CONFIG, P150_CONF_AVERAGING) +# define P150_SET_CONF_AVERAGING(x) set2BitToUL(P150_CONFIG, P150_CONF_AVERAGING, x) + +// Plugin options: +# define P150_OPT_ENABLE_RAW 0 // Use Raw value, default on +# define P150_OPT_ENABLE_LOG 1 // Log measured values, default on +# if P150_USE_EXTRA_LOG +# define P150_OPT_EXTRA_LOG 2 // Log low-level measured values, default off +# endif // if P150_USE_EXTRA_LOG + +# define P150_GET_OPT_ENABLE_RAW bitRead(P150_OPTIONS, P150_OPT_ENABLE_RAW) +# define P150_SET_OPT_ENABLE_RAW(x) bitWrite(P150_OPTIONS, P150_OPT_ENABLE_RAW, x) +# define P150_GET_OPT_ENABLE_LOG bitRead(P150_OPTIONS, P150_OPT_ENABLE_LOG) +# define P150_SET_OPT_ENABLE_LOG(x) bitWrite(P150_OPTIONS, P150_OPT_ENABLE_LOG, x) +# if P150_USE_EXTRA_LOG +# define P150_GET_OPT_EXTRA_LOG bitRead(P150_OPTIONS, P150_OPT_EXTRA_LOG) +# define P150_SET_OPT_EXTRA_LOG(x) bitWrite(P150_OPTIONS, P150_OPT_EXTRA_LOG, x) +# endif // if P150_USE_EXTRA_LOG + +# define TMP117_RESOLUTION 0.0078125f // Resolution of the device, see specifications +# define TMP117_DEVICE_ID_VALUE 0x0117 // Value found in the device ID register on reset + +enum TMP117_register { + TMP117_TEMP_RESULT = 0x00, + TMP117_CONFIGURATION = 0x01, + + // TMP117_T_HIGH_LIMIT = 0x02, // Unused + // TMP117_T_LOW_LIMIT = 0x03, + // TMP117_EEPROM_UL = 0x04, + // TMP117_EEPROM1 = 0x05, + // TMP117_EEPROM2 = 0x06, + TMP117_TEMP_OFFSET = 0x07, + + // TMP117_EEPROM3 = 0x08, + TMP117_DEVICE_ID = 0x0F, +}; + +struct P150_data_struct : public PluginTaskData_base { + P150_data_struct() = delete; + P150_data_struct(struct EventStruct *event); + + virtual ~P150_data_struct() = default; + + bool init(); + void setConfig(); + bool plugin_read(struct EventStruct *event); + bool plugin_once_a_second(struct EventStruct *event); + +private: + + float readTemp(); + void setTemperatureOffset(float offset); + bool dataReady(); + + uint16_t _config = 0; + float _temperatureOffset = 0.0f; + int8_t _deviceAddress = -1; + bool _rawEnabled = false; + bool _logEnabled = false; + # if P150_USE_EXTRA_LOG + bool _extraLog = false; + # endif // if P150_USE_EXTRA_LOG + + int16_t _digitalTempC = 0; + float _finalTempC = 0.0f; + bool _readValid = false; +}; + +#endif // ifdef USES_P150 +#endif // ifndef PLUGINSTRUCTS_P150_DATA_STRUCT_H diff --git a/src/src/WebServer/I2C_Scanner.cpp b/src/src/WebServer/I2C_Scanner.cpp index 7ed4de1c9..0510b2e88 100644 --- a/src/src/WebServer/I2C_Scanner.cpp +++ b/src/src/WebServer/I2C_Scanner.cpp @@ -260,10 +260,10 @@ String getKnownI2Cdevice(uint8_t address) { case 0x48: case 0x4A: case 0x4B: - result += F("PCF8591,ADS1115,LM75A,INA219"); + result += F("PCF8591,ADS1115,LM75A,INA219,TMP117"); break; case 0x49: - result += F("PCF8591,ADS1115,TSL2561,LM75A,INA219"); + result += F("PCF8591,ADS1115,TSL2561,LM75A,INA219,TMP117"); break; case 0x4C: case 0x4E: