Compare commits

...

49 commits

Author SHA1 Message Date
dherrada
25c8977b2c Fixed discord invite link 2020-07-08 16:49:04 -04:00
Limor "Ladyada" Fried
394cb7aa22
Merge pull request #38 from JanHBade/master
Fixes Issue #36
2020-06-14 14:45:52 -04:00
JanHBade
1a70659082
Update README.rst 2020-06-14 13:17:20 +02:00
JanHBade
0b9d6f69e3
Update README.rst
typo
2020-06-14 13:16:57 +02:00
JanHBade
e224735f69
Update README.rst
Fixes Issue #36 (https://github.com/adafruit/Adafruit_CircuitPython_BME280/issues/36)
2020-06-14 13:16:26 +02:00
Scott Shawcroft
87e54ce603
Merge pull request #35 from adafruit/black-update
Black reformatting with Python 3 target.
2020-04-08 10:13:50 -07:00
Kattni Rembor
fdad5ab978 Black reformatting with Python 3 target. 2020-04-08 13:08:26 -04:00
sommersoft
b34ce92a37 build.yml: add black formatting check
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-04-07 16:07:55 -05:00
Kattni
0c85112fb6
Merge pull request #34 from adafruit/pylint-update
Ran black, updated to pylint 2.x
2020-03-17 16:44:44 -04:00
dherrada
575558059f Re-added --force-reinstall 2020-03-17 14:46:05 -04:00
dherrada
6fb01e73c4 Ran black, updated to pylint 2.x 2020-03-16 15:16:30 -04:00
sommersoft
44a11a1b97 update code of coduct: discord moderation contact section
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-03-15 18:20:47 -05:00
Kattni
421567b49a
Merge pull request #33 from sommersoft/patch_coc
Update Code of Conduct
2020-03-13 15:00:42 -04:00
sommersoft
3dd1c232d3 update code of conduct 2020-03-13 13:18:42 -05:00
sommersoft
39affff5f3 build.yml: move pylint, black, and Sphinx installs to each repo; add description to 'actions-ci/install.sh'
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-03-05 10:05:47 -06:00
sommersoft
80757ff214 update pylint examples directive
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-01-14 17:07:24 -06:00
Limor "Ladyada" Fried
2f362f7c7f
Merge pull request #30 from adafruit/dherrada-patch-1
Moved repository from Travis to GitHub Actions
2019-12-27 22:42:58 -05:00
dherrada
ac5d1c7bb2 Moved repository from Travis to GitHub Actions 2019-12-27 22:24:07 -05:00
Kattni
d4e476ad79
Merge pull request #28 from adafruit/dherrada-patch-1
Removed building locally section from README, replaced with documenta…
2019-10-21 19:56:52 -04:00
dherrada
8311b76857
Removed building locally section from README, replaced with documentation section 2019-10-17 18:16:39 -04:00
Limor "Ladyada" Fried
30bd4c3b36
Merge pull request #27 from ncguk/patch-1
Minor comment cleanup
2019-07-26 19:37:08 -04:00
ncguk
f06bc781ef
Minor comment cleanup
A typo and a couple of trivial formatting tweaks for consistency. No code changes.
2019-07-27 00:16:10 +01:00
Limor "Ladyada" Fried
53e09304e0
Merge pull request #26 from barbudor/master
fix #25 + fix #19 + refactor `pressure` property
2019-06-17 12:33:25 -04:00
Barbudor
8975faee83 fix #19 with proper struct unpack
tested with simulation:
# 0xE1 / 0xE2         dig_H2 [7:0]  / [15:8]    signed short
# 0xE3                dig_H3 [7:0]              unsigned char
# 0xE4 / 0xE5[3:0]    dig_H4 [11:4] / [3:0]     signed short
# 0xE5[7:4] / 0xE6    dig_H5 [3:0]  / [11:4]    signed short
# 0xE7                dig_H6                    signed char

>>> coeff = [ 0x12, 0xFF, 0xAA, 0xEE, 0x46, 0xCC, 0x88 ]
>>> coeff = list(struct.unpack('<hBbBbb', bytes(coeff)))
>>> float(coeff[0])                                 # 0xFF12 -> -238.0
-238.0
>>> float(coeff[1])                                 # 0xAA -> 170.0
170.0
>>> float((coeff[2] << 4) |  (coeff[3] & 0xF))      # 0xEE6 -> -282.0
-282.0
>>> float((coeff[4] << 4) | (coeff[3] >> 4))        # 0xCC4 -> -828.0
-828.0
>>> float(coeff[5])                                 # 0x88 -> -120.0
-120.0
>>>
2019-06-01 15:55:02 +02:00
Barbudor
a2d13f1ada refactor pressure property to handle ZeroDivision case
Recap: in the `pressure` property there is a test `if var1 == 0:` in order to avoid a division-by-zero exception. Current code return a pressure of 0 in that case.
It was suggested that my PR makes this a little more pythonic by usage of exception raise.

Analysis of the root cause: because last calculation is
```var1 = (1.0 + var1 / 32768.0) * self._pressure_calib[0]```
the only reason for `var1` to be 0 is `self._pressure_calib[0]` is 0. Calibration values are read at init time from registers in the chip. So the root cause probably relates to a register read problem.

Analysis of other similar codes
Bosch bme280.c (Github): if var1 == 0, return minimum valid pressure (300hPa).
Adafruit CiPy BMP280 driver:
  => initially, no tests were performed
  => In Feb, jraber implemeted return 0 in a commit named "Adopt changes from the BME280 library"
  => In Mar, jraber implemeted return minimum value in a commit named "Remove unnecessary 'if' and 'else' in the pressure property"
Adafruit CiPy BMP680 driver: not tested => ZeroDivisionError

I feel that returning silently the minimun valid pressure is not correct to draw attention on a possible hardware reliability problem. Returning 0 could make sense only if we were sure that the user was testing the return value against 0.
Alternatively, letting the ZeroDivisionError occur will not provide proper clue to the user as to the root cause of the problem and will probably lead to this issue to be raised again as a bug in GitHub.

Proposed solution:
Test against 0 and raise a ArithmeticError with message "Invalid calculation possibly related to error while reading the calibration registers"
2019-06-01 13:25:35 +02:00
Barbudor
cf74245929 fix issue#25 (removed frozenset()) + refactor pressure property
Removed `frozenset()` on `_BME280_IIR_FILTERS`, `_BME280_MODES`, `_BME280_STANDBY_TCS`. Kept as tuples.

