API Reference

Main Module

bme280pi package: a package to read out the BME280 sensor on Raspberry Pi.

Here’s a quick overview of how this package can be used:

1) Import the Sensor class: from bme280pi import Sensor 2) Initialize a Sensor object: sensor = Sensor() 3) Get the sensor data: data = sensor.get_data()

You can also just fetch the temperature, the pressure, or the humidity with the individual .get_temperature(), .get_pressure, and get_humidity functions.

The standard units are degrees Celsius (C) for temperature, hectopascal (hPa) for pressure, and percentage for humidity. Other units are supported for temperature (F and K) and pressure (mm Hg, atm, Pa, kPa), and the humidity can also be indicated in absolute terms (i.e. g per m^3).

For more in-depth information see the individual docstrings of the functions of the Sensor class.

class Sensor(address=118)[source]

Bases: object

Sensor class.

This class initializes the BME280 sensor, and offers an intuitive interface to access the sensor information. You can read out the temperature, humidity, and pressure using the corresponding get_ commands:

  • get_temperature: get the current temperature

  • get_pressure: get the current pressure

  • get_humidity: get the current humidity

The functions each support the unit argument, so you can specify the unit you would like the value to be in. For instance, the get_temperature function supports degrees C, F, or K.

You can also use print_data() for a nicer presentation.

Example usage: >>> sensor = Sensor() >>> sensor.get_temperature(unit=’C’) >>> sensor.get_temperature(unit=’K’) >>> sensor.get_humidity(relative=True) >>> sensor.get_humidity(relative=True) >>> sensor.get_pressure(unit=’hPa’) >>> sensor.get_pressure(unit=’mmHg’)

Parameters:

address (int)

get_data()[source]

Get a reading from the sensor.

Fetches the latest humidity, temperature, and pressure data from the sensor. The data is returned as a dictionary with keys “temperature”, “humidity”, and “pressure”.

Returns:

dictionary with current temperature, humidity, and pressure

Return type:

dict

get_humidity(relative=True)[source]

Get a humidity reading.

Fetches a humidity reading from the sensor. The value can be the relative humidity (relative=True), with values between 0 and 100. Alternatively, it returns the absolute humidity in kg / m^3.

Parameters:

relative (bool) – indicate relative (instead of absolute) humidity

Returns:

the current relative/absolute humidity

Return type:

float

get_pressure(unit='hPa', height_above_sea_level=None, as_pressure_at_sea_level=False)[source]

Get a pressure reading.

Fetch the pressure from the sensor. The value can be returned in hPa (unit=’hPa’), Pa (`unit=’Pa’), kPa (`unit=’kPa’), atm (unit=’atm’), or mm Hg (unit=’mmHg’).

For meteorological applications, it can be useful to conver the pressure into its equivalent value at sea level. If you prefer this convention, set as_pressure_at_sea_level=True. In that case, you need to specify the height above sea level as well.

Parameters:
  • unit (str) – unit the pressure should be in (Pa/hPa/kPa/atm/mmHg)

  • height_above_sea_level (int/float) – height above sea level in m

  • as_pressure_at_sea_level (bool) – quote as pressure above sea level

Returns:

the pressure in the specified unit, at sea level if desired

Return type:

float

get_temperature(unit='C')[source]

Get a temperature reading.

Fetches a temperature reading from the sensor and returns it in the user-specified temperature unit (degrees Celsius by default). The value can be returned in degrees Celsius (unit=’C’), in degrees Fahrenheit (unit=’F’), or in Kelvin (unit=’K’).

Parameters:

unit (str) – the unit the temperature should be in (C/F/K)

Returns:

the current temperature in the specified unit

Return type:

float

print_data(temp_unit='C', relative_humidity=True, pressure_unit='hPa', n_significant_digits=4)[source]

Print sensor data.

Prints the temperature, humidity, and pressure in a easy readable format. The user can specify the temperature unit (e.g. “C”) via temp_unit, the pressure unit (e.g. “hPa”) via pressure_unit, and whether to use absolute or relative humidity via relative_humidity.

