Compare commits

..

No commits in common. "master" and "revert-12-add-dew-point" have entirely different histories.

12 changed files with 270 additions and 714 deletions

View file

@ -1,57 +0,0 @@
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

View file

@ -1,81 +0,0 @@
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__ __pycache__
_build _build
*.pyc *.pyc
*.mpy
.env .env
build*
bundles bundles

View file

@ -18,7 +18,6 @@ ignore-patterns=
#init-hook= #init-hook=
# Use multiple processes to speed up Pylint. # Use multiple processes to speed up Pylint.
# jobs=1
jobs=2 jobs=2
# List of plugins (as comma separated values of python modules names) to load, # List of plugins (as comma separated values of python modules names) to load,
@ -51,8 +50,7 @@ confidence=
# --enable=similarities". If you want to run only the classes checker, but have # --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes # no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W" # --disable=W"
# 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
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 # 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 # either give multiple identifier separated by comma (,) or put this option
@ -119,8 +117,7 @@ spelling-store-unknown-words=no
[MISCELLANEOUS] [MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma. # List of note tags to take in consideration, separated by a comma.
# notes=FIXME,XXX,TODO notes=FIXME,XXX,TODO
notes=FIXME,XXX
[TYPECHECK] [TYPECHECK]
@ -156,7 +153,7 @@ ignored-classes=optparse.Values,thread._local,_thread._local
# (useful for modules/projects where namespaces are manipulated during runtime # (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It # and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching. # supports qualified module names, as well as Unix pattern matching.
ignored-modules=board ignored-modules=
# Show a hint with possible names when a member name was not found. The aspect # Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance. # of finding the hint is based on edit distance.
@ -203,7 +200,6 @@ redefining-builtins-modules=six.moves,future.builtins
[FORMAT] [FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. # Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
# expected-line-ending-format=
expected-line-ending-format=LF expected-line-ending-format=LF
# Regexp for a line that is allowed to be longer than the limit. # Regexp for a line that is allowed to be longer than the limit.
@ -276,11 +272,9 @@ 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}|(__.*__))$ class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
# Naming hint for class names # Naming hint for class names
# class-name-hint=[A-Z_][a-zA-Z0-9]+$
class-name-hint=[A-Z_][a-zA-Z0-9_]+$ class-name-hint=[A-Z_][a-zA-Z0-9_]+$
# Regular expression matching correct class names # Regular expression matching correct class names
# class-rgx=[A-Z_][a-zA-Z0-9]+$
class-rgx=[A-Z_][a-zA-Z0-9_]+$ class-rgx=[A-Z_][a-zA-Z0-9_]+$
# Naming hint for constant names # Naming hint for constant names
@ -300,8 +294,7 @@ 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_]*))$ 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 variable names which should always be accepted, separated by a comma
# good-names=i,j,k,ex,Run,_ good-names=r,g,b,i,j,k,n,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 a hint for the correct naming format with invalid-name
include-naming-hint=no include-naming-hint=no
@ -398,7 +391,6 @@ valid-metaclass-classmethod-first-arg=mcs
max-args=5 max-args=5
# Maximum number of attributes for a class (see R0902). # Maximum number of attributes for a class (see R0902).
# max-attributes=7
max-attributes=11 max-attributes=11
# Maximum number of boolean expressions in a if statement # Maximum number of boolean expressions in a if statement
@ -423,7 +415,7 @@ max-returns=6
max-statements=50 max-statements=50
# Minimum number of public methods for a class (see R0903). # Minimum number of public methods for a class (see R0903).
min-public-methods=1 min-public-methods=2
[EXCEPTIONS] [EXCEPTIONS]

32
.travis.yml Normal file
View file