Removed useless `if/else` in property `pressure` (was pointed by pylint)
2019-05-31 23:51:07 +02:00
Melissa LeBlanc-Williams
febcd51983
Merge pull request #22 from jraber/master
Add class attributes to allow more control over the sensor
2019-03-12 22:47:20 -07:00
Jeff Raber
0a10d868a6 Don't enable SPI 3-wire interface 2019-03-13 00:34:33 -05:00
Jeff Raber
9c37a711e2 Always write the new mode to the sensor
In FORCE mode, the sensor changes back to SLEEP after completeing a single
measurement, but we are not updating the mode internally.  It's better to
always write the mode to the sensor, and trust the caller not to change it
needlessly.
2019-03-12 23:42:40 -05:00
Jeff Raber
f40fb2c9d4 Add properties for the typical and maximum measurement time
Changed_BME280_OVERSCANS from frozenset to dict to allow lookup
 of the associated value for the measurement time calculation
2019-03-07 03:17:02 -06:00
Jeff Raber
79d4e8556e Do not return None when temp, pressure, or humidity value = 0x80000
0x800000 is the *default* value and is a valid value
2019-03-07 02:04:27 -06:00
Jeff Raber
ef0eef6145 Refactor to remove dependency on the enum class
Removed references to the enum class, while keeping the same
functionality

Updated the 'normal mode' example
2019-03-01 08:13:40 -06:00
Jeff Raber
a8c12e76b0 Fix-up example 2019-03-01 00:46:21 -06:00
Jeff Raber
ccf536384a Added and example for setting the mode, overscan, standby, and iir_filter 2019-02-28 22:57:54 -06:00
Jeff Raber
3b37d55d0e Add disable=too-many-instance-attributes to keep pylint happy 2019-02-28 07:52:20 -06:00
Jeff Raber
3284ed4fc0 Fix __write_config, docstring comes first 2019-02-27 08:58:32 -06:00
Jeff Raber
e9d7320639 Fix typo: standy -> standby 2019-02-27 08:50:04 -06:00
Jeff Raber
29af22eabc Default normal_flag to False to avoid UnboundLocalError in _write_config 2019-02-27 08:35:14 -06:00
Jeff Raber
032d38c749 Increase underline length to make sphinx happy 2019-02-27 01:38:19 -06:00
Jeff Raber
dc89e0becd Fix-up overscan_tempearure as it was returning the wrong value 2019-02-27 01:36:06 -06:00
Jeff Raber
3ebd5c3075 Add class attributes to allow more control over the sensor
Add attributes for IIR filter, standby period, operation mode,
 and overscan for temperature, pressure and humidity.

Add Enum classes for the overscan, standby, and iir filter values
2019-02-27 00:37:49 -06:00
Kattni
a18166df5d
Merge pull request #20 from sommersoft/readme_fix_travis
Update README Travis Badge
2018-12-21 13:45:13 -06:00
sommersoft
e3cadc96cb change 'travis-ci.org' to 'travis-ci.com' 2018-12-21 13:22:49 -06:00
Scott Shawcroft
80fedb78fa
Merge pull request #18 from robert-hh/master
adafruit_bme280.py: Fix the value of dig_H5
2018-11-25 22:15:55 -08:00
hh
e947bde6bb adafruit_bme280.py: Fix the value of dig_H5
The calculation of dig_H5 from the calibration data did not match the
definition of the data sheet and the Bosch sample code. As a result,
the compensated relative humidity data could have been calculated wrong.
2018-11-17 08:51:21 +01:00
Brennen Bearnes
2ce3755316
Merge pull request #16 from adafruit/pypi-readme-update
update to PyPi instructions in readme
2018-10-31 17:55:13 -06:00
Kattni
9f4c59bffb
update to PyPi instructions in readme 2018-10-31 16:44:07 -04:00
sommersoft
1416d93bc6 ignore the board module imports in .pylintrc
Signed-off-by: sommersoft <sommersoft@gmail.com>
2018-08-25 14:06:25 +00:00
Kattni
403cee347c
Merge pull request #13 from adafruit/revert-12-add-dew-point
Revert "Added dew point, updated example"
2018-08-14 16:43:28 -04:00
12 changed files with 714 additions and 270 deletions

57
.github/workflows/build.yml vendored Normal file
View file