Parameters:
  • temp_unit (str) – the unit the temperature should be in (C/F/K)

  • relative_humidity (bool) – relative instead of absolute humidity

  • pressure_unit (str) – pressure unit (Pa/hPa/kPa/atm/mmHg)

  • n_significant_digits (int) – number of significant digits for values

Returns:

values are printed, not returned.

Return type:

None

Sensor Class

class Sensor(address=118)[source]

Bases: object

Sensor class.

This class initializes the BME280 sensor, and offers an intuitive interface to access the sensor information. You can read out the temperature, humidity, and pressure using the corresponding get_ commands:

  • get_temperature: get the current temperature

  • get_pressure: get the current pressure

  • get_humidity: get the current humidity

The functions each support the unit argument, so you can specify the unit you would like the value to be in. For instance, the get_temperature function supports degrees C, F, or K.

You can also use print_data() for a nicer presentation.

Example usage: >>> sensor = Sensor() >>> sensor.get_temperature(unit=’C’) >>> sensor.get_temperature(unit=’K’) >>> sensor.get_humidity(relative=True) >>> sensor.get_humidity(relative=True) >>> sensor.get_pressure(unit=’hPa’) >>> sensor.get_pressure(unit=’mmHg’)

Parameters:

address (int)

get_data()[source]

Get a reading from the sensor.

Fetches the latest humidity, temperature, and pressure data from the sensor. The data is returned as a dictionary with keys “temperature”, “humidity”, and “pressure”.

Returns:

dictionary with current temperature, humidity, and pressure

Return type:

dict

get_humidity(relative=True)[source]

Get a humidity reading.

Fetches a humidity reading from the sensor. The value can be the relative humidity (relative=True), with values between 0 and 100. Alternatively, it returns the absolute humidity in kg / m^3.

Parameters:

relative (bool) – indicate relative (instead of absolute) humidity

Returns:

the current relative/absolute humidity

Return type:

float

get_pressure(unit='hPa', height_above_sea_level=None, as_pressure_at_sea_level=False)[source]

Get a pressure reading.

Fetch the pressure from the sensor. The value can be returned in hPa (unit=’hPa’), Pa (`unit=’Pa’), kPa (`unit=’kPa’), atm (unit=’atm’), or mm Hg (unit=’mmHg’).

For meteorological applications, it can be useful to conver the pressure into its equivalent value at sea level. If you prefer this convention, set as_pressure_at_sea_level=True. In that case, you need to specify the height above sea level as well.

Parameters:
  • unit (str) – unit the pressure should be in (Pa/hPa/kPa/atm/mmHg)

  • height_above_sea_level (int/float) – height above sea level in m

  • as_pressure_at_sea_level (bool) – quote as pressure above sea level

Returns:

the pressure in the specified unit, at sea level if desired

Return type:

float

get_temperature(unit='C')[source]

Get a temperature reading.

Fetches a temperature reading from the sensor and returns it in the user-specified temperature unit (degrees Celsius by default). The value can be returned in degrees Celsius (unit=’C’), in degrees Fahrenheit (unit=’F’), or in Kelvin (unit=’K’).

Parameters:

unit (str) – the unit the temperature should be in (C/F/K)

Returns:

the current temperature in the specified unit

Return type:

float

print_data(temp_unit='C', relative_humidity=True, pressure_unit='hPa', n_significant_digits=4)[source]

Print sensor data.

Prints the temperature, humidity, and pressure in a easy readable format. The user can specify the temperature unit (e.g. “C”) via temp_unit, the pressure unit (e.g. “hPa”) via pressure_unit, and whether to use absolute or relative humidity via relative_humidity.

Parameters:
  • temp_unit (str) – the unit the temperature should be in (C/F/K)

  • relative_humidity (bool) – relative instead of absolute humidity

  • pressure_unit (str) – pressure unit (Pa/hPa/kPa/atm/mmHg)

  • n_significant_digits (int) – number of significant digits for values