@ -0,0 +1,32 @@
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,129 +1,74 @@
# Adafruit Community Code of Conduct # Contributor Covenant Code of Conduct
## Our Pledge ## Our Pledge
In the interest of fostering an open and welcoming environment, we as In the interest of fostering an open and welcoming environment, we as
contributors and leaders pledge to making participation in our project and contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level or type of size, disability, ethnicity, gender identity and expression, level of experience,
experience, education, socio-economic status, nationality, personal appearance, nationality, personal appearance, race, religion, or sexual identity and
race, religion, or sexual identity and orientation. orientation.
## Our Standards ## 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 Examples of behavior that contributes to creating a positive environment
include: include:
* Be kind and courteous to others
* Using welcoming and inclusive language * Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences * Being respectful of differing viewpoints and experiences
* Collaborating with other community members
* Gracefully accepting constructive criticism * Gracefully accepting constructive criticism
* Focusing on what is best for the community * Focusing on what is best for the community
* Showing empathy towards other community members * Showing empathy towards other community members
Examples of unacceptable behavior by participants include: Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and sexual attention or advances * The use of sexualized language or imagery and unwelcome sexual attention or
* The use of inappropriate images, including in a community member's avatar advances
* 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 * 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 * Public or private harassment
* Publishing others' private information, such as a physical or electronic * Publishing others' private information, such as a physical or electronic
address, without explicit permission address, without explicit permission
* Other conduct which could reasonably be considered inappropriate * Other conduct which could reasonably be considered inappropriate in a
professional setting
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 ## Our Responsibilities
Project leaders are responsible for clarifying the standards of acceptable Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior. response to any instances of unacceptable behavior.
Project leaders have the right and responsibility to remove, edit, or Project maintainers have the right and responsibility to remove, edit, or
reject messages, comments, commits, code, issues, and other contributions reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any community member for other behaviors that they deem permanently any contributor for other behaviors that they deem inappropriate,
inappropriate, threatening, offensive, or harmful. 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 ## 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 This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. As a community when an individual is representing the project or its community. Examples of
member, you are representing our community, and are expected to behave representing a project or community include using an official project e-mail
accordingly. 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.
## Attribution ## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
version 1.4, available at available at [http://contributor-covenant.org/version/1/4][version]
<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).
For other projects adopting the Adafruit Community Code of [homepage]: http://contributor-covenant.org
Conduct, please contact the maintainers of those projects for enforcement. [version]: http://contributor-covenant.org/version/1/4/
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 :alt: Documentation Status
.. image :: https://img.shields.io/discord/327254708534116352.svg .. image :: https://img.shields.io/discord/327254708534116352.svg
:target: https://adafru.it/discord :target: https://discord.gg/nBQh6qu
:alt: Discord :alt: Discord
.. image:: https://github.com/adafruit/Adafruit_CircuitPython_BME280/workflows/Build%20CI/badge.svg .. image:: https://travis-ci.org/adafruit/Adafruit_CircuitPython_BME280.svg?branch=master
:target: https://github.com/adafruit/Adafruit_CircuitPython_BME280/actions/ :target: https://travis-ci.org/adafruit/Adafruit_CircuitPython_BME280
:alt: Build Status :alt: Build Status
I2C and SPI driver for the Bosch BME280 Temperature, Humidity, and Barometric Pressure sensor I2C and SPI driver for the Bosch BME280 Temperature, Humidity, and Barometric Pressure sensor
@ -32,14 +32,9 @@ on your device.
Installing from PyPI Installing from PyPI
-------------------- --------------------
On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from On the Raspberry Pi, you can install the driver locally
PyPI <https://pypi.org/project/adafruit-circuitpython-bme280/>`_. To install for current user: `from PyPI <https://pypi.org/project/adafruit-circuitpython-bme280/>`_. To
install system-wide, use:
.. code-block:: shell
pip3 install adafruit-circuitpython-bme280
To install system-wide (this may be required in some cases):
.. code-block:: shell .. code-block:: shell
@ -68,8 +63,6 @@ Usage Example
# Create library object using our Bus I2C port # Create library object using our Bus I2C port
i2c = busio.I2C(board.SCL, board.SDA) i2c = busio.I2C(board.SCL, board.SDA)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c) 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 # OR create library object using our Bus SPI port
#spi = busio.SPI(board.SCK, board.MOSI, board.MISO) #spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
@ -93,7 +86,49 @@ Contributions are welcome! Please read our `Code of Conduct
<https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/master/CODE_OF_CONDUCT.md>`_ <https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/master/CODE_OF_CONDUCT.md>`_
before contributing to help this project stay welcoming. before contributing to help this project stay welcoming.
Documentation Building Locally
============= ================
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>`_. 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.

