bme280 driver in Lua+C

This commit is contained in:
Lukáš Voborský 2020-05-27 23:51:19 +02:00 committed by Nathaniel Wesley Filardo
parent 54e8696ac9
commit b9091784ae
8 changed files with 904 additions and 0 deletions

View File

@ -16,6 +16,7 @@
//#define LUA_USE_MODULES_BLOOM //#define LUA_USE_MODULES_BLOOM
//#define LUA_USE_MODULES_BMP085 //#define LUA_USE_MODULES_BMP085
//#define LUA_USE_MODULES_BME280 //#define LUA_USE_MODULES_BME280
//#define LUA_USE_MODULES_BME280_MATH
//#define LUA_USE_MODULES_BME680 //#define LUA_USE_MODULES_BME680
//#define LUA_USE_MODULES_COAP //#define LUA_USE_MODULES_COAP
//#define LUA_USE_MODULES_COLOR_UTILS //#define LUA_USE_MODULES_COLOR_UTILS

View File

@ -236,6 +236,8 @@ static int bme280_lua_setup(lua_State* L) {
uint8_t const bit3 = 0b111; uint8_t const bit3 = 0b111;
uint8_t const bit2 = 0b11; uint8_t const bit2 = 0b11;
platform_print_deprecation_note("bme280", "soon. Use bme280math and bme280 Lua module instead");
bme280_mode = (!lua_isnumber(L, 4)?BME280_NORMAL_MODE:(luaL_checkinteger(L, 4)&bit2)) // 4-th parameter: power mode bme280_mode = (!lua_isnumber(L, 4)?BME280_NORMAL_MODE:(luaL_checkinteger(L, 4)&bit2)) // 4-th parameter: power mode
| ((!lua_isnumber(L, 2)?BME280_OVERSAMP_16X:(luaL_checkinteger(L, 2)&bit3)) << 2) // 2-nd parameter: pressure oversampling | ((!lua_isnumber(L, 2)?BME280_OVERSAMP_16X:(luaL_checkinteger(L, 2)&bit3)) << 2) // 2-nd parameter: pressure oversampling
| ((!lua_isnumber(L, 1)?BME280_OVERSAMP_16X:(luaL_checkinteger(L, 1)&bit3)) << 5); // 1-st parameter: temperature oversampling | ((!lua_isnumber(L, 1)?BME280_OVERSAMP_16X:(luaL_checkinteger(L, 1)&bit3)) << 5); // 1-st parameter: temperature oversampling

357
app/modules/bme280_math.c Normal file
View File

@ -0,0 +1,357 @@
// ***************************************************************************
// BMP280 module for ESP8266 with nodeMCU
//
// Written by Lukas Voborsky, @voborsky
//
// MIT license, http://opensource.org/licenses/MIT
// ***************************************************************************
// #define NODE_DEBUG
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "user_interface.h"
#include <math.h>
/****************************************************/
/**\name registers definition */
/***************************************************/
#define BME280_REGISTER_CONTROL (0xF4)
#define BME280_REGISTER_CONTROL_HUM (0xF2)
#define BME280_REGISTER_CONFIG (0xF5)
#define BME280_REGISTER_CHIPID (0xD0)
#define BME280_REGISTER_VERSION (0xD1)
#define BME280_REGISTER_SOFTRESET (0xE0)
#define BME280_REGISTER_CAL26 (0xE1)
#define BME280_REGISTER_PRESS (0xF7) // 0xF7-0xF9
#define BME280_REGISTER_TEMP (0xFA) // 0xFA-0xFC
#define BME280_REGISTER_HUM (0xFD) // 0xFD-0xFE
#define BME280_REGISTER_DIG_T (0x88) // 0x88-0x8D ( 6)
#define BME280_REGISTER_DIG_P (0x8E) // 0x8E-0x9F (18)
#define BME280_REGISTER_DIG_H1 (0xA1) // 0xA1 ( 1)
#define BME280_REGISTER_DIG_H2 (0xE1) // 0xE1-0xE7 ( 7)
/****************************************************/
/**\name I2C ADDRESS DEFINITIONS */
/***************************************************/
#define BME280_I2C_ADDRESS1 (0x76)
#define BME280_I2C_ADDRESS2 (0x77)
/****************************************************/
/**\name POWER MODE DEFINITIONS */
/***************************************************/
/* Sensor Specific constants */
#define BME280_SLEEP_MODE (0x00)
#define BME280_FORCED_MODE (0x01)
#define BME280_NORMAL_MODE (0x03)
#define BME280_SOFT_RESET_CODE (0xB6)
/****************************************************/
/**\name OVER SAMPLING DEFINITIONS */
/***************************************************/
#define BME280_OVERSAMP_1X (0x01)
#define BME280_OVERSAMP_2X (0x02)
#define BME280_OVERSAMP_4X (0x03)
#define BME280_OVERSAMP_8X (0x04)
#define BME280_OVERSAMP_16X (0x05)
/****************************************************/
/**\name STANDBY TIME DEFINITIONS */
/***************************************************/
#define BME280_STANDBY_TIME_1_MS (0x00)
#define BME280_STANDBY_TIME_63_MS (0x01)
#define BME280_STANDBY_TIME_125_MS (0x02)
#define BME280_STANDBY_TIME_250_MS (0x03)
#define BME280_STANDBY_TIME_500_MS (0x04)
#define BME280_STANDBY_TIME_1000_MS (0x05)
#define BME280_STANDBY_TIME_10_MS (0x06)
#define BME280_STANDBY_TIME_20_MS (0x07)
/****************************************************/
/**\name FILTER DEFINITIONS */
/***************************************************/
#define BME280_FILTER_COEFF_OFF (0x00)
#define BME280_FILTER_COEFF_2 (0x01)
#define BME280_FILTER_COEFF_4 (0x02)
#define BME280_FILTER_COEFF_8 (0x03)
#define BME280_FILTER_COEFF_16 (0x04)
/****************************************************/
/**\data type definition */
/***************************************************/
#define BME280_S32_t int32_t
#define BME280_U32_t uint32_t
#define BME280_S64_t int64_t
#define BME280_SAMPLING_DELAY 113 //maximum measurement time in ms for maximum oversampling for all measures = 1.25 + 2.3*16 + 2.3*16 + 0.575 + 2.3*16 + 0.575 ms
// #define r16s(reg) ((int16_t)r16u(reg))
// #define r16sLE(reg) ((int16_t)r16uLE(reg))
// #define bme280_adc_P(void) r24u(BME280_REGISTER_PRESS)
// #define bme280_adc_T(void) r24u(BME280_REGISTER_TEMP)
// #define bme280_adc_H(void) r16u(BME280_REGISTER_HUM)
typedef struct {
uint16_t dig_T1;
int16_t dig_T2;
int16_t dig_T3;
uint16_t dig_P1;
int16_t dig_P2;
int16_t dig_P3;
int16_t dig_P4;
int16_t dig_P5;
int16_t dig_P6;
int16_t dig_P7;
int16_t dig_P8;
int16_t dig_P9;
uint8_t dig_H1;
int16_t dig_H2;
uint8_t dig_H3;
int16_t dig_H4;
int16_t dig_H5;
int8_t dig_H6;
} bme280_data_t;
typedef bme280_data_t* bme280_data_p;
bme280_data_p bme280_data;
BME280_S32_t bme280_t_fine;
// Returns temperature in DegC, resolution is 0.01 DegC. Output value of “5123” equals 51.23 DegC.
// t_fine carries fine temperature as global value
BME280_S32_t bme280_compensate_T(BME280_S32_t adc_T) {
BME280_S32_t var1, var2, T;
var1 = ((((adc_T>>3) - ((BME280_S32_t)(*bme280_data).dig_T1<<1))) * ((BME280_S32_t)(*bme280_data).dig_T2)) >> 11;
var2 = (((((adc_T>>4) - ((BME280_S32_t)(*bme280_data).dig_T1)) * ((adc_T>>4) - ((BME280_S32_t)(*bme280_data).dig_T1))) >> 12) *
((BME280_S32_t)(*bme280_data).dig_T3)) >> 14;
bme280_t_fine = var1 + var2;
T = (bme280_t_fine * 5 + 128) >> 8;
return T;
}
// Returns pressure in Pa as unsigned 32 bit integer in Q24.8 format (24 integer bits and 8 fractional bits).
// Output value of “24674867” represents 24674867/256 = 96386.2 Pa = 963.862 hPa
BME280_U32_t bme280_compensate_P(BME280_S32_t adc_P) {
BME280_S64_t var1, var2, p;
var1 = ((BME280_S64_t)bme280_t_fine) - 128000;
var2 = var1 * var1 * (BME280_S64_t)(*bme280_data).dig_P6;
var2 = var2 + ((var1*(BME280_S64_t)(*bme280_data).dig_P5)<<17);
var2 = var2 + (((BME280_S64_t)(*bme280_data).dig_P4)<<35);
var1 = ((var1 * var1 * (BME280_S64_t)(*bme280_data).dig_P3)>>8) + ((var1 * (BME280_S64_t)(*bme280_data).dig_P2)<<12);
var1 = (((((BME280_S64_t)1)<<47)+var1))*((BME280_S64_t)(*bme280_data).dig_P1)>>33;
if (var1 == 0) {
return 0; // avoid exception caused by division by zero
}
p = 1048576-adc_P;
p = (((p<<31)-var2)*3125)/var1;
var1 = (((BME280_S64_t)(*bme280_data).dig_P9) * (p>>13) * (p>>13)) >> 25;
var2 = (((BME280_S64_t)(*bme280_data).dig_P8) * p) >> 19;
p = ((p + var1 + var2) >> 8) + (((BME280_S64_t)(*bme280_data).dig_P7)<<4);
p = (p * 10) >> 8;
return (BME280_U32_t)p;
}
// Returns humidity in %RH as unsigned 32 bit integer in Q22.10 format (22 integer and 10 fractional bits).
// Output value of “47445” represents 47445/1024 = 46.333 %RH
BME280_U32_t bme280_compensate_H(BME280_S32_t adc_H) {
BME280_S32_t v_x1_u32r;
v_x1_u32r = (bme280_t_fine - ((BME280_S32_t)76800));
v_x1_u32r = (((((adc_H << 14) - (((BME280_S32_t)(*bme280_data).dig_H4) << 20) - (((BME280_S32_t)(*bme280_data).dig_H5) * v_x1_u32r)) +
((BME280_S32_t)16384)) >> 15) * (((((((v_x1_u32r * ((BME280_S32_t)(*bme280_data).dig_H6)) >> 10) * (((v_x1_u32r *
((BME280_S32_t)(*bme280_data).dig_H3)) >> 11) + ((BME280_S32_t)32768))) >> 10) + ((BME280_S32_t)2097152)) *
((BME280_S32_t)(*bme280_data).dig_H2) + 8192) >> 14));
v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) * ((BME280_S32_t)(*bme280_data).dig_H1)) >> 4));
v_x1_u32r = (v_x1_u32r < 0 ? 0 : v_x1_u32r);
v_x1_u32r = (v_x1_u32r > 419430400 ? 419430400 : v_x1_u32r);
v_x1_u32r = v_x1_u32r>>12;
return (BME280_U32_t)((v_x1_u32r * 1000)>>10);
}
double ln(double x) {
double y = (x-1)/(x+1);
double y2 = y*y;
double r = 0;
for (int8_t i=33; i>0; i-=2) { //we've got the power
r = 1.0/(double)i + y2 * r;
}
return 2*y*r;
}
uint32_t bme280_h = 0; // buffer last qfe2qnh calculation
double bme280_hc = 1.0;
double bme280_qfe2qnh(double qfe, double h) {
double hc;
if (bme280_h == h) {
hc = bme280_hc;
} else {
hc = pow((double)(1.0 - 2.25577e-5 * h), (double)(-5.25588));
bme280_hc = hc; bme280_h = h;
}
double qnh = (double)qfe * hc;
return qnh;
}
int bme280_lua_setup(lua_State* L) {
uint8_t bme280_mode = 0; // stores oversampling settings
uint8_t bme280_ossh = 0; // stores humidity oversampling settings
uint8_t config;
uint8_t const bit3 = 0b111;
uint8_t const bit2 = 0b11;
bme280_mode = (!lua_isnumber(L, 5)?BME280_NORMAL_MODE:(luaL_checkinteger(L, 5)&bit2)) // 4-th parameter: power mode
| ((!lua_isnumber(L, 3)?BME280_OVERSAMP_16X:(luaL_checkinteger(L, 3)&bit3)) << 2) // 2-nd parameter: pressure oversampling
| ((!lua_isnumber(L, 2)?BME280_OVERSAMP_16X:(luaL_checkinteger(L, 2)&bit3)) << 5); // 1-st parameter: temperature oversampling
bme280_ossh = (!lua_isnumber(L, 4))?BME280_OVERSAMP_16X:(luaL_checkinteger(L, 4)&bit3); // 3-rd parameter: humidity oversampling
config = ((!lua_isnumber(L, 6)?BME280_STANDBY_TIME_20_MS:(luaL_checkinteger(L, 6)&bit3))<< 5) // 5-th parameter: inactive duration in normal mode
| ((!lua_isnumber(L, 7)?BME280_FILTER_COEFF_16:(luaL_checkinteger(L, 7)&bit3)) << 2); // 6-th parameter: IIR filter
// NODE_DBG("mode: %x\nhumidity oss: %x\nconfig: %x\n", bme280_mode, bme280_ossh, config);
#define r16uLE_buf(reg) (uint16_t)((reg[1] << 8) | reg[0])
#define r16sLE_buf(reg) (int16_t)(r16uLE_buf(reg))
size_t reg_len;
const char *buf = luaL_checklstring(L, 1, &reg_len);
bme280_data = (bme280_data_p) memset(lua_newuserdata(L, sizeof(*bme280_data)), 0, sizeof(*bme280_data)); // first parameter to be returned
const uint8_t *reg;
reg = buf;
(*bme280_data).dig_T1 = r16uLE_buf(reg); reg+=2;
(*bme280_data).dig_T2 = r16sLE_buf(reg); reg+=2;
(*bme280_data).dig_T3 = r16sLE_buf(reg); reg+=2;
// NODE_DBG("dig_T: %d\t%d\t%d\n", (*bme280_data).dig_T1, (*bme280_data).dig_T2, (*bme280_data).dig_T3);
(*bme280_data).dig_P1 = r16uLE_buf(reg); reg+=2;
(*bme280_data).dig_P2 = r16sLE_buf(reg); reg+=2;
(*bme280_data).dig_P3 = r16sLE_buf(reg); reg+=2;
(*bme280_data).dig_P4 = r16sLE_buf(reg); reg+=2;
(*bme280_data).dig_P5 = r16sLE_buf(reg); reg+=2;
(*bme280_data).dig_P6 = r16sLE_buf(reg); reg+=2;
(*bme280_data).dig_P7 = r16sLE_buf(reg); reg+=2;
(*bme280_data).dig_P8 = r16sLE_buf(reg); reg+=2;
(*bme280_data).dig_P9 = r16sLE_buf(reg); reg+=2;
// NODE_DBG("dig_P: %d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", (*bme280_data).dig_P1, (*bme280_data).dig_P2,(*bme280_data).dig_P3, (*bme280_data).dig_P4, (*bme280_data).dig_P5, (*bme280_data).dig_P6, (*bme280_data).dig_P7,(*bme280_data).dig_P8, (*bme280_data).dig_P9);
if (reg_len>=6+18) { // is BME?
(*bme280_data).dig_H1 = (uint8)reg[0]; reg+=1;
(*bme280_data).dig_H2 = r16sLE_buf(reg); reg+=2;
(*bme280_data).dig_H3 = reg[0]; reg++;
(*bme280_data).dig_H4 = (int16_t)reg[0] << 4 | (reg[1] & 0x0F); reg+=1; // H4[11:4 3:0] = 0xE4[7:0] 0xE5[3:0] 12-bit signed
(*bme280_data).dig_H5 = (int16_t)reg[1] << 4 | (reg[0] >> 4); reg+=2; // H5[11:4 3:0] = 0xE6[7:0] 0xE5[7:4] 12-bit signed
(*bme280_data).dig_H6 = (int8_t)reg[0];
NODE_DBG("dig_H: %d\t%d\t%d\t%d\t%d\t%d\n", (*bme280_data).dig_H1, (*bme280_data).dig_H2, (*bme280_data).dig_H3, (*bme280_data).dig_H4, (*bme280_data).dig_H5, (*bme280_data).dig_H6);
}
#undef r16uLE_buf
#undef r16sLE_buf
int i = 1;
char cfg[2]={'\0', '\0'};
lua_createtable(L, 3, 0); /* configuration table */
cfg[0]=(char)config;
lua_pushstring(L, cfg);
lua_rawseti(L, -2, i++);
cfg[0]=(char)bme280_ossh;
lua_pushstring(L, cfg);
lua_rawseti(L, -2, i++);
cfg[0]=(char)bme280_mode;
lua_pushstring(L, cfg);
lua_rawseti(L, -2, i);
return 2;
}
// Return T, QFE, H if no altitude given
// Return T, QFE, H, QNH if altitude given
int bme280_lua_read(lua_State* L) {
double qfe;
bme280_data = (bme280_data_p)lua_touserdata(L, 1);
size_t reg_len;
const char *buf = luaL_checklstring(L, 2, &reg_len); // registers are P[3], T[3], H[2]
if (reg_len != 8 && reg_len !=6) {
luaL_error(L, "invalid readout data");
}
uint8_t calc_qnh = lua_isnumber(L, 3);
// Must do Temp first since bme280_t_fine is used by the other compensation functions
uint32_t adc_T = (uint32_t)(((buf[3] << 16) | (buf[4] << 8) | buf[5]) >> 4);
if (adc_T == 0x80000 || adc_T == 0xfffff)
return 0;
lua_pushnumber(L, bme280_compensate_T(adc_T)/100.0);
uint32_t adc_P = (uint32_t)(((buf[0] << 16) | (buf[1] << 8) | buf[2]) >> 4);
NODE_DBG("adc_P: %d\n", adc_P);
if (adc_P ==0x80000 || adc_P == 0xfffff) {
lua_pushnil(L);
calc_qnh = 0;
} else {
qfe = bme280_compensate_P(adc_P)/1000.0;
lua_pushnumber (L, qfe);
}
uint32_t adc_H = (uint32_t)((buf[6] << 8) | buf[7]);
if (reg_len!=8 || adc_H == 0x8000 || adc_H == 0xffff)
lua_pushnil(L);
else
lua_pushnumber (L, bme280_compensate_H(adc_H)/1000.0);
if (calc_qnh) { // have altitude
int32_t h = luaL_checknumber(L, 3);
double qnh = bme280_qfe2qnh(qfe, h);
lua_pushnumber (L, qnh);
return 4;
}
return 3;
}
int bme280_lua_qfe2qnh(lua_State* L) {
if (lua_isuserdata(L, 1) || lua_istable(L, 1)) { // allow to call it as object method, userdata have no use here
lua_remove(L, 1);
}
double qfe = luaL_checknumber(L, 1);
double h = luaL_checknumber(L, 2);
double qnh = bme280_qfe2qnh(qfe, h);
lua_pushnumber(L, qnh);
return 1;
}
int bme280_lua_altitude(lua_State* L) {
if (lua_isuserdata(L, 1) || lua_istable(L, 1)) { // allow to call it as object method, userdata have no use here
lua_remove(L, 1);
}
double P = luaL_checknumber(L, 1);
double qnh = luaL_checknumber(L, 2);
double h = (1.0 - pow((double)P/(double)qnh, 1.0/5.25588)) / 2.25577e-5;
lua_pushnumber (L, h);
return 1;
}
int bme280_lua_dewpoint(lua_State* L) {
if (lua_isuserdata(L, 1) || lua_istable(L, 1)) { // allow to call it as object method, userdata have no use here
lua_remove(L, 1);
}
double H = luaL_checknumber(L, 1)/100.0; // percent
double T = luaL_checknumber(L, 2);
const double c243 = 243.5;
const double c17 = 17.67;
double c = ln(H) + ((c17 * T) / (c243 + T));
double d = (c243 * c)/(c17 - c);
lua_pushnumber (L, d);
return 1;
}
LROT_BEGIN(bme280_math, NULL, 0)
LROT_FUNCENTRY( setup, bme280_lua_setup )
LROT_FUNCENTRY( read, bme280_lua_read )
LROT_FUNCENTRY( qfe2qnh, bme280_lua_qfe2qnh )
LROT_FUNCENTRY( altitude, bme280_lua_altitude )
LROT_FUNCENTRY( dewpoint, bme280_lua_dewpoint )
LROT_END(bme280_math, NULL, 0)
NODEMCU_MODULE(BME280_MATH, "bme280_math", bme280_math, NULL);