Returns:

values are printed, not returned.

Return type:

None

Physics Helpers

Physics functions for pressure/temperature/humidity/…

Provides functions related to converting humidity from relative to absolute humidity. Also provides functions for converting pressure & temperature into different units (e.g. Kelvin, mm Hg), and to round numbers to a n significant digits.

The following functions are present in this module: - validate_pressure(pressure) - validate_temperature(temperature) - validate_humidity(rel_humidity) - validate_height_above_sea_level(height_above_sea_level) - pressure_function(pressure) - calculate_abs_humidity(pressure, temperature, rel_humidity) - convert_pressure(pressure, unit=’hPa’) - convert_temperature(temperature, unit=’C’) - pressure_at_sea_level(pressure, temperature, height_above_sea_level) - round_to_n_significant_digits(value, n_digits)

source for formulae: https://planetcalc.com/2167/ https://keisan.casio.com/keisan/image/Convertpressure.pdf

calculate_abs_humidity(pressure, temperature, rel_humidity)[source]

Calculate the absolute humidity.

The absolute humidity is calculated in the following steps:

  1. Saturation vapor pressure over water (Magnus formula): .. math:: e_w(T) = 6.112 cdot expleft(

rac{17.62 cdot T}{T + 243.12} ight)

  1. Enhancement factor \(f(p)\) accounts for real moist air

  2. Actual vapor pressure: .. math:: e =

rac{ ext{rel_humidity}}{100} cdot f(p) cdot e_w(T)

  1. Absolute humidity (ideal gas law for water vapor): .. math:: AH =

rac{e cdot 100}{R_v cdot T_K} cdot 2.16679
\[\quad ext{with } R_v = 461.5\, ext{J}\, ext{kg}^{-1}\, ext{K}^{-1}\]

The constant 2.16679 converts from hPa·K to g/m³.

Parameters:
  • pressure (int/float) – pressure in hPa

  • temperature (int/float) – temperature in degrees Celsius

  • rel_humidity (int/float) – relative humidity in percent (0-100)

Returns:

humidity measurement value

Return type:

float

convert_pressure(pressure, unit='hPa')[source]

Pressure in user-specified unit.

Converts pressure from hPa (input) to the desired unit.

Available options are:

  • hPa (unit=’hPa’)

  • Pa (unit=’Pa’)

  • kPa (unit=’kPa’)

  • atm (unit=’atm’)

  • mm Hg (unit=’mmHg’)

Parameters:
  • pressure (int/float) – pressure in hPa

  • unit (str) – unit TO CONVERT PRESSURE TO (hPa/Pa/kPa/atm/mmHg)

Returns:

pressure in specified unit

Return type:

float

convert_temperature(temperature, unit='C')[source]

Temperature in user-specified unit.

Converts temperature from Celsius (input) to the desired unit. Available options are: - Celsius (unit=’C’) - Fahrenheit (unit=’F’) - Kelvin (unit=’K’)

Parameters:
  • temperature (int/float) – temperature in degrees Celsius

  • unit (str) – unit to convert the temperature to (C/F/K)

Returns:

temperature in desired unit

Return type:

float

pressure_at_sea_level(pressure, temperature, height_above_sea_level)[source]

Convert pressure to pressure at sea level.

Uses a simple formula to convert the observed pressure to the equivalent pressure at sea level. The pressure at sea level is a commonly quoted quantity, often referred to as QFF whereas the “local” observed pressure is referred to as QFE.

\[e = -\frac{g}{R_d \gamma} f = \left(1 + \frac{\gamma \cdot h}{T - \gamma\cdot h}\right) p = p_0 * f ^ e\]

