Compare commits

...

2 commits

Author SHA1 Message Date
ladyada
5ab8bef5c2 old bug fixed, example added, ready for bundlin 2017-12-09 16:29:48 -05:00
Scott Shawcroft
572713fae4 Rename seaLevelhPa to sea_level_pressure to match Python style. Enable lint. 2017-12-05 18:57:26 -08:00
7 changed files with 628 additions and 144 deletions

3
.gitignore vendored
View file

@ -1,3 +1,6 @@
__pycache__ __pycache__
_build _build
*.pyc *.pyc
.env
build*
bundles

425
.pylintrc Normal file
View file

@ -0,0 +1,425 @@
[MASTER]
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code
extension-pkg-whitelist=
# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=CVS
# Add files or directories matching the regex patterns to the blacklist. The
# regex matches against base names, not paths.
ignore-patterns=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint.
jobs=2
# List of plugins (as comma separated values of python modules names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# Specify a configuration file.
#rcfile=
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
confidence=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once).You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=
[REPORTS]
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details
#msg-template=
# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio).You can also give a reporter class, eg
# mypackage.mymodule.MyReporterClass.
output-format=text
# Tells whether to display a full report or only the messages
reports=no
# Activate the evaluation score.
score=yes
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
[LOGGING]
# Logging modules to check that the string format arguments are in logging
# function parameter format
logging-modules=logging
[SPELLING]
# Spelling dictionary name. Available dictionaries: none. To make it working
# install python-enchant package.
spelling-dict=
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to indicated private dictionary in
# --spelling-private-dict-file option instead of raising a message.
spelling-store-unknown-words=no
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,XXX,TODO
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid to define new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,_cb
# A regular expression matching the name of dummy variables (i.e. expectedly
# not used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored. Default to name
# with leading underscore
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,future.builtins
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=LF
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=100
# Maximum number of lines in a module
max-module-lines=1000
# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,dict-separator
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[SIMILARITIES]
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=no
# Minimum lines number of a similarity.
min-similarity-lines=4
[BASIC]
# Naming hint for argument names
argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Regular expression matching correct argument names
argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Naming hint for attribute names
attr-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Regular expression matching correct attribute names
attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Bad variable names which should always be refused, separated by a comma
bad-names=foo,bar,baz,toto,tutu,tata
# Naming hint for class attribute names
class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
# Regular expression matching correct class attribute names
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
# Naming hint for class names
class-name-hint=[A-Z_][a-zA-Z0-9_]+$
# Regular expression matching correct class names
class-rgx=[A-Z_][a-zA-Z0-9_]+$
# Naming hint for constant names
const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
# Regular expression matching correct constant names
const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming hint for function names
function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Regular expression matching correct function names
function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Good variable names which should always be accepted, separated by a comma
good-names=r,g,b,i,j,k,n,ex,Run,_
# Include a hint for the correct naming format with invalid-name
include-naming-hint=no
# Naming hint for inline iteration names
inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
# Regular expression matching correct inline iteration names
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
# Naming hint for method names
method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Regular expression matching correct method names
method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Naming hint for module names
module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Regular expression matching correct module names
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
property-classes=abc.abstractproperty
# Naming hint for variable names
variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Regular expression matching correct variable names
variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
[IMPORTS]
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Deprecated modules which should not be used, separated by a comma
deprecated-modules=optparse,tkinter.tix
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled)
ext-import-graph=
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled)
import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled)
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,__new__,setUp
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,_fields,_replace,_source,_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=mcs
[DESIGN]
# Maximum number of arguments for function / method
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=11
# Maximum number of boolean expressions in a if statement
max-bool-expr=5
# Maximum number of branch for function / method body
max-branches=12
# Maximum number of locals for function / method body
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body
max-returns=6
# Maximum number of statements in function / method body
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "Exception"
overgeneral-exceptions=Exception

View file