@ -0,0 +1,57 @@
name: Build CI
on: [pull_request, push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- name: Translate Repo Name For Build Tools filename_prefix
id: repo-name
run: |
echo ::set-output name=repo-name::$(
echo ${{ github.repository }} |
awk -F '\/' '{ print tolower($2) }' |
tr '_' '-'
)
- name: Set up Python 3.6
uses: actions/setup-python@v1
with:
python-version: 3.6
- name: Versions
run: |
python3 --version
- name: Checkout Current Repo
uses: actions/checkout@v1
with:
submodules: true
- name: Checkout tools repo
uses: actions/checkout@v2
with:
repository: adafruit/actions-ci-circuitpython-libs
path: actions-ci
- name: Install dependencies
# (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.)
run: |
source actions-ci/install.sh
- name: Pip install pylint, black, & Sphinx
run: |
pip install --force-reinstall pylint black==19.10b0 Sphinx sphinx-rtd-theme
- name: Library version
run: git describe --dirty --always --tags
- name: Check formatting
run: |
black --check --target-version=py35 .
- name: PyLint
run: |
pylint $( find . -path './adafruit*.py' )
([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace $( find . -path "./examples/*.py" ))
- name: Build assets
run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location .
- name: Build docs
working-directory: docs
run: sphinx-build -E -W -b html . _build/html

81
.github/workflows/release.yml vendored Normal file
View file

@ -0,0 +1,81 @@
name: Release Actions
on:
release:
types: [published]
jobs:
upload-release-assets:
runs-on: ubuntu-latest
steps:
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- name: Translate Repo Name For Build Tools filename_prefix
id: repo-name
run: |
echo ::set-output name=repo-name::$(
echo ${{ github.repository }} |
awk -F '\/' '{ print tolower($2) }' |
tr '_' '-'
)
- name: Set up Python 3.6
uses: actions/setup-python@v1
with:
python-version: 3.6
- name: Versions
run: |
python3 --version
- name: Checkout Current Repo
uses: actions/checkout@v1
with:
submodules: true
- name: Checkout tools repo
uses: actions/checkout@v2
with:
repository: adafruit/actions-ci-circuitpython-libs
path: actions-ci
- name: Install deps
run: |
source actions-ci/install.sh
- name: Build assets
run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location .
- name: Upload Release Assets
# the 'official' actions version does not yet support dynamically
# supplying asset names to upload. @csexton's version chosen based on
# discussion in the issue below, as its the simplest to implement and
# allows for selecting files with a pattern.
# https://github.com/actions/upload-release-asset/issues/4
#uses: actions/upload-release-asset@v1.0.1
uses: csexton/release-asset-action@master
with:
pattern: "bundles/*"
github-token: ${{ secrets.GITHUB_TOKEN }}
upload-pypi:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Check For setup.py
id: need-pypi
run: |
echo ::set-output name=setup-py::$( find . -wholename './setup.py' )
- name: Set up Python
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
uses: actions/setup-python@v1
with:
python-version: '3.x'
- name: Install dependencies
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine
- name: Build and publish
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
env:
TWINE_USERNAME: ${{ secrets.pypi_username }}
TWINE_PASSWORD: ${{ secrets.pypi_password }}
run: |
python setup.py sdist
twine upload dist/*

2
.gitignore vendored
View file

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

View file

@ -18,6 +18,7 @@ ignore-patterns=
#init-hook=
# Use multiple processes to speed up Pylint.
# jobs=1
jobs=2
# List of plugins (as comma separated values of python modules names) to load,
@ -50,7 +51,8 @@ confidence=
# --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
# disable=import-error,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
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,bad-continuation
# 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
@ -117,7 +119,8 @@ spelling-store-unknown-words=no
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,XXX,TODO
# notes=FIXME,XXX,TODO
notes=FIXME,XXX
[TYPECHECK]
@ -153,7 +156,7 @@ ignored-classes=optparse.Values,thread._local,_thread._local
# (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=
ignored-modules=board
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
@ -200,6 +203,7 @@ 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=
expected-line-ending-format=LF
# Regexp for a line that is allowed to be longer than the limit.
@ -272,9 +276,11 @@ class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
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]+$
class-name-hint=[A-Z_][a-zA-Z0-9_]+$
# Regular expression matching correct class names
# class-rgx=[A-Z_][a-zA-Z0-9]+$
class-rgx=[A-Z_][a-zA-Z0-9_]+$
# Naming hint for constant names
@ -294,7 +300,8 @@ function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
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,_
# good-names=i,j,k,ex,Run,_
good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_
# Include a hint for the correct naming format with invalid-name
include-naming-hint=no
@ -391,6 +398,7 @@ valid-metaclass-classmethod-first-arg=mcs
max-args=5
# Maximum number of attributes for a class (see R0902).
# max-attributes=7
max-attributes=11
# Maximum number of boolean expressions in a if statement
@ -415,7 +423,7 @@ max-returns=6
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
min-public-methods=1
[EXCEPTIONS]

View file

@ -1,32 +0,0 @@
dist: trusty
sudo: false
language: python
python:
- '3.6'
cache:
pip: true
deploy:
- provider: releases
api_key: "$GITHUB_TOKEN"
file_glob: true
file: "$TRAVIS_BUILD_DIR/bundles/*"
skip_cleanup: true
overwrite: true
on:
tags: true
- provider: pypi
user: adafruit-travis
on:
tags: true
password:
secure: hDbyx3IZpDVgmgbtrcZjmqgBCzDTwO0q0CqJJOMdCfAs7sGwW4GjhbAAxOqQAd9RS2pWbrmTRkToOxx/KML9HY+do1z4W2SPXCqYdVVAx5E2Krr8N5PjFmliTnOtWe+Y6JKQYE6di88CqIv9eaYiDEdOlExt69wRQh1pgJTOvNtmndGiXN2swQYVI8ta/pRVUtlpV2/KPczPnWH4CfWpw5ow8T+ldk+0lgPGO3c4IhcgIY1IVWimAbIPlrFT7QAGeqE+YvC3Fyl5HflCbo81GYJkCjo8LWnN27pIwFa51Z8XTh2CtjlOns5U4InuJx/dqQ9aMUsagv+HEBmwA/J+dyFf8c1KuaJkmvF0Q+nqHLfBd4hQ1V78eURqu2LWz0K/vCLUK21icCwjZKrLDysa58WJQnBqgJmE2yVnVC8w/1w9vY5taRVZbzMD4mEurYdo06b0QqiL7NyYhIEMmTFkEu5JEbFPZexk29UvPH4KsDtJEyfkfSqr8y5K1R7gn04Ej0RbAcJWLBtWIPtxeN//nGT6JPDpv/ZJIdemaWZ4iqE7Qw24bQhH+Dgk+tpaXW7Dzm49AXs3R9KzC+fAEag5FKgWHyttucB3j9zVf2SQ3YnYL12PCQxAzWSVcIqrR43uQTtonRHvo3F+4j4LTL7Ck+fFBNh2BJvLA6s75CQa6T8=
install:
- pip install -r requirements.txt
- pip install pylint circuitpython-build-tools Sphinx sphinx-rtd-theme
- pip install --force-reinstall pylint==1.9.2
script:
- pylint adafruit_bme280.py
- ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name examples/*.py)
- circuitpython-build-bundles --filename_prefix adafruit-circuitpython-bme280 --library_location
.
- cd docs && sphinx-build -E -W -b html . _build/html && cd ..

View file

@ -1,74 +1,129 @@
# Contributor Covenant Code of Conduct
# Adafruit Community Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
contributors and leaders pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
size, disability, ethnicity, gender identity and expression, level or type of
experience, education, socio-economic status, nationality, personal appearance,
race, religion, or sexual identity and orientation.
## Our Standards
We are committed to providing a friendly, safe and welcoming environment for
all.
Examples of behavior that contributes to creating a positive environment
include:
* Be kind and courteous to others
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Collaborating with other community members
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* The use of sexualized language or imagery and sexual attention or advances
* The use of inappropriate images, including in a community member's avatar
* The use of inappropriate language, including in a community member's nickname
* Any spamming, flaming, baiting or other attention-stealing behavior
* Excessive or unwelcome helping; answering outside the scope of the question
asked
* Trolling, insulting/derogatory comments, and personal or political attacks
* Promoting or spreading disinformation, lies, or conspiracy theories against
a person, group, organisation, project, or community
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
* Other conduct which could reasonably be considered inappropriate
The goal of the standards and moderation guidelines outlined here is to build
and maintain a respectful community. We ask that you dont just aim to be
"technically unimpeachable", but rather try to be your best self.
We value many things beyond technical expertise, including collaboration and
supporting others within our community. Providing a positive experience for
other community members can have a much more significant impact than simply
providing the correct answer.
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
Project leaders are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
Project leaders have the right and responsibility to remove, edit, or
reject messages, comments, commits, code, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
permanently any community member for other behaviors that they deem
inappropriate, threatening, offensive, or harmful.
## Moderation
Instances of behaviors that violate the Adafruit Community Code of Conduct
may be reported by any member of the community. Community members are
encouraged to report these situations, including situations they witness
involving other community members.
You may report in the following ways:
In any situation, you may send an email to <support@adafruit.com>.
On the Adafruit Discord, you may send an open message from any channel
to all Community Moderators by tagging @community moderators. You may
also send an open message from any channel, or a direct message to
@kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442,
@sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175.
Email and direct message reports will be kept confidential.
In situations on Discord where the issue is particularly egregious, possibly
illegal, requires immediate action, or violates the Discord terms of service,
you should also report the message directly to Discord.
These are the steps for upholding our communitys standards of conduct.
1. Any member of the community may report any situation that violates the
Adafruit Community Code of Conduct. All reports will be reviewed and
investigated.
2. If the behavior is an egregious violation, the community member who
committed the violation may be banned immediately, without warning.
3. Otherwise, moderators will first respond to such behavior with a warning.
4. Moderators follow a soft "three strikes" policy - the community member may
be given another chance, if they are receptive to the warning and change their
behavior.
5. If the community member is unreceptive or unreasonable when warned by a
moderator, or the warning goes unheeded, they may be banned for a first or
second offense. Repeated offenses will result in the community member being
banned.
## Scope
This Code of Conduct and the enforcement policies listed above apply to all
Adafruit Community venues. This includes but is not limited to any community
spaces (both public and private), the entire Adafruit Discord server, and
Adafruit GitHub repositories. Examples of Adafruit Community spaces include
but are not limited to meet-ups, audio chats on the Adafruit Discord, or
interaction at a conference.
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at support@adafruit.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
when an individual is representing the project or its community. As a community
member, you are representing our community, and are expected to behave
accordingly.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.4, available at
<https://www.contributor-covenant.org/version/1/4/code-of-conduct.html>,
and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html).
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
For other projects adopting the Adafruit Community Code of
Conduct, please contact the maintainers of those projects for enforcement.
If you wish to use this code of conduct for your own project, consider
explicitly mentioning your moderation policy or making a copy with your
own moderation policy so as to avoid confusion.

View file

@ -6,11 +6,11 @@ Introduction
:alt: Documentation Status
.. image :: https://img.shields.io/discord/327254708534116352.svg
:target: https://discord.gg/nBQh6qu
:target: https://adafru.it/discord
:alt: Discord
.. image:: https://travis-ci.org/adafruit/Adafruit_CircuitPython_BME280.svg?branch=master
:target: https://travis-ci.org/adafruit/Adafruit_CircuitPython_BME280
.. image:: https://github.com/adafruit/Adafruit_CircuitPython_BME280/workflows/Build%20CI/badge.svg
:target: https://github.com/adafruit/Adafruit_CircuitPython_BME280/actions/
:alt: Build Status
I2C and SPI driver for the Bosch BME280 Temperature, Humidity, and Barometric Pressure sensor
@ -32,9 +32,14 @@ on your device.
Installing from PyPI
--------------------
On the Raspberry Pi, you can install the driver locally
`from PyPI <https://pypi.org/project/adafruit-circuitpython-bme280/>`_. To
install system-wide, use:
On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from
PyPI <https://pypi.org/project/adafruit-circuitpython-bme280/>`_. To install for current user:
.. code-block:: shell
pip3 install adafruit-circuitpython-bme280
To install system-wide (this may be required in some cases):
.. code-block:: shell
@ -63,6 +68,8 @@ Usage Example
# Create library object using our Bus I2C port
i2c = busio.I2C(board.SCL, board.SDA)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
#or with other sensor address
#bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c, address=0x76)
# OR create library object using our Bus SPI port
#spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
@ -86,49 +93,7 @@ Contributions are welcome! Please read our `Code of Conduct
<https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/master/CODE_OF_CONDUCT.md>`_
before contributing to help this project stay welcoming.
Building Locally
================
Documentation
=============
To build this library locally you'll need to install the
`circuitpython-build-tools <https://github.com/adafruit/circuitpython-build-tools>`_ package.
.. code-block:: shell
python3 -m venv .env
source .env/bin/activate
pip3 install circuitpython-build-tools
Once installed, make sure you are in the virtual environment:
.. code-block:: shell
source .env/bin/activate
Then run the build:
.. code-block:: shell
circuitpython-build-bundles --filename_prefix adafruit-circuitpython-veml6070 --library_location .
Sphinx Documentation
--------------------
Sphinx is used to build the documentation based on rST files and comments in the code. First,
install dependencies (feel free to reuse the virtual environment from above):
.. code-block:: shell
python3 -m venv .env
source .env/bin/activate
pip3 install Sphinx sphinx-rtd-theme
Now, once you have the virtual environment activated:
.. code-block:: shell
cd docs
sphinx-build -E -W -b html . _build/html
This will output the documentation to ``docs/_build/html``. Open the index.html in your browser to
view them. It will also (due to -W) error out on any warning like Travis will. This is a good way to
locally verify it will pass.
For information on building library documentation, please check out `this guide <https://learn.adafruit.com/creating-and-sharing-a-circuitpython-library/sharing-our-docs-on-readthedocs#sphinx-5-1>`_.

View file

@ -20,16 +20,17 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
`adafruit_bme280` - Adafruit BME680 - Temperature, Humidity, Pressure & Gas Sensor
====================================================================================
`adafruit_bme280` - Adafruit BME280 - Temperature, Humidity & Barometic Pressure Sensor
=========================================================================================
CircuitPython driver from BME280 Temperature, Humidity and Barometic Pressure sensor
* Author(s): ladyada
"""
import math
import time
from time import sleep
from micropython import const
try:
import struct
except ImportError:
@ -67,42 +68,284 @@ _BME280_PRESSURE_MAX_HPA = const(1100)
_BME280_HUMIDITY_MIN = const(0)
_BME280_HUMIDITY_MAX = const(100)
"""iir_filter values"""
IIR_FILTER_DISABLE = const(0)
IIR_FILTER_X2 = const(0x01)
IIR_FILTER_X4 = const(0x02)
IIR_FILTER_X8 = const(0x03)
IIR_FILTER_X16 = const(0x04)
_BME280_IIR_FILTERS = (
IIR_FILTER_DISABLE,
IIR_FILTER_X2,
IIR_FILTER_X4,
IIR_FILTER_X8,
IIR_FILTER_X16,
)
"""overscan values for temperature, pressure, and humidity"""
OVERSCAN_DISABLE = const(0x00)
OVERSCAN_X1 = const(0x01)
OVERSCAN_X2 = const(0x02)
OVERSCAN_X4 = const(0x03)
OVERSCAN_X8 = const(0x04)
OVERSCAN_X16 = const(0x05)
_BME280_OVERSCANS = {
OVERSCAN_DISABLE: 0,
OVERSCAN_X1: 1,
OVERSCAN_X2: 2,
OVERSCAN_X4: 4,
OVERSCAN_X8: 8,
OVERSCAN_X16: 16,
}
"""mode values"""
MODE_SLEEP = const(0x00)
MODE_FORCE = const(0x01)
MODE_NORMAL = const(0x03)
_BME280_MODES = (MODE_SLEEP, MODE_FORCE, MODE_NORMAL)
"""
standby timeconstant values
TC_X[_Y] where X=milliseconds and Y=tenths of a millisecond
"""
STANDBY_TC_0_5 = const(0x00) # 0.5ms
STANDBY_TC_10 = const(0x06) # 10ms
STANDBY_TC_20 = const(0x07) # 20ms
STANDBY_TC_62_5 = const(0x01) # 62.5ms
STANDBY_TC_125 = const(0x02) # 125ms
STANDBY_TC_250 = const(0x03) # 250ms
STANDBY_TC_500 = const(0x04) # 500ms
STANDBY_TC_1000 = const(0x05) # 1000ms
_BME280_STANDBY_TCS = (
STANDBY_TC_0_5,
STANDBY_TC_10,
STANDBY_TC_20,
STANDBY_TC_62_5,
STANDBY_TC_125,
STANDBY_TC_250,
STANDBY_TC_500,
STANDBY_TC_1000,
)
class Adafruit_BME280:
"""Driver from BME280 Temperature, Humidity and Barometic Pressure sensor"""
# pylint: disable=too-many-instance-attributes
def __init__(self):
"""Check the BME280 was found, read the coefficients and enable the sensor for continuous
reads"""
"""Check the BME280 was found, read the coefficients and enable the sensor"""
# Check device ID.
chip_id = self._read_byte(_BME280_REGISTER_CHIPID)
if _BME280_CHIPID != chip_id:
raise RuntimeError('Failed to find BME280! Chip ID 0x%x' % chip_id)
self._write_register_byte(_BME280_REGISTER_SOFTRESET, 0xB6)
time.sleep(0.5)
raise RuntimeError("Failed to find BME280! Chip ID 0x%x" % chip_id)
# Set some reasonable defaults.
self._iir_filter = IIR_FILTER_DISABLE
self._overscan_humidity = OVERSCAN_X1
self._overscan_temperature = OVERSCAN_X1
self._overscan_pressure = OVERSCAN_X16
self._t_standby = STANDBY_TC_125
self._mode = MODE_SLEEP
self._reset()
self._read_coefficients()
self._write_ctrl_meas()
self._write_config()
self.sea_level_pressure = 1013.25
"""Pressure in hectoPascals at sea level. Used to calibrate `altitude`."""
# turn on humidity oversample 16x
self._write_register_byte(_BME280_REGISTER_CTRL_HUM, 0x03)
self._t_fine = None
def _read_temperature(self):
# perform one measurement
self._write_register_byte(_BME280_REGISTER_CTRL_MEAS, 0xFE) # high res, forced mode
if self.mode != MODE_NORMAL:
self.mode = MODE_FORCE
# Wait for conversion to complete
while self._read_byte(_BME280_REGISTER_STATUS) & 0x08:
time.sleep(0.002)
raw_temperature = self._read24(_BME280_REGISTER_TEMPDATA) / 16 # lowest 4 bits get dropped
#print("raw temp: ", UT)
var1 = (raw_temperature / 16384.0 - self._temp_calib[0] / 1024.0) * self._temp_calib[1]
#print(var1)
var2 = ((raw_temperature / 131072.0 - self._temp_calib[0] / 8192.0) * (
raw_temperature / 131072.0 - self._temp_calib[0] / 8192.0)) * self._temp_calib[2]
#print(var2)
while self._get_status() & 0x08:
sleep(0.002)
raw_temperature = (
self._read24(_BME280_REGISTER_TEMPDATA) / 16
) # lowest 4 bits get dropped
# print("raw temp: ", UT)
var1 = (
raw_temperature / 16384.0 - self._temp_calib[0] / 1024.0
) * self._temp_calib[1]
# print(var1)
var2 = (
(raw_temperature / 131072.0 - self._temp_calib[0] / 8192.0)
* (raw_temperature / 131072.0 - self._temp_calib[0] / 8192.0)
) * self._temp_calib[2]
# print(var2)
self._t_fine = int(var1 + var2)
#print("t_fine: ", self.t_fine)
# print("t_fine: ", self.t_fine)
def _reset(self):
"""Soft reset the sensor"""
self._write_register_byte(_BME280_REGISTER_SOFTRESET, 0xB6)
sleep(0.004) # Datasheet says 2ms. Using 4ms just to be safe
def _write_ctrl_meas(self):
"""
Write the values to the ctrl_meas and ctrl_hum registers in the device
ctrl_meas sets the pressure and temperature data acquistion options
ctrl_hum sets the humidty oversampling and must be written to first
"""
self._write_register_byte(_BME280_REGISTER_CTRL_HUM, self.overscan_humidity)
self._write_register_byte(_BME280_REGISTER_CTRL_MEAS, self._ctrl_meas)
def _get_status(self):
"""Get the value from the status register in the device """
return self._read_byte(_BME280_REGISTER_STATUS)
def _read_config(self):
"""Read the value from the config register in the device """
return self._read_byte(_BME280_REGISTER_CONFIG)
def _write_config(self):
"""Write the value to the config register in the device """
normal_flag = False
if self._mode == MODE_NORMAL:
# Writes to the config register may be ignored while in Normal mode
normal_flag = True
self.mode = MODE_SLEEP # So we switch to Sleep mode first
self._write_register_byte(_BME280_REGISTER_CONFIG, self._config)
if normal_flag:
self.mode = MODE_NORMAL
@property
def mode(self):
"""
Operation mode
Allowed values are the constants MODE_*
"""
return self._mode
@mode.setter
def mode(self, value):
if not value in _BME280_MODES:
raise ValueError("Mode '%s' not supported" % (value))
self._mode = value
self._write_ctrl_meas()
@property
def standby_period(self):
"""
Control the inactive period when in Normal mode
Allowed standby periods are the constants STANDBY_TC_*
"""
return self._t_standby
@standby_period.setter
def standby_period(self, value):
if not value in _BME280_STANDBY_TCS:
raise ValueError("Standby Period '%s' not supported" % (value))
if self._t_standby == value:
return
self._t_standby = value
self._write_config()
@property
def overscan_humidity(self):
"""
Humidity Oversampling
Allowed values are the constants OVERSCAN_*
"""
return self._overscan_humidity
@overscan_humidity.setter
def overscan_humidity(self, value):
if not value in _BME280_OVERSCANS:
raise ValueError("Overscan value '%s' not supported" % (value))
self._overscan_humidity = value
self._write_ctrl_meas()
@property
def overscan_temperature(self):
"""
Temperature Oversampling
Allowed values are the constants OVERSCAN_*
"""
return self._overscan_temperature
@overscan_temperature.setter
def overscan_temperature(self, value):
if not value in _BME280_OVERSCANS:
raise ValueError("Overscan value '%s' not supported" % (value))
self._overscan_temperature = value
self._write_ctrl_meas()
@property
def overscan_pressure(self):
"""
Pressure Oversampling
Allowed values are the constants OVERSCAN_*
"""
return self._overscan_pressure
@overscan_pressure.setter
def overscan_pressure(self, value):
if not value in _BME280_OVERSCANS:
raise ValueError("Overscan value '%s' not supported" % (value))
self._overscan_pressure = value
self._write_ctrl_meas()
@property
def iir_filter(self):
"""
Controls the time constant of the IIR filter
Allowed values are the constants IIR_FILTER_*
"""
return self._iir_filter
@iir_filter.setter
def iir_filter(self, value):
if not value in _BME280_IIR_FILTERS:
raise ValueError("IIR Filter '%s' not supported" % (value))
self._iir_filter = value
self._write_config()
@property
def _config(self):
"""Value to be written to the device's config register """
config = 0
if self.mode == MODE_NORMAL:
config += self._t_standby << 5
if self._iir_filter:
config += self._iir_filter << 2
return config
@property
def _ctrl_meas(self):
"""Value to be written to the device's ctrl_meas register """
ctrl_meas = self.overscan_temperature << 5
ctrl_meas += self.overscan_pressure << 2
ctrl_meas += self.mode
return ctrl_meas
@property
def measurement_time_typical(self):
"""Typical time in milliseconds required to complete a measurement in normal mode"""
meas_time_ms = 1.0
if self.overscan_temperature != OVERSCAN_DISABLE:
meas_time_ms += 2 * _BME280_OVERSCANS.get(self.overscan_temperature)
if self.overscan_pressure != OVERSCAN_DISABLE:
meas_time_ms += 2 * _BME280_OVERSCANS.get(self.overscan_pressure) + 0.5
if self.overscan_humidity != OVERSCAN_DISABLE:
meas_time_ms += 2 * _BME280_OVERSCANS.get(self.overscan_humidity) + 0.5
return meas_time_ms
@property
def measurement_time_max(self):
"""Maximum time in milliseconds required to complete a measurement in normal mode"""
meas_time_ms = 1.25
if self.overscan_temperature != OVERSCAN_DISABLE:
meas_time_ms += 2.3 * _BME280_OVERSCANS.get(self.overscan_temperature)
if self.overscan_pressure != OVERSCAN_DISABLE:
meas_time_ms += 2.3 * _BME280_OVERSCANS.get(self.overscan_pressure) + 0.575
if self.overscan_humidity != OVERSCAN_DISABLE:
meas_time_ms += 2.3 * _BME280_OVERSCANS.get(self.overscan_humidity) + 0.575
return meas_time_ms
@property
def temperature(self):
@ -112,12 +355,17 @@ class Adafruit_BME280:
@property
def pressure(self):
"""The compensated pressure in hectoPascals."""
"""
The compensated pressure in hectoPascals.
returns None if pressure measurement is disabled
"""
self._read_temperature()
# Algorithm from the BME280 driver
# https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c
adc = self._read24(_BME280_REGISTER_PRESSUREDATA) / 16 # lowest 4 bits get dropped
adc = (
self._read24(_BME280_REGISTER_PRESSUREDATA) / 16
) # lowest 4 bits get dropped
var1 = float(self._t_fine) / 2.0 - 64000.0
var2 = var1 * var1 * self._pressure_calib[5] / 32768.0
var2 = var2 + var1 * self._pressure_calib[4] * 2.0
@ -125,9 +373,11 @@ class Adafruit_BME280:
var3 = self._pressure_calib[2] * var1 * var1 / 524288.0
var1 = (var3 + self._pressure_calib[1] * var1) / 524288.0
var1 = (1.0 + var1 / 32768.0) * self._pressure_calib[0]
if var1 == 0:
return 0
if var1:
if not var1: # avoid exception caused by division by zero
raise ArithmeticError(
"Invalid result possibly related to error while \
reading the calibration registers"
)
pressure = 1048576.0 - adc
pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1
var1 = self._pressure_calib[8] * pressure * pressure / 2147483648.0
@ -140,32 +390,35 @@ class Adafruit_BME280:
if pressure > _BME280_PRESSURE_MAX_HPA:
return _BME280_PRESSURE_MAX_HPA
return pressure
else:
return _BME280_PRESSURE_MIN_HPA
@property
def humidity(self):
"""The relative humidity in RH %"""
"""
The relative humidity in RH %
returns None if humidity measurement is disabled
"""
self._read_temperature()
hum = self._read_register(_BME280_REGISTER_HUMIDDATA, 2)
#print("Humidity data: ", hum)
# print("Humidity data: ", hum)
adc = float(hum[0] << 8 | hum[1])
#print("adc:", adc)
# print("adc:", adc)
# Algorithm from the BME280 driver
# https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c
var1 = float(self._t_fine) - 76800.0
#print("var1 ", var1)
var2 = (self._humidity_calib[3] * 64.0 + (self._humidity_calib[4] / 16384.0) * var1)
#print("var2 ",var2)
# print("var1 ", var1)
var2 = (
self._humidity_calib[3] * 64.0 + (self._humidity_calib[4] / 16384.0) * var1
)
# print("var2 ",var2)
var3 = adc - var2
#print("var3 ",var3)
# print("var3 ",var3)
var4 = self._humidity_calib[1] / 65536.0
#print("var4 ",var4)
var5 = (1.0 + (self._humidity_calib[2] / 67108864.0) * var1)
#print("var5 ",var5)
# print("var4 ",var4)
var5 = 1.0 + (self._humidity_calib[2] / 67108864.0) * var1
# print("var5 ",var5)
var6 = 1.0 + (self._humidity_calib[5] / 67108864.0) * var1 * var5
#print("var6 ",var6)
# print("var6 ",var6)
var6 = var3 * var4 * (var5 * var6)
humidity = var6 * (1.0 - self._humidity_calib[0] * var6 / 524288.0)
@ -186,19 +439,19 @@ class Adafruit_BME280:
def _read_coefficients(self):
"""Read & save the calibration coefficients"""
coeff = self._read_register(_BME280_REGISTER_DIG_T1, 24)
coeff = list(struct.unpack('<HhhHhhhhhhhh', bytes(coeff)))
coeff = list(struct.unpack("<HhhHhhhhhhhh", bytes(coeff)))
coeff = [float(i) for i in coeff]
self._temp_calib = coeff[:3]
self._pressure_calib = coeff[3:]
self._humidity_calib = [0]*6
self._humidity_calib = [0] * 6
self._humidity_calib[0] = self._read_byte(_BME280_REGISTER_DIG_H1)
coeff = self._read_register(_BME280_REGISTER_DIG_H2, 7)
coeff = list(struct.unpack('<hBBBBb', bytes(coeff)))
coeff = list(struct.unpack("<hBbBbb", bytes(coeff)))
self._humidity_calib[1] = float(coeff[0])
self._humidity_calib[2] = float(coeff[1])
self._humidity_calib[3] = float((coeff[2] << 4) | (coeff[3] & 0xF))
self._humidity_calib[4] = float(((coeff[3] & 0xF0) << 4) | coeff[4])
self._humidity_calib[4] = float((coeff[4] << 4) | (coeff[3] >> 4))
self._humidity_calib[5] = float(coeff[5])
def _read_byte(self, register):
@ -219,10 +472,13 @@ class Adafruit_BME280:
def _write_register_byte(self, register, value):
raise NotImplementedError()
class Adafruit_BME280_I2C(Adafruit_BME280):
"""Driver for BME280 connected over I2C"""
def __init__(self, i2c, address=_BME280_ADDRESS):
import adafruit_bus_device.i2c_device as i2c_device
import adafruit_bus_device.i2c_device as i2c_device # pylint: disable=import-outside-toplevel
self._i2c = i2c_device.I2CDevice(i2c, address)
super().__init__()
@ -231,31 +487,34 @@ class Adafruit_BME280_I2C(Adafruit_BME280):
i2c.write(bytes([register & 0xFF]))
result = bytearray(length)
i2c.readinto(result)
#print("$%02X => %s" % (register, [hex(i) for i in result]))
# print("$%02X => %s" % (register, [hex(i) for i in result]))
return result
def _write_register_byte(self, register, value):
with self._i2c as i2c:
i2c.write(bytes([register & 0xFF, value & 0xFF]))
#print("$%02X <= 0x%02X" % (register, value))
# print("$%02X <= 0x%02X" % (register, value))
class Adafruit_BME280_SPI(Adafruit_BME280):
"""Driver for BME280 connected over SPI"""
def __init__(self, spi, cs, baudrate=100000):
import adafruit_bus_device.spi_device as spi_device
import adafruit_bus_device.spi_device as spi_device # pylint: disable=import-outside-toplevel
self._spi = spi_device.SPIDevice(spi, cs, baudrate=baudrate)
super().__init__()
def _read_register(self, register, length):
register = (register | 0x80) & 0xFF # Read single, bit 7 high.
with self._spi as spi:
spi.write(bytearray([register])) #pylint: disable=no-member
spi.write(bytearray([register])) # pylint: disable=no-member
result = bytearray(length)
spi.readinto(result) #pylint: disable=no-member
#print("$%02X => %s" % (register, [hex(i) for i in result]))
spi.readinto(result) # pylint: disable=no-member
# print("$%02X => %s" % (register, [hex(i) for i in result]))
return result
def _write_register_byte(self, register, value):
register &= 0x7F # Write, bit 7 low.
with self._spi as spi:
spi.write(bytes([register, value & 0xFF])) #pylint: disable=no-member
spi.write(bytes([register, value & 0xFF])) # pylint: disable=no-member

View file

@ -2,7 +2,8 @@
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath(".."))
# -- General configuration ------------------------------------------------
@ -10,35 +11,42 @@ sys.path.insert(0, os.path.abspath('..'))
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.viewcode",
]
# API docs fix
intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)}
intersphinx_mapping = {
"python": ("https://docs.python.org/3.4", None),
"BusDevice": (
"https://circuitpython.readthedocs.io/projects/busdevice/en/latest/",
None,
),
"CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None),
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]
source_suffix = '.rst'
source_suffix = ".rst"
# The master toctree document.
master_doc = 'index'
master_doc = "index"
# General information about the project.
project = u'Adafruit BME280 Library'
copyright = u'2017 ladyada'
author = u'ladyada'
project = "Adafruit BME280 Library"
copyright = "2017 ladyada"
author = "ladyada"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'1.0'
version = "1.0"
# The full version, including alpha/beta/rc tags.
release = u'1.0'
release = "1.0"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@ -50,7 +58,7 @@ language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"]
# The reST default role (used for this markup: `text`) to use for all
# documents.
@ -62,7 +70,7 @@ default_role = "any"
add_function_parentheses = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
@ -76,32 +84,33 @@ todo_emit_warnings = True
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
on_rtd = os.environ.get("READTHEDOCS", None) == "True"
if not on_rtd: # only import and set the theme if we're building docs locally
try:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.']
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."]
except:
html_theme = 'default'
html_theme_path = ['.']
html_theme = "default"
html_theme_path = ["."]
else:
html_theme_path = ['.']
html_theme_path = ["."]
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
html_favicon = '_static/favicon.ico'
html_favicon = "_static/favicon.ico"
# Output file base name for HTML help builder.
htmlhelp_basename = 'AdafruitBME280Librarydoc'
htmlhelp_basename = "AdafruitBME280Librarydoc"
# -- Options for LaTeX output ---------------------------------------------
@ -109,15 +118,12 @@ latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
@ -127,8 +133,13 @@ latex_elements = {
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'AdafruitBME280Library.tex', u'Adafruit BME280 Library Documentation',
author, 'manual'),
(
master_doc,
"AdafruitBME280Library.tex",
"Adafruit BME280 Library Documentation",
author,
"manual",
),
]
# -- Options for manual page output ---------------------------------------
@ -136,8 +147,13 @@ latex_documents = [
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'adafruitBME280library', u'Adafruit BME280 Library Documentation',
[author], 1)
(
master_doc,
"adafruitBME280library",
"Adafruit BME280 Library Documentation",
[author],
1,
)
]
# -- Options for Texinfo output -------------------------------------------
@ -146,10 +162,16 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'AdafruitBME280Library', u'Adafruit BME280 Library Documentation',
author, 'AdafruitBME280Library', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"AdafruitBME280Library",
"Adafruit BME280 Library Documentation",
author,
"AdafruitBME280Library",
"One line description of project.",
"Miscellaneous",
),
]
# API docs fix
autodoc_mock_imports = ['micropython']
autodoc_mock_imports = ["micropython"]

View file

@ -0,0 +1,37 @@
"""
Example showing how the BME280 library can be used to set the various
parameters supported by the sensor.
Refer to the BME280 datasheet to understand what these parameters do
"""
import time
import board
import busio
import adafruit_bme280
# Create library object using our Bus I2C port
i2c = busio.I2C(board.SCL, board.SDA)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
# OR create library object using our Bus SPI port
# spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
# bme_cs = digitalio.DigitalInOut(board.D10)
# bme280 = adafruit_bme280.Adafruit_BME280_SPI(spi, bme_cs)
# Change this to match the location's pressure (hPa) at sea level
bme280.sea_level_pressure = 1013.25
bme280.mode = adafruit_bme280.MODE_NORMAL
bme280.standby_period = adafruit_bme280.STANDBY_TC_500
bme280.iir_filter = adafruit_bme280.IIR_FILTER_X16
bme280.overscan_pressure = adafruit_bme280.OVERSCAN_X16
bme280.overscan_humidity = adafruit_bme280.OVERSCAN_X1
bme280.overscan_temperature = adafruit_bme280.OVERSCAN_X2
# The sensor will need a moment to gather initial readings
time.sleep(1)
while True:
print("\nTemperature: %0.1f C" % bme280.temperature)
print("Humidity: %0.1f %%" % bme280.humidity)
print("Pressure: %0.1f hPa" % bme280.pressure)
print("Altitude = %0.2f meters" % bme280.altitude)
time.sleep(2)

View file

@ -9,9 +9,9 @@ i2c = busio.I2C(board.SCL, board.SDA)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
# OR create library object using our Bus SPI port
#spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
#bme_cs = digitalio.DigitalInOut(board.D10)
#bme280 = adafruit_bme280.Adafruit_BME280_SPI(spi, bme_cs)
# spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
# bme_cs = digitalio.DigitalInOut(board.D10)
# bme280 = adafruit_bme280.Adafruit_BME280_SPI(spi, bme_cs)
# change this to match the location's pressure (hPa) at sea level
bme280.sea_level_pressure = 1013.25

View file

@ -7,6 +7,7 @@ https://github.com/pypa/sampleproject
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
@ -14,47 +15,38 @@ from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
with open(path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = f.read()
setup(
name='adafruit-circuitpython-bme280',
name="adafruit-circuitpython-bme280",
use_scm_version=True,
setup_requires=['setuptools_scm'],
description='CircuitPython library for the Bosch BME280 temperature/humidity/pressure sensor.',
setup_requires=["setuptools_scm"],
description="CircuitPython library for the Bosch BME280 temperature/humidity/pressure sensor.",
long_description=long_description,
long_description_content_type='text/x-rst',
long_description_content_type="text/x-rst",
# The project's main homepage.
url='https://github.com/adafruit/Adafruit_CircuitPython_BME280',
url="https://github.com/adafruit/Adafruit_CircuitPython_BME280",
# Author details
author='Adafruit Industries',
author_email='circuitpython@adafruit.com',
install_requires=['Adafruit-Blinka', 'adafruit-circuitpython-busdevice'],
author="Adafruit Industries",
author_email="circuitpython@adafruit.com",
install_requires=["Adafruit-Blinka", "adafruit-circuitpython-busdevice"],
# Choose your license
license='MIT',
license="MIT",
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries',
'Topic :: System :: Hardware',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries",
"Topic :: System :: Hardware",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
],
# What does your project relate to?
keywords='adafruit bme280 sensor hardware micropython circuitpython',
keywords="adafruit bme280 sensor hardware micropython circuitpython",
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
py_modules=['adafruit_bme280'],
py_modules=["adafruit_bme280"],
)