where e is the exponent, f is the correction factor, gamma is the derivative dT/dz (which is approx. -0.0065 K/m), g is the gravitational acceleration in free fall (9.80665 m/s^2), T is the temperature, R_d is the specific gas constant of dry air (287 J/kg/K), p is the observed pressure, and p_0 is the pressure at sea level. All calculations are in SI units.

Parameters:
  • pressure (float/int) – pressure in hPa

  • temperature (float/int) – temperature in degrees Celsius

  • height_above_sea_level (float/int) – height above sea level in meters

Returns:

equivalent pressure at sea level in hPa

Return type:

float

pressure_function(pressure)[source]

Saturation vapor pressure function.

Calculates the relevant factor to convert the saturation vapor pressure in pure phase to the saturation vapor pressure in moist air.

Parameters:

pressure (int/float) – pressure in hPa

Returns:

factor to convert saturation vapor pressure

Return type:

float

round_to_n_significant_digits(value, n_digits)[source]

Round to n significant digits.

Rounds a number to n significant digits, e.g. for 1234 the result with 2 significant digits would be 1200.

Parameters:
  • value (float/int) – the value to be rounded

  • n_digits (int) – the desired number of significant digits

Returns:

the value rounded to the desired number of significant digits

Return type:

float

validate_height_above_sea_level(height_above_sea_level)[source]

Validate height above sea level.

Checks that height above sea level satisfies the following constraints: - needs to be positive - needs to be smaller than 11000 (limit of validity of conversion formula)

A ValueError is raised if any of the assumptions are violated.

Parameters:

height_above_sea_level (float/int) – height above sea level in meters

Return type:

None

Returns:

None

validate_humidity(rel_humidity)[source]

Validate input humidity.

Checks that humidity satisfies the following constraints: - relative humidity must be below 100% - relative humidity must be above 0%

A ValueError is raised if any of the assumptions are violated.

Parameters:

rel_humidity (float/int) – relative humidity in percent (i.e. 0-100)

Return type:

None

Returns:

None

validate_pressure(pressure)[source]

Validate input pressure.

Checks that pressure satisfies the following constraints: - needs to be positive - needs to be smaller than 1100 (largest value ever was 1083)

A ValueError is raised if any of the assumptions are violated.

Parameters:

pressure (float/int) – pressure in hPa

Return type:

None

Returns:

None

validate_temperature(temperature)[source]

Validate input temperature.

Checks that temperature satisfies the following constraints:

  • needs to be smaller than 100 degrees (humidity calculations don’t make much sense above this temperature)

  • needs to be larger than -100 (same reason)

A ValueError is raised if any of the assumptions are violated.

Parameters:

temperature (float/int) – temperature in degrees Celsius

Return type:

None

Returns:

None

Raspberry Pi Version Detection

Detect the Raspberry Pi Version.

Contains the detect_raspberry_pi_version function, which detects the version of the Raspberry Pi used.

detect_raspberry_pi_version()[source]

Detect the Raspberry Pi Version.

Detects the Raspberry Pi version based on CPU information. Note that if the model comes back as “Unknown”, you may need to add it to the dictionary in get_list_of_revisions. The current list is up-to-date as of June 2020.

Args:

Returns:

Raspberry Pi version

Return type:

str

get_list_of_revisions()[source]

List of known Raspberry Pi Revisions.

Provides a list of known Raspberry Pi CPU IDs and the corresponding Raspberry Pi model name (“revision”).

Args:

Returns:

dictionary of Raspberry Pi Revisions

Return type:

dict

Readout Logic

Functions to read out and interpret the raw sensor data.

This module contains all functions necessary for reading out the raw data from the BME280 sensor according to the Bosch data sheet, and processing this raw data in order to obtain a more digestible format, i.e. the temperature, pressure, and relative humidity.

The best way to use this module is through the Sensor class in sensor.py, i.e. by initializing a Sensor object and using it to fetch data. One could use the functions in this module to do the individual steps, but it’s much more practical to use the Sensor class directly and have it take care of everything.

Example usage: >>> sensor = Sensor() >>> sensor.get_temperature(unit=’C’)