View file

@ -20,17 +20,16 @@
# 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.
""" """
`adafruit_bme280` - Adafruit BME280 - Temperature, Humidity & Barometic Pressure Sensor `adafruit_bme280` - Adafruit BME680 - Temperature, Humidity, Pressure & Gas Sensor
========================================================================================= ====================================================================================
CircuitPython driver from BME280 Temperature, Humidity and Barometic Pressure sensor CircuitPython driver from BME280 Temperature, Humidity and Barometic Pressure sensor
* Author(s): ladyada * Author(s): ladyada
""" """
import math import math
from time import sleep import time
from micropython import const from micropython import const
try: try:
import struct import struct
except ImportError: except ImportError:
@ -68,284 +67,42 @@ _BME280_PRESSURE_MAX_HPA = const(1100)
_BME280_HUMIDITY_MIN = const(0) _BME280_HUMIDITY_MIN = const(0)
_BME280_HUMIDITY_MAX = const(100) _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: class Adafruit_BME280:
"""Driver from BME280 Temperature, Humidity and Barometic Pressure sensor""" """Driver from BME280 Temperature, Humidity and Barometic Pressure sensor"""
# pylint: disable=too-many-instance-attributes
def __init__(self): def __init__(self):
"""Check the BME280 was found, read the coefficients and enable the sensor""" """Check the BME280 was found, read the coefficients and enable the sensor for continuous
reads"""
# Check device ID. # Check device ID.
chip_id = self._read_byte(_BME280_REGISTER_CHIPID) chip_id = self._read_byte(_BME280_REGISTER_CHIPID)
if _BME280_CHIPID != chip_id: if _BME280_CHIPID != chip_id:
raise RuntimeError("Failed to find BME280! Chip ID 0x%x" % chip_id) raise RuntimeError('Failed to find BME280! Chip ID 0x%x' % chip_id)
# Set some reasonable defaults. self._write_register_byte(_BME280_REGISTER_SOFTRESET, 0xB6)
self._iir_filter = IIR_FILTER_DISABLE time.sleep(0.5)
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._read_coefficients()
self._write_ctrl_meas()
self._write_config()
self.sea_level_pressure = 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`."""
# turn on humidity oversample 16x
self._write_register_byte(_BME280_REGISTER_CTRL_HUM, 0x03)
self._t_fine = None self._t_fine = None
def _read_temperature(self): def _read_temperature(self):
# perform one measurement # perform one measurement
if self.mode != MODE_NORMAL: self._write_register_byte(_BME280_REGISTER_CTRL_MEAS, 0xFE) # high res, forced mode
self.mode = MODE_FORCE
# Wait for conversion to complete # Wait for conversion to complete
while self._get_status() & 0x08: while self._read_byte(_BME280_REGISTER_STATUS) & 0x08:
sleep(0.002) time.sleep(0.002)
raw_temperature = ( raw_temperature = self._read24(_BME280_REGISTER_TEMPDATA) / 16 # lowest 4 bits get dropped
self._read24(_BME280_REGISTER_TEMPDATA) / 16 #print("raw temp: ", UT)
) # lowest 4 bits get dropped
# print("raw temp: ", UT) var1 = (raw_temperature / 16384.0 - self._temp_calib[0] / 1024.0) * self._temp_calib[1]
var1 = ( #print(var1)
raw_temperature / 16384.0 - self._temp_calib[0] / 1024.0 var2 = ((raw_temperature / 131072.0 - self._temp_calib[0] / 8192.0) * (
) * self._temp_calib[1] raw_temperature / 131072.0 - self._temp_calib[0] / 8192.0)) * self._temp_calib[2]
# print(var1) #print(var2)
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) 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 @property
def temperature(self): def temperature(self):
@ -355,17 +112,12 @@ class Adafruit_BME280:
@property @property
def pressure(self): def pressure(self):
""" """The compensated pressure in hectoPascals."""
The compensated pressure in hectoPascals.
returns None if pressure measurement is disabled
"""
self._read_temperature() self._read_temperature()
# Algorithm from the BME280 driver # Algorithm from the BME280 driver
# https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c # https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c
adc = ( adc = self._read24(_BME280_REGISTER_PRESSUREDATA) / 16 # lowest 4 bits get dropped
self._read24(_BME280_REGISTER_PRESSUREDATA) / 16
) # lowest 4 bits get dropped
var1 = float(self._t_fine) / 2.0 - 64000.0 var1 = float(self._t_fine) / 2.0 - 64000.0
var2 = var1 * var1 * self._pressure_calib[5] / 32768.0 var2 = var1 * var1 * self._pressure_calib[5] / 32768.0
var2 = var2 + var1 * self._pressure_calib[4] * 2.0 var2 = var2 + var1 * self._pressure_calib[4] * 2.0
@ -373,52 +125,47 @@ class Adafruit_BME280:
var3 = self._pressure_calib[2] * var1 * var1 / 524288.0 var3 = self._pressure_calib[2] * var1 * var1 / 524288.0
var1 = (var3 + self._pressure_calib[1] * var1) / 524288.0 var1 = (var3 + self._pressure_calib[1] * var1) / 524288.0
var1 = (1.0 + var1 / 32768.0) * self._pressure_calib[0] var1 = (1.0 + var1 / 32768.0) * self._pressure_calib[0]
if not var1: # avoid exception caused by division by zero if var1 == 0:
raise ArithmeticError( return 0
"Invalid result possibly related to error while \ if var1:
reading the calibration registers" pressure = 1048576.0 - adc
) pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1
pressure = 1048576.0 - adc var1 = self._pressure_calib[8] * pressure * pressure / 2147483648.0
pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1 var2 = pressure * self._pressure_calib[7] / 32768.0
var1 = self._pressure_calib[8] * pressure * pressure / 2147483648.0 pressure = pressure + (var1 + var2 + self._pressure_calib[6]) / 16.0
var2 = pressure * self._pressure_calib[7] / 32768.0
pressure = pressure + (var1 + var2 + self._pressure_calib[6]) / 16.0
pressure /= 100 pressure /= 100
if pressure < _BME280_PRESSURE_MIN_HPA: if pressure < _BME280_PRESSURE_MIN_HPA:
return _BME280_PRESSURE_MIN_HPA
if pressure > _BME280_PRESSURE_MAX_HPA:
return _BME280_PRESSURE_MAX_HPA
return pressure
else:
return _BME280_PRESSURE_MIN_HPA return _BME280_PRESSURE_MIN_HPA
if pressure > _BME280_PRESSURE_MAX_HPA:
return _BME280_PRESSURE_MAX_HPA
return pressure
@property @property
def humidity(self): def humidity(self):
""" """The relative humidity in RH %"""
The relative humidity in RH %
returns None if humidity measurement is disabled
"""
self._read_temperature() self._read_temperature()
hum = self._read_register(_BME280_REGISTER_HUMIDDATA, 2) hum = self._read_register(_BME280_REGISTER_HUMIDDATA, 2)
# print("Humidity data: ", hum) #print("Humidity data: ", hum)
adc = float(hum[0] << 8 | hum[1]) adc = float(hum[0] << 8 | hum[1])
# print("adc:", adc) #print("adc:", adc)
# Algorithm from the BME280 driver # Algorithm from the BME280 driver
# https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c # https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c
var1 = float(self._t_fine) - 76800.0 var1 = float(self._t_fine) - 76800.0
# print("var1 ", var1) #print("var1 ", var1)
var2 = ( var2 = (self._humidity_calib[3] * 64.0 + (self._humidity_calib[4] / 16384.0) * var1)
self._humidity_calib[3] * 64.0 + (self._humidity_calib[4] / 16384.0) * var1 #print("var2 ",var2)
)
# print("var2 ",var2)
var3 = adc - var2 var3 = adc - var2
# print("var3 ",var3) #print("var3 ",var3)
var4 = self._humidity_calib[1] / 65536.0 var4 = self._humidity_calib[1] / 65536.0
# print("var4 ",var4) #print("var4 ",var4)
var5 = 1.0 + (self._humidity_calib[2] / 67108864.0) * var1 var5 = (1.0 + (self._humidity_calib[2] / 67108864.0) * var1)
# print("var5 ",var5) #print("var5 ",var5)
var6 = 1.0 + (self._humidity_calib[5] / 67108864.0) * var1 * var5 var6 = 1.0 + (self._humidity_calib[5] / 67108864.0) * var1 * var5
# print("var6 ",var6) #print("var6 ",var6)
var6 = var3 * var4 * (var5 * var6) var6 = var3 * var4 * (var5 * var6)
humidity = var6 * (1.0 - self._humidity_calib[0] * var6 / 524288.0) humidity = var6 * (1.0 - self._humidity_calib[0] * var6 / 524288.0)
@ -433,25 +180,25 @@ reading the calibration registers"
def altitude(self): def altitude(self):
"""The altitude based on current ``pressure`` versus the sea level pressure """The altitude based on current ``pressure`` versus the sea level pressure
(``sea_level_pressure``) - which you must enter ahead of time)""" (``sea_level_pressure``) - which you must enter ahead of time)"""
pressure = self.pressure # in Si units for hPascal pressure = self.pressure # in Si units for hPascal
return 44330 * (1.0 - math.pow(pressure / self.sea_level_pressure, 0.1903)) return 44330 * (1.0 - math.pow(pressure / self.sea_level_pressure, 0.1903))
def _read_coefficients(self): def _read_coefficients(self):
"""Read & save the calibration coefficients""" """Read & save the calibration coefficients"""
coeff = self._read_register(_BME280_REGISTER_DIG_T1, 24) 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] coeff = [float(i) for i in coeff]
self._temp_calib = coeff[:3] self._temp_calib = coeff[:3]
self._pressure_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) self._humidity_calib[0] = self._read_byte(_BME280_REGISTER_DIG_H1)
coeff = self._read_register(_BME280_REGISTER_DIG_H2, 7) 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[1] = float(coeff[0])
self._humidity_calib[2] = float(coeff[1]) self._humidity_calib[2] = float(coeff[1])
self._humidity_calib[3] = float((coeff[2] << 4) | (coeff[3] & 0xF)) self._humidity_calib[3] = float((coeff[2] << 4) | (coeff[3] & 0xF))
self._humidity_calib[4] = float((coeff[4] << 4) | (coeff[3] >> 4)) self._humidity_calib[4] = float(((coeff[3] & 0xF0) << 4) | coeff[4])
self._humidity_calib[5] = float(coeff[5]) self._humidity_calib[5] = float(coeff[5])
def _read_byte(self, register): def _read_byte(self, register):
@ -472,13 +219,10 @@ reading the calibration registers"
def _write_register_byte(self, register, value): def _write_register_byte(self, register, value):
raise NotImplementedError() raise NotImplementedError()
class Adafruit_BME280_I2C(Adafruit_BME280): class Adafruit_BME280_I2C(Adafruit_BME280):
"""Driver for BME280 connected over I2C""" """Driver for BME280 connected over I2C"""
def __init__(self, i2c, address=_BME280_ADDRESS): def __init__(self, i2c, address=_BME280_ADDRESS):
import adafruit_bus_device.i2c_device as i2c_device # pylint: disable=import-outside-toplevel import adafruit_bus_device.i2c_device as i2c_device
self._i2c = i2c_device.I2CDevice(i2c, address) self._i2c = i2c_device.I2CDevice(i2c, address)
super().__init__() super().__init__()
@ -487,34 +231,31 @@ class Adafruit_BME280_I2C(Adafruit_BME280):
i2c.write(bytes([register & 0xFF])) i2c.write(bytes([register & 0xFF]))
result = bytearray(length) result = bytearray(length)
i2c.readinto(result) 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 return result
def _write_register_byte(self, register, value): def _write_register_byte(self, register, value):
with self._i2c as i2c: with self._i2c as i2c:
i2c.write(bytes([register & 0xFF, value & 0xFF])) 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): class Adafruit_BME280_SPI(Adafruit_BME280):
"""Driver for BME280 connected over SPI""" """Driver for BME280 connected over SPI"""
def __init__(self, spi, cs, baudrate=100000): def __init__(self, spi, cs, baudrate=100000):
import adafruit_bus_device.spi_device as spi_device # pylint: disable=import-outside-toplevel import adafruit_bus_device.spi_device as spi_device
self._spi = spi_device.SPIDevice(spi, cs, baudrate=baudrate) self._spi = spi_device.SPIDevice(spi, cs, baudrate=baudrate)
super().__init__() super().__init__()
def _read_register(self, register, length): def _read_register(self, register, length):
register = (register | 0x80) & 0xFF # Read single, bit 7 high. register = (register | 0x80) & 0xFF # Read single, bit 7 high.
with self._spi as spi: with self._spi as spi:
spi.write(bytearray([register])) # pylint: disable=no-member spi.write(bytearray([register])) #pylint: disable=no-member
result = bytearray(length) result = bytearray(length)
spi.readinto(result) # pylint: disable=no-member spi.readinto(result) #pylint: disable=no-member
# print("$%02X => %s" % (register, [hex(i) for i in result])) #print("$%02X => %s" % (register, [hex(i) for i in result]))
return result return result
def _write_register_byte(self, register, value): def _write_register_byte(self, register, value):
register &= 0x7F # Write, bit 7 low. register &= 0x7F # Write, bit 7 low.
with self._spi as spi: 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,8 +2,7 @@
import os import os
import sys import sys
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath(".."))
# -- General configuration ------------------------------------------------ # -- General configuration ------------------------------------------------
@ -11,42 +10,35 @@ sys.path.insert(0, os.path.abspath(".."))
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones. # ones.
extensions = [ extensions = [
"sphinx.ext.autodoc", 'sphinx.ext.autodoc',
"sphinx.ext.intersphinx", 'sphinx.ext.intersphinx',
"sphinx.ext.viewcode", 'sphinx.ext.viewcode',
] ]
# API docs fix # API docs fix
intersphinx_mapping = { 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)}
"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. # 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. # The master toctree document.
master_doc = "index" master_doc = 'index'
# General information about the project. # General information about the project.
project = "Adafruit BME280 Library" project = u'Adafruit BME280 Library'
copyright = "2017 ladyada" copyright = u'2017 ladyada'
author = "ladyada" author = u'ladyada'
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the # |version| and |release|, also used in various other places throughout the
# built documents. # built documents.
# #
# The short X.Y version. # The short X.Y version.
version = "1.0" version = u'1.0'
# The full version, including alpha/beta/rc tags. # The full version, including alpha/beta/rc tags.
release = "1.0" release = u'1.0'
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages. # for a list of supported languages.
@ -58,7 +50,7 @@ language = None
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path # 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 # The reST default role (used for this markup: `text`) to use for all
# documents. # documents.
@ -70,7 +62,7 @@ default_role = "any"
add_function_parentheses = True add_function_parentheses = True
# The name of the Pygments (syntax highlighting) style to use. # 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. # If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False todo_include_todos = False
@ -84,62 +76,59 @@ todo_emit_warnings = True
# The theme to use for HTML and HTML Help pages. See the documentation for # The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes. # 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 if not on_rtd: # only import and set the theme if we're building docs locally
try: try:
import sphinx_rtd_theme import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.']
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."]
except: except:
html_theme = "default" html_theme = 'default'
html_theme_path = ["."] html_theme_path = ['.']
else: else:
html_theme_path = ["."] html_theme_path = ['.']
# Add any paths that contain custom static files (such as style sheets) here, # 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, # relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css". # 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 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 # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large. # pixels large.
# #
html_favicon = "_static/favicon.ico" html_favicon = '_static/favicon.ico'
# Output file base name for HTML help builder. # Output file base name for HTML help builder.
htmlhelp_basename = "AdafruitBME280Librarydoc" htmlhelp_basename = 'AdafruitBME280Librarydoc'
# -- Options for LaTeX output --------------------------------------------- # -- Options for LaTeX output ---------------------------------------------
latex_elements = { latex_elements = {
# The paper size ('letterpaper' or 'a4paper'). # The paper size ('letterpaper' or 'a4paper').
# #
# 'papersize': 'letterpaper', # 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# # The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt', #
# Additional stuff for the LaTeX preamble. # 'pointsize': '10pt',
#
# 'preamble': '', # Additional stuff for the LaTeX preamble.
# Latex figure (float) alignment #
# # 'preamble': '',
# 'figure_align': 'htbp',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
} }
# Grouping the document tree into LaTeX files. List of tuples # Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, # (source start file, target name, title,
# author, documentclass [howto, manual, or own class]). # author, documentclass [howto, manual, or own class]).
latex_documents = [ latex_documents = [
( (master_doc, 'AdafruitBME280Library.tex', u'Adafruit BME280 Library Documentation',
master_doc, author, 'manual'),
"AdafruitBME280Library.tex",
"Adafruit BME280 Library Documentation",
author,
"manual",
),
] ]
# -- Options for manual page output --------------------------------------- # -- Options for manual page output ---------------------------------------
@ -147,13 +136,8 @@ latex_documents = [
# One entry per manual page. List of tuples # One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section). # (source start file, name, description, authors, manual section).
man_pages = [ man_pages = [
( (master_doc, 'adafruitBME280library', u'Adafruit BME280 Library Documentation',
master_doc, [author], 1)
"adafruitBME280library",
"Adafruit BME280 Library Documentation",
[author],
1,
)
] ]
# -- Options for Texinfo output ------------------------------------------- # -- Options for Texinfo output -------------------------------------------
@ -162,16 +146,10 @@ man_pages = [
# (source start file, target name, title, author, # (source start file, target name, title, author,
# dir menu entry, description, category) # dir menu entry, description, category)
texinfo_documents = [ texinfo_documents = [
( (master_doc, 'AdafruitBME280Library', u'Adafruit BME280 Library Documentation',
master_doc, author, 'AdafruitBME280Library', 'One line description of project.',
"AdafruitBME280Library", 'Miscellaneous'),
"Adafruit BME280 Library Documentation",
author,
"AdafruitBME280Library",
"One line description of project.",
"Miscellaneous",
),
] ]
# API docs fix # API docs fix
autodoc_mock_imports = ["micropython"] autodoc_mock_imports = ['micropython']

View file

@ -1,37 +0,0 @@
"""
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) bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
# OR create library object using our Bus SPI port # OR create library object using our Bus SPI port
# spi = busio.SPI(board.SCK, board.MOSI, board.MISO) #spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
# bme_cs = digitalio.DigitalInOut(board.D10) #bme_cs = digitalio.DigitalInOut(board.D10)
# bme280 = adafruit_bme280.Adafruit_BME280_SPI(spi, bme_cs) #bme280 = adafruit_bme280.Adafruit_BME280_SPI(spi, bme_cs)
# 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.sea_level_pressure = 1013.25 bme280.sea_level_pressure = 1013.25

View file

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