211
docs/lua-modules/bme280.md Normal file
View File

@ -0,0 +1,211 @@
# BME280 module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2020-10-04 | [vsky279](https://github.com/vsky279) | [vsky279](https://github.com/vsky279) | [bme280.c](../../app/modules/bme280.c)|
This module communicates with [BME280/BMP280 temperature/air presssure/humidity sensors](http://www.bosch-sensortec.com/bst/products/all_products/bme280) (Bosch Sensortec) through [I2C](../modules/i2c.md) interface.
Note: the module works only with the [bme280_math](../modules/bme280_math) module.
## bme280.setup()
Creates bme280sensor object and initializes module. Initialization is mandatory before read values. Note that there has to be a delay between some tens to hundreds of milliseconds between calling `setup()` and reading measurements.
Functions supported by bme280sensor object:
- [setup()](#sobjsetup)
- [read()](#sobjread)
- [startreadout()](#sobjstartreadout)
- [qfe2qnh](#sobjqfe2qnh)
- [altitude](#sobjaltitude)
- [dewpoint](#sobjdewpoint)
#### Syntax
`bme280.setup(id, [address, temp_oss, press_oss, humi_oss, power_mode, inactive_duration, IIR_filter])`
#### Parameters
- `id` - I2C bus number
- (optional)`address` - BME280 sensor address. `1` for `BME280_I2C_ADDRESS1 = 0x76`, `2` for `BME280_I2C_ADDRESS2 = 0x77`. Default sensor address is `BME280_I2C_ADDRESS1`.
- (optional) `temp_oss` - Controls oversampling of temperature data. Default oversampling is 16x.
- (optional) `press_oss` - Controls oversampling of pressure data. Default oversampling is 16x.
- (optional) `humi_oss` - Controls oversampling of humidity data. Default oversampling is 16x
- (optional) `sensor_mode` - Controls the sensor mode of the device. Default sensor more is normal.
- (optional) `inactive_duration` - Controls inactive duration in normal mode. Default inactive duration is 20ms.
- (optional) `IIR_filter` - Controls the time constant of the IIR filter. Default filter coefficient is 16.
- (optional) `cold_start` - If 0 then the BME280 chip is not initialised. Useful in a battery operated setup when the ESP deep sleeps and on wakeup needs to initialise the driver (the module) but not the chip itself. The chip was kept powered (sleeping too) and is holding the latest reading that should be fetched quickly before another reading starts (`bme280sensor:startreadout()`). By default the chip is initialised.
|`temp_oss`, `press_oss`, `humi_oss`|Data oversampling|
|-----|-----------------|
|0|Skipped (output set to 0x80000)|
|1|oversampling ×1|
|2|oversampling ×2|
|3|oversampling ×4|
|4|oversampling ×8|
|**5**|**oversampling ×16**|
|`sensor_mode`|Sensor mode|
|-----|-----------------|
|0|Sleep mode|
|1 and 2|Forced mode|
|**3**|**Normal mode**|
Using forced mode is recommended for applications which require low sampling rate or hostbased synchronization. The sensor enters into sleep mode after a forced readout. Please refer to BME280 Final Datasheet for more details.
|`inactive_duration`|t standby (ms)|
|-----|-----------------|
|0|0.5|
|1|62.5|
|2|125|
|3|250|
|4|500|
|5|1000|
|6|10|
|**7**|**20**|
|`IIR_filter`|Filter coefficient |
|-----|-----------------|
|0|Filter off|
|1|2|
|2|4|
|3|8|
|**4**|**16**|
#### Returns
`sobj` - BME280 Sensor Object (`nil` if initialization has failed)
## BME280 Sensor Object Methods
### sobj:setup()
Re-initializes the sensor.
### Parameters
Parameters are the same as for the [bme280.setup](#bme280setup) function.
### Return
Returned values are the same as for the [bme280.setup](#bme280setup) function.
### sobj:altitude()
For given air pressure (called QFE in aviation - see [wiki QNH article](https://en.wikipedia.org/wiki/QNH)) and sea level air pressure returns the altitude in meters, i.e. altimeter function.
#### Syntax
`sobj:altitude(P, QNH)`
#### Parameters
- `P` measured pressure
- `QNH` current sea level pressure
#### Returns
altitude in meters of measurement point
## sobj:dewpoint()
For given temperature and relative humidity returns the dew point in celsius.
#### Syntax
`sobj:dewpoint(H, T)`
#### Parameters
- `H` relative humidity in percent (100 means 100%)
- `T` temperate in celsius
#### Returns
dew point in celsisus
## sobj:qfe2qnh()
For given altitude converts the air pressure to sea level air pressure ([QNH](https://en.wikipedia.org/wiki/QNH)).
#### Syntax
`sobj:qfe2qnh(P, altitude)`
#### Parameters
- `P` measured pressure
- `altitude` altitude in meters of measurement point
#### Returns
sea level pressure
## sobj:read()
Reads the sensor and returns the temperature, the air pressure, the air relative humidity and see level pressure when `altitude` is specified.
#### Syntax
`sobj:read([altitude])`
#### Parameters
- (optional) `altitude`- altitude in meters of measurement point. If provided also the air pressure converted to sea level air pressure is returned.
#### Returns
- `T` temperature in celsius
- `P` air pressure in hectopascals
- `H` relative humidity in percent
- (optional) `QNH` air pressure in hectopascals (when `altitude` is specified)
Returns `nil` if the readout is not successful.
## sobj:startreadout()
Starts readout (turns the sensor into forced mode). After the readout the sensor turns to sleep mode. Callback function is called with readout results.
#### Syntax
`sobj:startreadout(delay, callback)`
#### Parameters
- `callback` if provided it will be invoked after given `delay`. Callback parameters are identical to `sobj:read` results.
- `altitude` in meters of measurement point (QNH is returned when specified)
- `delay` sets sensor to forced mode and calls the `callback` (if provided) after given number of milliseconds. For 0 the default delay is set to 113ms (sufficient time to perform reading for oversampling settings 16x). For different oversampling setting please refer to [BME280 Final Datasheet - Appendix B: Measurement time and current calculation](https://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BME280-DS002.pdf#page=51).
#### Returns
`nil`
#### Example
```lua
alt=320 -- altitude of the measurement place
sda, scl = 3, 4
i2c.setup(0, sda, scl, i2c.SLOW)
s = require('bme280').setup(0)
tmr.create():alarm(500, tmr.ALARM_AUTO, function()
local T, P, H, QNH = s:read(alt)
local D = s:dewpoint(H, T)
print(("T=%.2f, QFE=%.3f, QNH=%.3f, humidity=%.3f, dewpoint=%.2f"):format(T, P, QNH, H, D))
end)
```
Example with sensor in sleep mode between readouts (asynchronous readouts)
```lua
alt=320 -- altitude of the measurement place
sda, scl = 3, 4
i2c.setup(0, sda, scl, i2c.SLOW)
s = require('bme280').setup(0, nil, nil, nil, nil, 0) -- initialize to sleep mode
tmr.create():alarm(1000, tmr.ALARM_AUTO, function()
s:startreadout(function(T, P, H, QNH)
local D = s:dewpoint(H, T)
print(("T=%.2f, QFE=%.3f, QNH=%.3f, humidity=%.3f, dewpoint=%.2f"):format(T, P, QNH, H, D))
end, alt)
end)
```
Altimeter function - calculate altitude based on current sea level pressure (QNH) and measure pressure
```lua
alt = 0 -- initial altitude
sda, scl = 3, 4
i2c.setup(0, sda, scl, i2c.SLOW)
s = require('bme280').setup(0)
tmr.create():alarm(100, tmr.ALARM_AUTO, function()
local _, P, _, lQNH = s:read(alt)
if not QNH then QNH = lQNH end
local altitude = s:altitude(P, QNH)
print(("altitude=%.3f m"):format(altitude))
end)
```

149
docs/modules/bme280_math.md Normal file
View File

@ -0,0 +1,149 @@
# BME280_math module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-02-21 | [vsky279](https://github.com/vsky279) | [vsky279](https://github.com/vsky279) | [bme280_math.c](../../app/modules/bme280_math.c)|
This module provides calculation routines for [BME280/BMP280 temperature/air presssure/humidity sensors](http://www.bosch-sensortec.com/bst/products/all_products/bme280) (Bosch Sensortec). Communication with the sensor is ensured by Lua code through I2C or SPI interface. Read registers are passed to the module to calculate measured values.
See [bme280](../lua-modules/bme280.md) Lua module for examples.
## bme280_math.altitude()
For given air pressure (called QFE in aviation - see [wiki QNH article](https://en.wikipedia.org/wiki/QNH)) and sea level air pressure returns the altitude in meters, i.e. altimeter function.
#### Syntax
`bme280_math.altitude([self], P, QNH)`
#### Parameters
- (optional) `self` userdata or table structure so that the function can be directly called as object method, parameter is ignored in the calculation
- `P` measured pressure
- `QNH` current sea level pressure
#### Returns
altitude in meters of measurement point
## bme280_math.dewpoint()
For given temperature and relative humidity returns the dew point in celsius.
#### Syntax
`bme280_math.dewpoint([self], H, T)`
#### Parameters
- (optional) `self` userdata or table structure so that the function can be directly called as object method, parameter is ignored in the calculation
- `H` relative humidity in percent (100 means 100%)
- `T` temperate in celsius
#### Returns
dew point in celsisus
## bme280_math.qfe2qnh()
For given altitude converts the air pressure to sea level air pressure ([QNH](https://en.wikipedia.org/wiki/QNH)).
#### Syntax
`bme280_math.qfe2qnh([self], P, altitude)`
#### Parameters
- (optional) `self` userdata or table structure so that the function can be directly called as object method, parameter is ignored in the calculation
- `P` measured pressure
- `altitude` altitude in meters of measurement point
#### Returns
sea level pressure
## bme280_math.read()
Reads the sensor and returns the temperature, the air pressure, the air relative humidity and see level air pressure when `altitude` is specified.
#### Syntax
`bme280_math.read(bme280sensor, registers, [altitude])`
#### Parameters
- `bme280sensor` - BME280 sensor user data returned by `bme280_math.setup()`
- `registers` - string of 8 bytes (chars) registers read from `BME280_REGISTER_PRESS`
- (optional) `altitude`- altitude in meters of measurement point. If provided also the air pressure converted to sea level air pressure is returned.
#### Returns
- `T` temperature in celsius
- `P` air pressure in hectopascals
- `H` relative humidity in percent
- (optional) `QNH` air pressure in hectopascals
Returns `nil` if the conversion is not successful.
## bme280_math.setup()
Initializes module. Initialization is mandatory before read values.
#### Syntax
`bme280_math.setup(registers, [temp_oss, press_oss, humi_oss, power_mode, inactive_duration, IIR_filter])`
#### Parameters
- registers - String of configuration registers read from the BME280 sensor. It consists of 6 bytes (chars) of `BME280_REGISTER_DIG_T`, 18 bytes (chars) `BME280_REGISTER_DIG_P` and optional (not present for BMP280 sensor) 8 bytes (chars) of `BME280_REGISTER_DIG_H1` (1 byte) and `BME280_REGISTER_DIG_H2` (7 bytes)
- (optional) `temp_oss` - Controls oversampling of temperature data. Default oversampling is 16x.
- (optional) `press_oss` - Controls oversampling of pressure data. Default oversampling is 16x.
- (optional) `humi_oss` - Controls oversampling of humidity data. Default oversampling is 16x
- (optional) `sensor_mode` - Controls the sensor mode of the device. Default sensor more is normal.
- (optional) `inactive_duration` - Controls inactive duration in normal mode. Default inactive duration is 20ms.
- (optional) `IIR_filter` - Controls the time constant of the IIR filter. Default filter coefficient is 16.
|`temp_oss`, `press_oss`, `humi_oss`|Data oversampling|
|-----|-----------------|
|0|Skipped (output set to 0x80000)|
|1|oversampling ×1|
|2|oversampling ×2|
|3|oversampling ×4|
|4|oversampling ×8|
|**5**|**oversampling ×16**|
|`sensor_mode`|Sensor mode|
|-----|-----------------|
|0|Sleep mode|
|1 and 2|Forced mode|
|**3**|**Normal mode**|
Using forced mode is recommended for applications which require low sampling rate or hostbased synchronization. The sensor enters into sleep mode after a forced readout. Please refer to BME280 Final Datasheet for more details.
|`inactive_duration`|t standby (ms)|
|-----|-----------------|
|0|0.5|
|1|62.5|
|2|125|
|3|250|
|4|500|
|5|1000|
|6|10|
|**7**|**20**|
|`IIR_filter`|Filter coefficient |
|-----|-----------------|
|0|Filter off|
|1|2|
|2|4|
|3|8|
|**4**|**16**|
#### Returns
- `bme280sensor` user data (`nil` if initialization has failed)
- `config` 3 (2 for BME280) field table with configuration parameters to be written to registers `BME280_REGISTER_CONFIG`, `BME280_REGISTER_CONTROL_HUM`, `BME280_REGISTER_CONTROL` consecutively
#### Example
See [bme280](../lua-modules/bme280.md) Lua module documentation.
## BME280 (selected) registers
| name | address |
|-------|----------|
| BME280_REGISTER_CONTROL | 0xF4 |
| BME280_REGISTER_CONTROL_HUM | 0xF2 |
| BME280_REGISTER_CONFIG| 0xF5 |
| BME280_REGISTER_CHIPID | 0xD0 |
| BME280_REGISTER_DIG_T | 0x88 (0x88-0x8D (6)) |
| BME280_REGISTER_DIG_P | 0x8E (0x8E-0x9F (18)) |
| BME280_REGISTER_DIG_H1 | 0xA1 |
| BME280_REGISTER_DIG_H2 | 0xE1 (0xE1-0xE7 (7)) |
| BME280_REGISTER_PRESS | 0xF7 (0xF7-0xF9 (8)) |

View File

@ -0,0 +1,173 @@
--[[
BME280 Lua module
Requires i2c and bme280_math module
Written by Lukas Voborsky, @voborsky
]]
local bme280 = {}
-- bme280.setup()
-- bme280:setup()
-- bme280:read()
-- bme280:altitude()
-- bme280:dewpoint()
-- bme280:qfe2qnh()
-- bme280:startreadout()
local type, assert = type, assert
local table_concat, math_floor = table.concat, math.floor
local i2c_start, i2c_stop, i2c_address, i2c_read, i2c_write, i2c_TRANSMITTER, i2c_RECEIVER =
i2c.start, i2c.stop, i2c.address, i2c.read, i2c.write, i2c.TRANSMITTER, i2c.RECEIVER
local bme280_math_setup, bme280_math_read, bme280_math_qfe2qnh, bme280_math_altitude, bme280_math_dewpoint =
bme280_math.setup, bme280_math.read, bme280_math.qfe2qnh, bme280_math.altitude, bme280_math.dewpoint
local tmr_create, tmr_ALARM_SINGLE = tmr.create, tmr.ALARM_SINGLE
local BME280_I2C_ADDRESS1 = 0x76
local BME280_I2C_ADDRESS2 = 0x77
local BME280_REGISTER_CONTROL = 0xF4
local BME280_REGISTER_CONTROL_HUM = 0xF2
local BME280_REGISTER_CONFIG= 0xF5
local BME280_REGISTER_CHIPID = 0xD0
local BME280_REGISTER_DIG_T = 0x88 -- 0x88-0x8D ( 6)
local BME280_REGISTER_DIG_P = 0x8E -- 0x8E-0x9F (18)
local BME280_REGISTER_DIG_H1 = 0xA1 -- 0xA1 ( 1)
local BME280_REGISTER_DIG_H2 = 0xE1 -- 0xE1-0xE7 ( 7)
local BME280_REGISTER_PRESS = 0xF7 -- 0xF7-0xF9
-- local BME280_FORCED_MODE = 0x01
-- maximum measurement time in ms for maximum oversampling for all measures
-- 113 > 1.25 + 2.3*16 + 2.3*16 + 0.575 + 2.3*16 + 0.575 ms
local BME280_SAMPLING_DELAY =113
-- Local functions
local read_reg
local write_reg
local bme280_setup
local bme280_read
local bme280_startreadout
-- -- Note that the space between debug and the arglist is there for a reason
-- -- so that a simple global edit " debug(" -> "-- debug(" or v.v. to
-- -- toggle debug compiled into the module.
-- local print, node_heap = print, node.heap
-- local function debug (fmt, ...) -- upval: cnt (, print, node_heap)
-- if not bme280.debug then return end
-- if (...) then fmt = fmt:format(...) end
-- print("[bme280]", node_heap(), fmt)
-- end
--------------------------- Set up the bme280 object ----------------------------
-- bme280 has method setup to create the sensor object and setup the sensor
-- object created by bme280.setup() has methods: read, qfe2qnh, altitude, dewpoint
---------------------------------------------------------------------------------
function bme280.setup(id, addr, temp_oss, press_oss, humi_oss, power_mode, inactive_duration, IIR_filter, full_init)
return bme280_setup(nil, id,
addr, temp_oss, press_oss, humi_oss, power_mode, inactive_duration, IIR_filter, full_init)
end
------------------------------------------------------------------------------
function bme280_setup(self, id, addr,
temp_oss, press_oss, humi_oss, power_mode, inactive_duration, IIR_filter, full_init)
addr = (addr==2) and BME280_I2C_ADDRESS2 or BME280_I2C_ADDRESS1
full_init = full_init or true
-- debug("%d %x %d", id, addr, BME280_REGISTER_CHIPID)
local chipid = read_reg(id, addr, BME280_REGISTER_CHIPID, 1)
if not chipid then
return nil
end
-- debug("chip_id: %x", chipid:byte(1))
local isbme = (chipid:byte(1) == 0x60)
local buf = {}
buf[1] = read_reg(id, addr, BME280_REGISTER_DIG_T, 6)
buf[2] = read_reg(id, addr, BME280_REGISTER_DIG_P, 18)
if (isbme) then
buf[3] = read_reg(id, addr, BME280_REGISTER_DIG_H1, 1)
buf[4] = read_reg(id, addr, BME280_REGISTER_DIG_H2, 7)
end
local sensor, config = bme280_math_setup(table_concat(buf),
temp_oss, press_oss, humi_oss, power_mode, inactive_duration, IIR_filter)
self = self or {
setup = bme280_setup,
read = bme280_read,
startreadout = bme280_startreadout,
qfe2qnh = bme280_math_qfe2qnh,
altitude = bme280_math_altitude,
dewpoint = bme280_math_dewpoint
}
self.id, self.addr = id, addr
self._sensor, self._config, self._isbme = sensor, config, isbme
if (full_init) then
write_reg(id, addr, BME280_REGISTER_CONFIG, config[1])
if (isbme) then write_reg(id, addr, BME280_REGISTER_CONTROL_HUM, config[2]) end
write_reg(id, addr, BME280_REGISTER_CONTROL, config[3])
end
return self
end
function bme280_read(self, alt)
local buf = read_reg(self.id, self.addr, BME280_REGISTER_PRESS, 8) -- registers are P[3], T[3], H[2]
if buf then
return bme280_math_read(self._sensor, buf, alt)
else
return nil
end
end
function bme280_startreadout(self, callback, delay, alt)
assert(type(callback) == "function", "invalid callback parameter")
delay = delay or BME280_SAMPLING_DELAY
if self._isbme then write_reg(self.id, self.addr, BME280_REGISTER_CONTROL_HUM, self._config[2]) end
write_reg(self.id, self.addr, BME280_REGISTER_CONTROL, math_floor(self._config[3]:byte(1)/4)+ 1)
-- math_floor(self._config[3]:byte(1)/4)+ 1
-- an awful way to avoid bit operations but calculate (config[3] & 0xFC) | BME280_FORCED_MODE
-- Lua 5.3 integer division // would be more suitable
tmr_create():alarm(delay, tmr_ALARM_SINGLE,
function()
callback(bme280_read(self, alt))
end
)
end
function write_reg(id, dev_addr, reg_addr, data)
i2c_start(id)
if not i2c_address(id, dev_addr, i2c_TRANSMITTER) then
-- debug("No ACK on address: %x", dev_addr)
return nil
end
i2c_write(id, reg_addr)
local c = i2c_write(id, data)
i2c_stop(id)
return c
end
function read_reg(id, dev_addr, reg_addr, n)
i2c_start(id)
if not i2c_address(id, dev_addr, i2c_TRANSMITTER) then
-- debug("No ACK on address: %x", dev_addr)
return nil
end
i2c_write(id, reg_addr)
i2c_stop(id)
i2c_start(id)
i2c_address(id, dev_addr, i2c_RECEIVER)
local c = i2c_read(id, n)
i2c_stop(id)
return c
end
------------------------------------------------ -----------------------------
return bme280

View File

@ -48,6 +48,7 @@ pages:
- Lua Modules: - Lua Modules:
- 'Lua modules directory': 'lua-modules/README.md' - 'Lua modules directory': 'lua-modules/README.md'
- 'bh1750': 'lua-modules/bh1750.md' - 'bh1750': 'lua-modules/bh1750.md'
- 'bme280': 'lua-modules/bme280.md'
- 'cohelper': 'lua-modules/cohelper.md' - 'cohelper': 'lua-modules/cohelper.md'
- 'ds18b20': 'lua-modules/ds18b20.md' - 'ds18b20': 'lua-modules/ds18b20.md'
- 'ds3231': 'lua-modules/ds3231.md' - 'ds3231': 'lua-modules/ds3231.md'
@ -73,6 +74,7 @@ pages:
- 'bit': 'modules/bit.md' - 'bit': 'modules/bit.md'
- 'bloom' : 'modules/bloom.md' - 'bloom' : 'modules/bloom.md'
- 'bme280': 'modules/bme280.md' - 'bme280': 'modules/bme280.md'
- 'bme280_math': 'modules/bme280_math.md'
- 'bme680': 'modules/bme680.md' - 'bme680': 'modules/bme680.md'
- 'bmp085': 'modules/bmp085.md' - 'bmp085': 'modules/bmp085.md'
- 'cjson': 'modules/cjson.md' - 'cjson': 'modules/cjson.md'

View File

@ -112,6 +112,15 @@ stds.nodemcu_libs = {
temp = empty temp = empty
} }
}, },
bme280_math = {
fields = {
altitude = empty,
dewpoint = empty,
qfe2qnh = empty,
read = empty,
setup = empty
}
},
bme680 = { bme680 = {
fields = { fields = {
altitude = empty, altitude = empty,