Have a look at the Sensor class in sensor.py for more detailed information.

The (helper) functions contained in this module are the following: - get_short(data, index): - get_unsigned_short(data, index): - get_character(data, index): - get_unsigned_character(data, index): - read_raw_sensor(bus, address, oversampling, reg_data): - get_modified(cal, i, function, shift=False): - process_calibration_data(cal): - shift_read(values, i, j, k): - extract_raw_values(data): - improve_temperature_measurement(temp_raw, dig_t): - improve_pressure_measurement(raw_pressure, dig_p, t_fine): - improve_humidity_measurement(raw_humidity, dig_h, t_fine): - extract_values(data, dig_t, dig_p, dig_h): - validate_oversampling(oversampling=None): - read_sensor(bus, address, reg_data=0xF7,

Notes: 1) This module is based on the bme280 script from MattHawkinsUK, https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/bme280.py

2) Before changing parameters in the code, it is recommended to have a look at the data sheet available directly from Bosch: https://www.bosch-sensortec.com/products/environmental-sensors/humidity-sensors-bme280/

extract_raw_values(data)[source]

Extract raw reading of temperature, pressure, and humidity.

Parameters:

data (list) – raw sensor data

Returns:

raw pressure, temperature, and humidity

Return type:

tuple

extract_values(data, dig_t, dig_p, dig_h)[source]

Extract values from raw data.

Extracts temperature, pressure, and humidity from raw data and correct it to provide the best measurement.

Parameters:
  • data (list) – data blocks from sensor

  • dig_t (list) – data blocks pertaining to temperature measurement

  • dig_p (list) – data blocks pertaining to pressure measurement

  • dig_h (list) – data blocks pertaining to humidity measurement

Returns:

three floats representing temperature, pressure, and humidity

Return type:

tuple

get_character(data, index)[source]

Return one byte from data as a signed char.

Parameters:
  • data (list) – raw data from sensor

  • index (int) – index entry from which to read data

Returns:

extracted signed char value

Return type:

int

get_modified(cal, i, function, shift=False)[source]

Obtain and modify data from block.

Extracts information from block, and shifts it if necessary.

Parameters:
  • cal (list) – calibration data

  • i (int) – index from which to read

  • function (object) – function to apply to data

  • shift (bool) – whether to apply a shift to result

Returns:

processed data from specified blocks

Return type:

int

get_short(data, index)[source]

Return two bytes from data as a signed 16-bit value.

Parameters:
  • data (list) – raw data from sensor

  • index (int) – index entry from which to read data

Returns:

extracted signed 16-bit value

Return type:

c_short

get_unsigned_character(data, index)[source]

Return one byte from data as an unsigned char.

Parameters:
  • data (list) – raw data from sensor

  • index (int) – index entry from which to read data

Returns:

extracted unsigned 16-bit value

Return type:

int

get_unsigned_short(data, index)[source]

Return two bytes from data as an unsigned 16-bit value.

Parameters:
  • data (list) – raw data from sensor

  • index (int) – index entry from which to read data

Returns:

extracted unsigned 16-bit value

Return type:

int

improve_humidity_measurement(raw_humidity, dig_h, t_fine)[source]

Refine the humidity measurement.

Adapts the humidity measurement by using the available temperature information, along with the humidity readout details.

Parameters:
  • raw_humidity (int) – raw humidity

  • dig_h (list) – raw data blocks pertaining to humidity measurement

  • t_fine (float) – temperature measurement

Returns:

refined humidity measurement

Return type:

float

Reference: Bosch data sheet, Appendix A, “BME280_compensate_H_double”

improve_pressure_measurement(raw_pressure, dig_p, t_fine)[source]

Refine the pressure measurement.

Adapts the pressure measurement according to the formula specified in the Bosch data sheet, and adjust it for the available temperature measurement, along with the pressure readout details.