@ -1,53 +1,30 @@
# Travis CI configuration for automated .mpy file generation. # This is a common .travis.yml for generating library release zip files for
# Author: Tony DiCola # CircuitPython library releases using circuitpython-build-tools.
# License: Public Domain # See https://github.com/adafruit/circuitpython-build-tools for detailed setup
# This configuration will work with Travis CI (travis-ci.org) to automacially # instructions.
# build .mpy files for CircuitPython when a new tagged release is created. This
# file is relatively generic and can be shared across multiple repositories by
# following these steps:
# 1. Copy this file into a .travis.yml file in the root of the repository.
# 2. Change the deploy > file section below to list each of the .mpy files
# that should be generated. The config will automatically look for
# .py files with the same name as the source for generating the .mpy files.
# Note that the .mpy extension should be lower case!
# 3. Commit the .travis.yml file and push it to GitHub.
# 4. Go to travis-ci.org and find the repository (it needs to be setup to access
# your github account, and your github account needs access to write to the
# repo). Flip the 'ON' switch on for Travis and the repo, see the Travis
# docs for more details: https://docs.travis-ci.com/user/getting-started/
# 5. Get a GitHub 'personal access token' which has at least 'public_repo' or
# 'repo' scope: https://help.github.com/articles/creating-an-access-token-for-command-line-use/
# Keep this token safe and secure! Anyone with the token will be able to
# access and write to your GitHub repositories. Travis will use the token
# to attach the .mpy files to the release.
# 6. In the Travis CI settings for the repository that was enabled find the
# environment variable editing page: https://docs.travis-ci.com/user/environment-variables/#Defining-Variables-in-Repository-Settings
# Add an environment variable named GITHUB_TOKEN and set it to the value
# of the GitHub personal access token above. Keep 'Display value in build
# log' flipped off.
# 7. That's it! Tag a release and Travis should go to work to add .mpy files
# to the release. It takes about a 2-3 minutes for a worker to spin up,
# build mpy-cross, and add the binaries to the release.
language: generic
sudo: true dist: trusty
sudo: false
language: python
python:
- "3.6"
cache:
pip: true
deploy: deploy:
provider: releases provider: releases
api_key: $GITHUB_TOKEN api_key: $GITHUB_TOKEN
file: file_glob: true
- "adafruit_bme680.mpy" file: bundles/*
skip_cleanup: true skip_cleanup: true
on: on:
tags: true tags: true
before_install: install:
- sudo apt-get -yqq update - pip install pylint circuitpython-build-tools
- sudo apt-get install -y build-essential git python python-pip
- git clone https://github.com/adafruit/circuitpython.git -b 2.x
- make -C circuitpython/mpy-cross
- export PATH=$PATH:$PWD/circuitpython/mpy-cross/
- sudo pip install shyaml
before_deploy: script:
- shyaml get-values deploy.file < .travis.yml | sed 's/.mpy/.py/' | xargs -L1 mpy-cross - pylint adafruit_bme680.py
- ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name examples/*.py)
- circuitpython-build-bundles --filename_prefix adafruit-circuitpython-bme680 --library_location .

View file

@ -27,6 +27,7 @@ Usage Example
============= =============
.. code-block:: python .. code-block:: python
import gc import gc
from busio import I2C from busio import I2C
import adafruit_bme680 import adafruit_bme680
@ -38,17 +39,17 @@ Usage Example
# Create library object using our Bus I2C port # Create library object using our Bus I2C port
i2c = I2C(board.SCL, board.SDA) i2c = I2C(board.SCL, board.SDA)
bme280 = adafruit_bme680.Adafruit_BME680_I2C(i2c) bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c)
# change this to match the location's pressure (hPa) at sea level # change this to match the location's pressure (hPa) at sea level
bme280.seaLevelhPa = 1013.25 bme680.sea_level_pressure = 1013.25
while True: while True:
print("\nTemperature: %0.1f C" % bme280.temperature) print("\nTemperature: %0.1f C" % bme680.temperature)
print("Gas: %d ohm" % bme280.gas) print("Gas: %d ohm" % bme680.gas)
print("Humidity: %0.1f %%" % bme280.humidity) print("Humidity: %0.1f %%" % bme680.humidity)
print("Pressure: %0.1f hPa" % bme280.pressure) print("Pressure: %0.3f hPa" % bme680.pressure)
print("Altitude = %0.2f meters" % bme280.altitude) print("Altitude = %0.2f meters" % bme680.altitude)
time.sleep(2) time.sleep(2)

View file

@ -20,6 +20,9 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE. # THE SOFTWARE.
# We have a lot of attributes for this complex sensor.
# pylint: disable=too-many-instance-attributes
""" """
`adafruit_bme680` `adafruit_bme680`
==================================================== ====================================================
@ -29,7 +32,8 @@ CircuitPython driver from BME680 air quality sensor
* Author(s): ladyada * Author(s): ladyada
""" """
import time, math import time
import math
from micropython import const from micropython import const
try: try:
import struct import struct
@ -38,14 +42,14 @@ except ImportError:
# I2C ADDRESS/BITS/SETTINGS # I2C ADDRESS/BITS/SETTINGS
# ----------------------------------------------------------------------- # -----------------------------------------------------------------------
_BME680_CHIPID = const(0x61) _BME680_CHIPID = const(0x61)
_BME680_REG_CHIPID = const(0xD0) _BME680_REG_CHIPID = const(0xD0)
_BME680_BME680_COEFF_ADDR1 = const(0x89) _BME680_BME680_COEFF_ADDR1 = const(0x89)
_BME680_BME680_COEFF_ADDR2 = const(0xE1) _BME680_BME680_COEFF_ADDR2 = const(0xE1)
_BME680_BME680_RES_WAIT_0 = const(0x5A) _BME680_BME680_RES_WAIT_0 = const(0x5A)
_BME680_REG_SOFTRESET = const(0xE0) _BME680_REG_SOFTRESET = const(0xE0)
_BME680_REG_CTRL_GAS = const(0x71) _BME680_REG_CTRL_GAS = const(0x71)
_BME680_REG_CTRL_HUM = const(0x72) _BME680_REG_CTRL_HUM = const(0x72)
_BME280_REG_STATUS = const(0xF3) _BME280_REG_STATUS = const(0xF3)
@ -62,79 +66,103 @@ _BME680_FILTERSIZES = (0, 1, 3, 7, 15, 31, 63, 127)
_BME680_RUNGAS = const(0x10) _BME680_RUNGAS = const(0x10)
lookupTable1 = (2147483647.0, 2147483647.0, 2147483647.0, 2147483647.0, 2147483647.0, 2126008810.0, 2147483647.0, 2130303777.0, 2147483647.0, 2147483647.0, 2143188679.0, 2136746228.0, 2147483647.0, 2126008810.0, 2147483647.0, 2147483647.0) _LOOKUP_TABLE_1 = (2147483647.0, 2147483647.0, 2147483647.0, 2147483647.0, 2147483647.0,
2126008810.0, 2147483647.0, 2130303777.0, 2147483647.0, 2147483647.0,
2143188679.0, 2136746228.0, 2147483647.0, 2126008810.0, 2147483647.0,
2147483647.0)
lookupTable2 = (4096000000.0, 2048000000.0, 1024000000.0, 512000000.0, 255744255.0, 127110228.0, 64000000.0, 32258064.0, 16016016.0, 8000000.0, 4000000.0, 2000000.0, 1000000.0, 500000.0, 250000.0, 125000.0) _LOOKUP_TABLE_2 = (4096000000.0, 2048000000.0, 1024000000.0, 512000000.0, 255744255.0, 127110228.0,
64000000.0, 32258064.0, 16016016.0, 8000000.0, 4000000.0, 2000000.0, 1000000.0,
500000.0, 250000.0, 125000.0)
def _read24(arr):
"""Parse an unsigned 24-bit value as a floating point and return it."""
ret = 0.0
#print([hex(i) for i in arr])
for b in arr:
ret *= 256.0
ret += float(b & 0xFF)
return ret
class Adafruit_BME680: class Adafruit_BME680:
"""Driver from BME680 air quality sensor""" """Driver from BME680 air quality sensor"""
def __init__(self): def __init__(self):
"""Check the BME680 was found, read the coefficients and enable the sensor for continuous reads""" """Check the BME680 was found, read the coefficients and enable the sensor for continuous
reads"""
self._write(_BME680_REG_SOFTRESET, [0xB6]) self._write(_BME680_REG_SOFTRESET, [0xB6])
time.sleep(0.5) time.sleep(0.5)
# Check device ID. # Check device ID.
id = self._read_byte(_BME680_REG_CHIPID) chip_id = self._read_byte(_BME680_REG_CHIPID)
if _BME680_CHIPID != id: if _BME680_CHIPID != chip_id:
raise RuntimeError('Failed to find BME680! Chip ID 0x%x' % id) raise RuntimeError('Failed to find BME680! Chip ID 0x%x' % id)
self._read_coefficients() self._read_calibration()
# set up heater # set up heater
self._write(_BME680_BME680_RES_WAIT_0, [0x73, 0x64, 0x65]) self._write(_BME680_BME680_RES_WAIT_0, [0x73, 0x64, 0x65])
self.seaLevelhPa = 1013.25 self.sea_level_pressure = 1013.25
"""Pressure in hectoPascals at sea level. Used to calibrate `altitude`.""" """Pressure in hectoPascals at sea level. Used to calibrate `altitude`."""
self.osrs_p = 4 self.pressure_oversample = 4
self.osrs_t = 8 self.temperature_oversample = 8
self.osrs_h = 2 self.humidity_oversample = 2
self.filter = 2 self.filter_size = 3
self._adc_pres = None
self._adc_temp = None
self._adc_hum = None
self._adc_gas = None
self._gas_range = None
self._t_fine = None
self._status = 0
@property @property
def pressure_oversample(self): def pressure_oversample(self):
"""The oversampling for pressure sensor""" """The oversampling for pressure sensor"""
return _BME680_SAMPLERATES[self.osrs_p] return _BME680_SAMPLERATES[self._pressure_oversample]
@pressure_oversample.setter @pressure_oversample.setter
def pressure_oversample(self, os): def pressure_oversample(self, sample_rate):
if os in _BME680_SAMPLERATES: if sample_rate in _BME680_SAMPLERATES:
self.osrs_p = _BME680_SAMPLERATES.index(os) self._pressure_oversample = _BME680_SAMPLERATES.index(sample_rate)
else: else:
raise RuntimeError("Invalid oversample") raise RuntimeError("Invalid oversample")
@property @property
def humidity_oversample(self): def humidity_oversample(self):
"""The oversampling for humidity sensor""" """The oversampling for humidity sensor"""
return _BME680_SAMPLERATES[self.osrs_h] return _BME680_SAMPLERATES[self._humidity_oversample]
@humidity_oversample.setter @humidity_oversample.setter
def humidity_oversample(self, os): def humidity_oversample(self, sample_rate):
if os in _BME680_SAMPLERATES: if sample_rate in _BME680_SAMPLERATES:
self.osrs_h = _BME680_SAMPLERATES.index(os) self._humidity_oversample = _BME680_SAMPLERATES.index(sample_rate)
else: else:
raise RuntimeError("Invalid oversample") raise RuntimeError("Invalid oversample")
@property @property
def temperature_oversample(self): def temperature_oversample(self):
"""The oversampling for temperature sensor""" """The oversampling for temperature sensor"""
return _BME680_SAMPLERATES[self.osrs_p] return _BME680_SAMPLERATES[self._pressure_oversample]
@temperature_oversample.setter @temperature_oversample.setter
def temperature_oversample(self, os): def temperature_oversample(self, sample_rate):
if os in _BME680_SAMPLERATES: if sample_rate in _BME680_SAMPLERATES:
self.osrs_t = _BME680_SAMPLERATES.index(os) self._temp_oversample = _BME680_SAMPLERATES.index(sample_rate)
else: else:
raise RuntimeError("Invalid oversample") raise RuntimeError("Invalid oversample")
@property @property
def filter_size(self): def filter_size(self):
"""The filter size for the built in IIR filter""" """The filter size for the built in IIR filter"""
return _BME680_FILTERSIZES[self.filter] return _BME680_FILTERSIZES[self._filter]
@filter_size.setter @filter_size.setter
def filter_size(self, fs): def filter_size(self, size):
if fs in _BME680_FILTERSIZES: if size in _BME680_FILTERSIZES:
self.filter = _BME680_FILTERSIZES(fs) self._filter = _BME680_FILTERSIZES[size]
else: else:
raise RuntimeError("Invalid size") raise RuntimeError("Invalid size")
@ -142,46 +170,46 @@ class Adafruit_BME680:
def temperature(self): def temperature(self):
"""The compensated temperature in degrees celsius.""" """The compensated temperature in degrees celsius."""
self._perform_reading() self._perform_reading()
var1 = (self._adc_temp / 8) - (self._T1 * 2) calc_temp = (((self._t_fine * 5) + 128) / 256)
var2 = (var1 * self._T2) / 2048
var3 = ((var1 / 2) * (var1 / 2)) / 4096
var3 = (var3 * self._T3 * 16) / 16384
self.t_fine = int(var2 + var3)
calc_temp = (((self.t_fine * 5) + 128) / 256)
return calc_temp / 100 return calc_temp / 100
@property @property
def pressure(self): def pressure(self):
"""The barometric pressure in hectoPascals""" """The barometric pressure in hectoPascals"""
self.temperature self._perform_reading()
var1 = (self.t_fine / 2) - 64000 var1 = (self._t_fine / 2) - 64000
var2 = ((var1 / 4) * (var1 / 4)) / 2048 var2 = ((var1 / 4) * (var1 / 4)) / 2048
var2 = (var2 * self._P6) / 4 var2 = (var2 * self._pressure_calibration[5]) / 4
var2 = var2 + (var1 * self._P5 * 2) var2 = var2 + (var1 * self._pressure_calibration[4] * 2)
var2 = (var2 / 4) + (self._P4 * 65536) var2 = (var2 / 4) + (self._pressure_calibration[3] * 65536)
var1 = ((var1 / 4) * (var1 / 4)) / 8192 var1 = ((var1 / 4) * (var1 / 4)) / 8192
var1 = ((var1 * self._P3 * 32) / 8) + ((self._P2 * var1) / 2) var1 = (((var1 * self._pressure_calibration[2] * 32) / 8) +
((self._pressure_calibration[1] * var1) / 2))
var1 = var1 / 262144 var1 = var1 / 262144
var1 = ((32768 + var1) * self._P1) / 32768 var1 = ((32768 + var1) * self._pressure_calibration[0]) / 32768
calc_pres = 1048576 - self._adc_pres calc_pres = 1048576 - self._adc_pres
calc_pres = (calc_pres - (var2 / 4096)) * 3125 calc_pres = (calc_pres - (var2 / 4096)) * 3125
calc_pres = (calc_pres / var1) * 2 calc_pres = (calc_pres / var1) * 2
var1 = (self._P9 * (((calc_pres / 8) * (calc_pres / 8)) / 8192)) / 4096 var1 = (self._pressure_calibration[8] * (((calc_pres / 8) * (calc_pres / 8)) / 8192)) / 4096
var2 = ((calc_pres / 4) * self._P8) / 8192 var2 = ((calc_pres / 4) * self._pressure_calibration[7]) / 8192
var3 = ((calc_pres / 256) * (calc_pres / 256) * (calc_pres / 256) * self._P10) / 131072 var3 = (((calc_pres / 256) ** 3) * self._pressure_calibration[9]) / 131072
calc_pres += ((var1 + var2 + var3 + (self._P7 * 128)) / 16) calc_pres += ((var1 + var2 + var3 + (self._pressure_calibration[6] * 128)) / 16)
return calc_pres/100 return calc_pres/100
@property @property
def humidity(self): def humidity(self):
"""The relative humidity in RH %""" """The relative humidity in RH %"""
self.temperature # Trigger a read self._perform_reading()
temp_scaled = ((self.t_fine * 5) + 128) / 256 temp_scaled = ((self._t_fine * 5) + 128) / 256
var1 = (self._adc_hum - (self._H1 * 16)) - ((temp_scaled * self._H3) / 200) var1 = ((self._adc_hum - (self._humidity_calibration[0] * 16)) -
var2 = (self._H2 * (((temp_scaled * self._H4) / 100) + (((temp_scaled * ((temp_scaled * self._H5) / 100)) / 64) / 100) + 16384)) / 1024 ((temp_scaled * self._humidity_calibration[2]) / 200))
var2 = (self._humidity_calibration[1] *
(((temp_scaled * self._humidity_calibration[3]) / 100) +
(((temp_scaled * ((temp_scaled * self._humidity_calibration[4]) / 100)) /
64) / 100) + 16384)) / 1024
var3 = var1 * var2 var3 = var1 * var2
var4 = self._H6 * 128 var4 = self._humidity_calibration[5] * 128
var4 = (var4 + ((temp_scaled * self._H7) / 100)) / 16 var4 = (var4 + ((temp_scaled * self._humidity_calibration[6]) / 100)) / 16
var5 = ((var3 / 16384) * (var3 / 16384)) / 1024 var5 = ((var3 / 16384) * (var3 / 16384)) / 1024
var6 = (var4 * var5) / 2 var6 = (var4 * var5) / 2
calc_hum = (((var3 + var6) / 1024) * 1000) / 4096 calc_hum = (((var3 + var6) / 1024) * 1000) / 4096
@ -195,44 +223,48 @@ class Adafruit_BME680:
@property @property
def altitude(self): def altitude(self):
"""The altitude based on current `pressure` vs the sea level pressure (`seaLevelhPa`) - which you must enter ahead of time)""" """The altitude based on current `pressure` vs the sea level pressure
p = self.pressure # in Si units for hPascal (`sea_level_pressure`) - which you must enter ahead of time)"""
return 44330 * (1.0 - math.pow(p / self.seaLevelhPa, 0.1903)); pressure = self.pressure # in Si units for hPascal
return 44330 * (1.0 - math.pow(pressure / self.sea_level_pressure, 0.1903))
@property @property
def gas(self): def gas(self):
"""The gas resistance in ohms""" """The gas resistance in ohms"""
self._perform_reading() self._perform_reading()
var1 = ((1340 + (5 * self._sw_err)) * (lookupTable1[self._gas_range])) / 65536 var1 = ((1340 + (5 * self._sw_err)) * (_LOOKUP_TABLE_1[self._gas_range])) / 65536
var2 = ((self._adc_gas * 32768) - 16777216) + var1 var2 = ((self._adc_gas * 32768) - 16777216) + var1
var3 = (lookupTable2[self._gas_range] * var1) / 512 var3 = (_LOOKUP_TABLE_2[self._gas_range] * var1) / 512
calc_gas_res = (var3 + (var2 / 2)) / var2 calc_gas_res = (var3 + (var2 / 2)) / var2
return int(calc_gas_res) return int(calc_gas_res)
def _perform_reading(self): def _perform_reading(self):
"""Perform a single-shot reading from the sensor and fill internal data structure for calculations""" """Perform a single-shot reading from the sensor and fill internal data structure for
calculations"""
# set filter # set filter
self._write(_BME680_REG_CONFIG, [self.filter << 2]) self._write(_BME680_REG_CONFIG, [self._filter << 2])
# turn on temp oversample & pressure oversample # turn on temp oversample & pressure oversample
self._write(_BME680_REG_CTRL_MEAS, [(self.osrs_t << 5)|(self.osrs_p << 2)]) self._write(_BME680_REG_CTRL_MEAS,
[(self._temp_oversample << 5)|(self._pressure_oversample << 2)])
# turn on humidity oversample # turn on humidity oversample
self._write(_BME680_REG_CTRL_HUM, [self.osrs_h]) self._write(_BME680_REG_CTRL_HUM, [self._humidity_oversample])
# gas measurements enabled # gas measurements enabled
self._write(_BME680_REG_CTRL_GAS, [_BME680_RUNGAS]) self._write(_BME680_REG_CTRL_GAS, [_BME680_RUNGAS])
v = self._read(_BME680_REG_CTRL_MEAS, 1)[0] ctrl = self._read(_BME680_REG_CTRL_MEAS, 1)[0]
v = (v & 0xFC) | 0x01 # enable single shot! ctrl = (ctrl & 0xFC) | 0x01 # enable single shot!
self._write(_BME680_REG_CTRL_MEAS, [v]) self._write(_BME680_REG_CTRL_MEAS, [ctrl])
time.sleep(0.5) time.sleep(0.5)
data = self._read(_BME680_REG_STATUS, 15) data = self._read(_BME680_REG_STATUS, 15)
self._status = data[0] & 0x80 self._status = data[0] & 0x80
gas_idx = data[0] & 0x0F #gas_idx = data[0] & 0x0F
meas_idx = data[1] #meas_idx = data[1]
#print("status 0x%x gas_idx %d meas_idx %d" % (status, gas_idx, meas_idx)) #print("status 0x%x gas_idx %d meas_idx %d" % (self._status, gas_idx, meas_idx))
self._adc_pres = self._read24(data[2:5]) / 16 #print([hex(i) for i in data])
self._adc_temp = self._read24(data[5:8]) / 16 self._adc_pres = _read24(data[2:5]) / 16
self._adc_temp = _read24(data[5:8]) / 16
self._adc_hum = struct.unpack('>H', bytes(data[8:10]))[0] self._adc_hum = struct.unpack('>H', bytes(data[8:10]))[0]
self._adc_gas = int(struct.unpack('>H', bytes(data[13:15]))[0] / 64) self._adc_gas = int(struct.unpack('>H', bytes(data[13:15]))[0] / 64)
self._gas_range = data[14] & 0x0F self._gas_range = data[14] & 0x0F
@ -240,16 +272,13 @@ class Adafruit_BME680:
#print(self._adc_gas) #print(self._adc_gas)
self._status |= data[14] & 0x30 # VALID + STABILITY mask self._status |= data[14] & 0x30 # VALID + STABILITY mask
def _read24(self, arr): var1 = (self._adc_temp / 8) - (self._temp_calibration[0] * 2)
"""Parse an unsigned 24-bit value as a floating point and return it.""" var2 = (var1 * self._temp_calibration[1]) / 2048
ret = 0.0 var3 = ((var1 / 2) * (var1 / 2)) / 4096
#print([hex(i) for i in arr]) var3 = (var3 * self._temp_calibration[2] * 16) / 16384
for b in arr: self._t_fine = int(var2 + var3)
ret *= 256.0
ret += float(b & 0xFF)
return ret
def _read_coefficients(self): def _read_calibration(self):
"""Read & save the calibration coefficients""" """Read & save the calibration coefficients"""
coeff = self._read(_BME680_BME680_COEFF_ADDR1, 25) coeff = self._read(_BME680_BME680_COEFF_ADDR1, 25)
coeff += self._read(_BME680_BME680_COEFF_ADDR2, 16) coeff += self._read(_BME680_BME680_COEFF_ADDR2, 16)
@ -257,30 +286,57 @@ class Adafruit_BME680:
coeff = list(struct.unpack('<hbBHhbBhhbbHhhBBBHbbbBbHhbb', bytes(coeff[1:]))) coeff = list(struct.unpack('<hbBHhbBhhbbHhhBBBHbbbBbHhbb', bytes(coeff[1:])))
#print("\n\n",coeff) #print("\n\n",coeff)
coeff = [float(i) for i in coeff] coeff = [float(i) for i in coeff]
self._T2,self._T3, skip, self._P1,self._P2,self._P3, skip, self._P4,self._P5,self._P7,self._P6, skip,self._P8,self._P9,self._P10, skip, h2m, self._H1,self._H3,self._H4,self._H5,self._H6,self._H7,self._T1,self._G2,self._G1,self._G3 = coeff self._temp_calibration = [coeff[x] for x in [23, 0, 1]]
self._pressure_calibration = [coeff[x] for x in [3, 4, 5, 7, 8, 10, 9, 12, 13, 14]]
self._humidity_calibration = [coeff[x] for x in [17, 16, 18, 19, 20, 21, 22]]
self._gas_calibration = [coeff[x] for x in [25, 24, 26]]
# flip around H1 & H2 # flip around H1 & H2
self._H2 = h2m * 16 + (self._H1 % 16) self._humidity_calibration[1] *= 16
self._H1 /= 16 self._humidity_calibration[1] += self._humidity_calibration[0] % 16
self._humidity_calibration[0] /= 16
self._heat_range = (self._read(0x02, 1)[0] & 0x30) / 16 self._heat_range = (self._read(0x02, 1)[0] & 0x30) / 16
self._heat_val = self._read(0x00, 1)[0] self._heat_val = self._read(0x00, 1)[0]
self._sw_err = (self._read(0x04, 1)[0] & 0xF0) / 16 self._sw_err = (self._read(0x04, 1)[0] & 0xF0) / 16
#print("T1-3: %d %d %d" % (self._T1, self._T2, self._T3)) """
#print("P1-3: %d %d %d" % (self._P1, self._P2, self._P3)) print("T1-3: %d %d %d" % (self._temp_calibration[0],
#print("P4-6: %d %d %d" % (self._P4, self._P5, self._P6)) self._temp_calibration[1],
#print("P7-9: %d %d %d" % (self._P7, self._P8, self._P9)) self._temp_calibration[2]))
#print("P10: %d" % self._P10) print("P1-3: %d %d %d" % (self._pressure_calibration[0],
#print("H1-3: %d %d %d" % (self._H1, self._H2, self._H3)) self._pressure_calibration[1],
#print("H4-7: %d %d %d %d" % (self._H4, self._H5, self._H6, self._H7)) self._pressure_calibration[2]))
#print("G1-3: %d %d %d" % (self._G1, self._G2, self._G3)) print("P4-6: %d %d %d" % (self._pressure_calibration[3],
#print("HR %d HV %d SWERR %d" % (self._HEATRANGE, self._HEATVAL, self._SWERR)) self._pressure_calibration[4],
self._pressure_calibration[5]))
print("P7-9: %d %d %d" % (self._pressure_calibration[6],
self._pressure_calibration[7],
self._pressure_calibration[8]))
print("P10: %d" % self._pressure_calibration[9])
print("H1-3: %d %d %d" % (self._humidity_calibration[0],
self._humidity_calibration[1],
self._humidity_calibration[2]))
print("H4-7: %d %d %d %d" % (self._humidity_calibration[3],
self._humidity_calibration[4],
self._humidity_calibration[5],
self._humidity_calibration[6]))
print("G1-3: %d %d %d" % (self._gas_calibration[0],
self._gas_calibration[1],
self._gas_calibration[2]))
print("HR %d HV %d SWERR %d" % (self._heat_range, self._heat_val, self._sw_err))
"""
def _read_byte(self, register): def _read_byte(self, register):
"""Read a byte register value and return it""" """Read a byte register value and return it"""
return self._read(register, 1)[0] return self._read(register, 1)[0]
def _read(self, register, length):
raise NotImplementedError()
def _write(self, register, values):
raise NotImplementedError()
class Adafruit_BME680_I2C(Adafruit_BME680): class Adafruit_BME680_I2C(Adafruit_BME680):
"""Driver for I2C connected BME680.""" """Driver for I2C connected BME680."""
def __init__(self, i2c, address=0x77, debug=False): def __init__(self, i2c, address=0x77, debug=False):

21
examples/main.py Normal file
View file

@ -0,0 +1,21 @@
import gc
from busio import I2C
import adafruit_bme680
import time
import board
# Create library object using our Bus I2C port
i2c = I2C(board.SCL, board.SDA)
bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False)
# change this to match the location's pressure (hPa) at sea level
bme680.sea_level_pressure = 1013.25
while True:
print("\nTemperature: %0.1f C" % bme680.temperature)
print("Gas: %d ohm" % bme680.gas)
print("Humidity: %0.1f %%" % bme680.humidity)
print("Pressure: %0.3f hPa" % bme680.pressure)
print("Altitude = %0.2f meters" % bme680.altitude)
time.sleep(1)

View file

@ -1,2 +1,3 @@
python:
version: 3
requirements_file: requirements.txt requirements_file: requirements.txt