Parameters:
  • raw_pressure (float) – raw temperature measurement

  • dig_p (list) – data blocks pertaining to pressure

  • t_fine (float) – temperature measurement

Returns:

improved pressure measurement

Return type:

float

Reference: Bosch data sheet, Appendix A, “BME280_compensate_P_double”

improve_temperature_measurement(temp_raw, dig_t)[source]

Refine the temperature measurement.

Adapts the raw temperature measurement according to a formula specified in the Bosch data sheet.

Parameters:
  • temp_raw (int) – raw temperature reading

  • dig_t (list) – blocks of data pertaining to temperature

Returns:

refined temperature measurement and reference point

Return type:

tuple

Reference:

Bosch data sheet, Appendix A, “BME280_compensate_T_double”

process_calibration_data(cal)[source]

Process calibration data.

Processes calibration data to extract the information pertaining to temperature, pressure, and humidity. Returns the relevant block data.

Parameters:

cal (list) – calibration data

Returns:

block values for temperature, pressure, and humidity

Return type:

tuple

read_raw_sensor(bus, address, oversampling, reg_data)[source]

Read raw sensor data.

For an explanation of the parameter storage, naming, and data type, see Table 16, page 25, of the data sheet. For information about oversampling, see e.g. page 26. For a memory map, see Table 18 on page 27.

Parameters:
  • bus (object) – bus from which to read data

  • address (int) – address at which to read data

  • oversampling (dict) – over-sampling rates (see data sheet)

  • reg_data (int) – register at which to obtain data

Returns:

calibration data as a list, and sensor data

Return type:

tuple

read_sensor(bus, address, reg_data=247, oversampling=None)[source]

Read measurements from sensor.

Reads the raw information from the sensor and converts it into a readable format. The function returns a dictionary with the measurements, with the three keys “temperature”, See the data sheet for more information, e.g. p27 for oversampling settings, App. B for measurement time, Sec. 4 for data readout, etc.

If no oversampling is defined, the code defaults to the standard 2/2/2 for temperature/humidity/pressure. If you wish to specify your own oversampling parameters, please pass a dictionary to oversampling with the keys ‘temperature’, ‘pressure’, and ‘humidity’.

This module is based on the bme280 script from MattHawkinsUK, which in turn is based on the data sheet from Bosch (see references below).

Parameters:
  • bus (object) – the sensor bus to read from

  • address (int) – the address from which to read data

  • reg_data (int) – register at which to obtain data

  • oversampling (dict) – oversampling rates

Returns:

measurements for temperature, pressure, and humidity

Return type:

dict

References: https://www.bosch-sensortec.com/products/environmental-sensors/humidity-sensors-bme280/

shift_read(values, i, j, k)[source]

Read raw data from array and shift it.

Reads values from array and shifts them the following way:

  • the first one is shifted to the left by 12 places

  • the second value is shifted to the left by 4 places

  • the third one is shifted to the right by 4 places

Then a bitwise “or” operation is performed.

Example: values = [1, 2, 3]

  • the first entry (1) is shifted 12 places to the left:

    000000000001 becomes 1000000000000

  • the second entry (2) is shifted 4 places to the left:

    000000000010 becomes 000000100000

  • the third entry (3) is shifted 4 places to the right:

    000000000011 becomes 000000000000

Finally, a bit-wise “or” is performed:

1000000000000 or 0000000100000 or 0000000000000 is 1000000100000

which, in decimal, is 4128.

Parameters:
  • values (list) – the raw values

  • i (int) – first index to read from

  • j (int) – second index to read from

  • k (int) – third index to read from

Returns:

extracted (shifted) values

Return type:

int

validate_oversampling(oversampling=None)[source]

Validate the oversampling parameter.

Checks whether the parameter is valid. This parameter can either be None (to use the default values) or it can be a dictionary containing the three keys “temperature”, “humidity”, and “pressure”.

Parameters:

oversampling (dict) – None or a dictionary with over-sampling values

Returns:

oversampling values as a dictionary

Return type:

dict