From e129bdb18bc058e07f1e6b2bb13e91a41fcf79cc Mon Sep 17 00:00:00 2001 From: Tony DiCola Date: Fri, 20 Oct 2017 14:04:07 -0700 Subject: [PATCH 01/62] Add travis config for mpy generation. --- .travis.yml | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..d56d250 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,56 @@ +# Travis CI configuration for automated .mpy file generation. +# Author: Tony DiCola +# License: Public Domain +# This configuration will work with Travis CI (travis-ci.org) to automacially +# build .mpy files for MicroPython when a new tagged release is created. This +# file is relatively generic and can be shared across multiple repositories by +# following these steps: +# 1. Copy this file into a .travis.yml file in the root of the repository. +# 2. Change the deploy > file section below to list each of the .mpy files +# that should be generated. The config will automatically look for +# .py files with the same name as the source for generating the .mpy files. +# Note that the .mpy extension should be lower case! +# 3. Commit the .travis.yml file and push it to GitHub. +# 4. Go to travis-ci.org and find the repository (it needs to be setup to access +# your github account, and your github account needs access to write to the +# repo). Flip the 'ON' switch on for Travis and the repo, see the Travis +# docs for more details: https://docs.travis-ci.com/user/getting-started/ +# 5. Get a GitHub 'personal access token' which has at least 'public_repo' or +# 'repo' scope: https://help.github.com/articles/creating-an-access-token-for-command-line-use/ +# Keep this token safe and secure! Anyone with the token will be able to +# access and write to your GitHub repositories. Travis will use the token +# to attach the .mpy files to the release. +# 6. In the Travis CI settings for the repository that was enabled find the +# environment variable editing page: https://docs.travis-ci.com/user/environment-variables/#Defining-Variables-in-Repository-Settings +# Add an environment variable named GITHUB_TOKEN and set it to the value +# of the GitHub personal access token above. Keep 'Display value in build +# log' flipped off. +# 7. That's it! Tag a release and Travis should go to work to add .mpy files +# to the release. It takes about a 2-3 minutes for a worker to spin up, +# build mpy-cross, and add the binaries to the release. +language: generic + +sudo: true + +deploy: + provider: releases + api_key: $GITHUB_TOKEN + file: + - "adafruit_dht.mpy" + skip_cleanup: true + on: + tags: true + +before_install: +- sudo apt-get -yqq update +- sudo apt-get install -y build-essential git python python-pip +- git clone https://github.com/adafruit/micropython.git +- cd micropython +- git checkout stable +- cd .. +- make -C micropython/mpy-cross +- export PATH=$PATH:$PWD/micropython/mpy-cross/ +- sudo pip install shyaml + +before_deploy: +- shyaml get-values deploy.file < .travis.yml | sed 's/.mpy/.py/' | xargs -L1 mpy-cross From 0feedd0d09858cf366324400107b35e738ab34d8 Mon Sep 17 00:00:00 2001 From: mrmcwethy Date: Sat, 9 Dec 2017 05:32:19 -0700 Subject: [PATCH 02/62] Added pylint to project with update to code --- .gitignore | 4 + .pylintrc | 432 ++++++++++++++++++++++++++++++++++++ .travis.yml | 30 +++ adafruit_dht.py | 7 +- examples/dhttoleddisplay.py | 11 +- 5 files changed, 474 insertions(+), 10 deletions(-) create mode 100644 .gitignore create mode 100644 .pylintrc create mode 100644 .travis.yml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5b5b0c8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.env +build* +bundles + diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..e274ba9 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,432 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code +extension-pkg-whitelist= + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the blacklist. The +# regex matches against base names, not paths. +ignore-patterns= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. +# jobs=1 +jobs=2 + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Specify a configuration file. +#rcfile= + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once).You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use"--disable=all --enable=classes +# --disable=W" +# disable=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 + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable= + + +[REPORTS] + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio).You can also give a reporter class, eg +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + + +[LOGGING] + +# Logging modules to check that the string format arguments are in logging +# function parameter format +logging-modules=logging + + +[SPELLING] + +# Spelling dictionary name. Available dictionaries: none. To make it working +# install python-enchant package. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME,XXX,TODO + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis. It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid to define new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_,_cb + +# A regular expression matching the name of dummy variables (i.e. expectedly +# not used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,future.builtins + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +# expected-line-ending-format= +expected-line-ending-format=LF + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module +max-module-lines=1000 + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma,dict-separator + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[BASIC] + +# Naming hint for argument names +argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Regular expression matching correct argument names +argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Naming hint for attribute names +attr-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Regular expression matching correct attribute names +attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Bad variable names which should always be refused, separated by a comma +bad-names=foo,bar,baz,toto,tutu,tata + +# Naming hint for class attribute names +class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ + +# Regular expression matching correct class attribute names +class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ + +# Naming hint for class names +# class-name-hint=[A-Z_][a-zA-Z0-9]+$ +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 +const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ + +# Regular expression matching correct constant names +const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming hint for function names +function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Regular expression matching correct function names +function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Good variable names which should always be accepted, separated by a comma +# good-names=i,j,k,ex,Run,_ +good-names=r,g,b,i,j,k,n,ex,Run,_ + +# Include a hint for the correct naming format with invalid-name +include-naming-hint=no + +# Naming hint for inline iteration names +inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ + +# Regular expression matching correct inline iteration names +inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ + +# Naming hint for method names +method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Regular expression matching correct method names +method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Naming hint for module names +module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ + +# Regular expression matching correct module names +module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +property-classes=abc.abstractproperty + +# Naming hint for variable names +variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Regular expression matching correct variable names +variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + + +[IMPORTS] + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma +deprecated-modules=optparse,tkinter.tix + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled) +ext-import-graph= + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled) +import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled) +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__,__new__,setUp + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + + +[DESIGN] + +# Maximum number of arguments for function / method +max-args=5 + +# Maximum number of attributes for a class (see R0902). +# max-attributes=7 +max-attributes=11 + +# Maximum number of boolean expressions in a if statement +max-bool-expr=5 + +# Maximum number of branch for function / method body +max-branches=12 + +# Maximum number of locals for function / method body +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body +max-returns=6 + +# Maximum number of statements in function / method body +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "Exception" +overgeneral-exceptions=Exception diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..87ea816 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,30 @@ +# This is a common .travis.yml for generating library release zip files for +# CircuitPython library releases using circuitpython-build-tools. +# See https://github.com/adafruit/circuitpython-build-tools for detailed setup +# instructions. + +dist: trusty +sudo: false +language: python +python: + - "3.6" + +cache: + pip: true + +deploy: + provider: releases + api_key: $GITHUB_TOKEN + file_glob: true + file: bundles/* + skip_cleanup: true + on: + tags: true + +install: + - pip install pylint circuitpython-travis-build-tools + +script: + - pylint adafruit_circuitpython_dht.py + - ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name examples/*.py) + - circuitpython-build-bundles --filename_prefix adafruit-circuitpython-dht --library_location . diff --git a/adafruit_dht.py b/adafruit_dht.py index bc9b1f0..78af41d 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -34,7 +34,7 @@ import pulseio except ImportError as excpt: print("adafruit_dht requires the pulseio library, but it failed to load."+ - " Note that CircuitPython does not support pulseio on all boards.") + " Note that CircuitPython does not support pulseio on all boards.") raise excpt class DHTBase: @@ -120,7 +120,7 @@ def _get_pulses(self): break pulse_in.pause() - while len(pulse_in): + while pulse_in: pulses.append(pulse_in.popleft()) pulse_in.resume() @@ -167,7 +167,8 @@ def measure(self): if chk_sum & 0xff != buf[4]: # check sum failed to validate raise RuntimeError("Checksum did not validate. Try again.") - #print("checksum did not match. Temp: {} Humidity: {} Checksum:{}".format(self._temperature,self._humidity,bites[4])) + #print("checksum did not match. Temp: {} Humidity: {} Checksum:{}" + #.format(self._temperature,self._humidity,bites[4])) # checksum matches #print("Temp: {} C Humidity: {}% ".format(self._temperature, self._humidity)) diff --git a/examples/dhttoleddisplay.py b/examples/dhttoleddisplay.py index 9b8ff88..b3b7335 100644 --- a/examples/dhttoleddisplay.py +++ b/examples/dhttoleddisplay.py @@ -3,17 +3,15 @@ and displaying results to the serial port and a 8 digit 7-segment display the DHT device data wire is connected to board.D2 """ -# import for dht devices +# import for dht devices and 7-segment display devices import time import adafruit_dht -from board import D2 - -#imports for 7-segment display device from adafruit_max7219 import bcddigits -from board import TX, RX, A2 import busio import digitalio +from board import D2, TX, RX, A2 + clk = RX din = TX cs = digitalio.DigitalInOut(A2) @@ -33,11 +31,10 @@ # now show the values on the 8 digit 7-segment display display.clear_all() - display.show_str(0,'{:5.1f}{:5.1f}'.format(temperature, humidity)) + display.show_str(0, '{:5.1f}{:5.1f}'.format(temperature, humidity)) display.show() except RuntimeError as error: print(error.args) time.sleep(2.0) - \ No newline at end of file From a9bdb62a60b505594f547e86810ddb4608a690d5 Mon Sep 17 00:00:00 2001 From: mrmcwethy Date: Sat, 9 Dec 2017 06:08:46 -0700 Subject: [PATCH 03/62] Adding repo info to .py file --- adafruit_dht.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/adafruit_dht.py b/adafruit_dht.py index 78af41d..f455fe6 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -37,6 +37,9 @@ " Note that CircuitPython does not support pulseio on all boards.") raise excpt +__version__ = "0.0.0-auto.0" +__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_DHT.git" + class DHTBase: """ base support for DHT11 and DHT22 devices """ From bb311b7d41cb6a30c2e522229a6436b7b26243ca Mon Sep 17 00:00:00 2001 From: mrmcwethy Date: Sat, 9 Dec 2017 06:21:22 -0700 Subject: [PATCH 04/62] Fixed .yml file --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 87ea816..ee554db 100644 --- a/.travis.yml +++ b/.travis.yml @@ -25,6 +25,6 @@ install: - pip install pylint circuitpython-travis-build-tools script: - - pylint adafruit_circuitpython_dht.py + - pylint adafruit_dht.py - ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name examples/*.py) - circuitpython-build-bundles --filename_prefix adafruit-circuitpython-dht --library_location . From 88dc03012b74fcbcb43ad5613c92ebe17648da75 Mon Sep 17 00:00:00 2001 From: mrmcwethy Date: Sat, 9 Dec 2017 13:36:54 -0700 Subject: [PATCH 05/62] Fixed typo --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ee554db..65862d3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,7 +22,7 @@ deploy: tags: true install: - - pip install pylint circuitpython-travis-build-tools + - pip install pylint circuitpython-build-tools script: - pylint adafruit_dht.py From fd756be7e07dd4db47977aa32f697c64377ab7da Mon Sep 17 00:00:00 2001 From: sommersoft Date: Sat, 24 Feb 2018 19:52:04 -0600 Subject: [PATCH 06/62] added simpletest example --- examples/dht_simpletest.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 examples/dht_simpletest.py diff --git a/examples/dht_simpletest.py b/examples/dht_simpletest.py new file mode 100644 index 0000000..1947174 --- /dev/null +++ b/examples/dht_simpletest.py @@ -0,0 +1,18 @@ +import time +import adafruit_dht +from board import D2 + +#initial the dht device +dhtDevice = adafruit_dht.DHT22(D2) + +while True: + try: + # show the values to the serial port + temperature = dhtDevice.temperature*9/5+32 + humidity = dhtDevice.humidity + print("Temp: {:.1f} F Humidity: {}% ".format(temperature, humidity)) + + except RuntimeError as error: + print(error.args) + + time.sleep(2.0) From d8e0222d6a5e26ba809017587c36a39381daf2bc Mon Sep 17 00:00:00 2001 From: sommersoft Date: Sat, 24 Feb 2018 19:54:09 -0600 Subject: [PATCH 07/62] renamed led display example --- examples/{dhttoleddisplay.py => dht_to_led_display.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename examples/{dhttoleddisplay.py => dht_to_led_display.py} (100%) diff --git a/examples/dhttoleddisplay.py b/examples/dht_to_led_display.py similarity index 100% rename from examples/dhttoleddisplay.py rename to examples/dht_to_led_display.py From 70479e9850458e2c90fea79b619f45cb62350799 Mon Sep 17 00:00:00 2001 From: sommersoft Date: Sat, 24 Feb 2018 20:00:22 -0600 Subject: [PATCH 08/62] setup docs folder --- api.rst | 6 ----- docs/_static/favicon.ico | Bin 0 -> 4414 bytes docs/api.rst | 5 ++++ conf.py => docs/conf.py | 15 +++++++++--- docs/examples.rst | 8 +++++++ docs/index.rst | 49 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 74 insertions(+), 9 deletions(-) delete mode 100644 api.rst create mode 100644 docs/_static/favicon.ico create mode 100644 docs/api.rst rename conf.py => docs/conf.py (90%) create mode 100644 docs/examples.rst create mode 100644 docs/index.rst diff --git a/api.rst b/api.rst deleted file mode 100644 index e69910e..0000000 --- a/api.rst +++ /dev/null @@ -1,6 +0,0 @@ - -DHT Libary Documentation -============================ - -.. automodule:: adafruit_dht - :members: diff --git a/docs/_static/favicon.ico b/docs/_static/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..5aca98376a1f7e593ebd9cf41a808512c2135635 GIT binary patch literal 4414 zcmd^BX;4#F6n=SG-XmlONeGrD5E6J{RVh+e928U#MG!$jWvO+UsvWh`x&VqGNx*en zx=qox7Dqv{kPwo%fZC$dDwVpRtz{HzTkSs8QhG0)%Y=-3@Kt!4ag|JcIo?$-F|?bXVS9UDUyev>MVZQ(H8K4#;BQW-t2CPorj8^KJrMX}QK zp+e<;4ldpXz~=)2GxNy811&)gt-}Q*yVQpsxr@VMoA##{)$1~=bZ1MmjeFw?uT(`8 z^g=09<=zW%r%buwN%iHtuKSg|+r7HkT0PYN*_u9k1;^Ss-Z!RBfJ?Un4w(awqp2b3 z%+myoFis_lTlCrGx2z$0BQdh+7?!JK#9K9@Z!VrG zNj6gK5r(b4?YDOLw|DPRoN7bdP{(>GEG41YcN~4r_SUHU2hgVtUwZG@s%edC;k7Sn zC)RvEnlq~raE2mY2ko64^m1KQL}3riixh?#J{o)IT+K-RdHae2eRX91-+g!y`8^># z-zI0ir>P%Xon)!@xp-BK2bDYUB9k613NRrY6%lVjbFcQc*pRqiK~8xtkNPLxt}e?&QsTB}^!39t_%Qb)~Ukn0O%iC;zt z<&A-y;3h++)>c1br`5VFM~5(83!HKx$L+my8sW_c#@x*|*vB1yU)_dt3vH;2hqPWx zAl^6@?ipx&U7pf`a*>Yq6C85nb+B=Fnn+(id$W#WB^uHAcZVG`qg;rWB}ubvi(Y>D z$ei>REw$#xp0SHAd^|1hq&9HJ=jKK8^zTH~nk)G?yUcmTh9vUM6Y0LMw4(gYVY$D$ zGl&WY&H<)BbJ&3sYbKjx1j^=3-0Q#f^}(aP1?8^`&FUWMp|rmtpK)bLQ1Zo?^s4jqK=Lfg*9&geMGVQ z#^-*!V`fG@;H&{M9S8%+;|h&Qrxym0Ar>WT4BCVLR8cGXF=JmEYN(sNT(9vl+S|%g z8r7nXQ(95i^`=+XHo|){$vf2$?=`F$^&wFlYXyXg$B{a>$-Fp+V}+D;9k=~Xl~?C4 zAB-;RKXdUzBJE{V&d&%R>aEfFe;vxqI$0@hwVM}gFeQR@j}a>DDxR+n+-*6|_)k%% z*mSpDV|=5I9!&VC&9tD%fcVygWZV!iIo2qFtm#!*(s|@ZT33*Ad;+<|3^+yrp*;oH zBSYLV(H1zTU?2WjrCQoQW)Z>J2a=dTriuvezBmu16`tM2fm7Q@d4^iqII-xFpwHGI zn9CL}QE*1vdj2PX{PIuqOe5dracsciH6OlAZATvE8rj6ykqdIjal2 z0S0S~PwHb-5?OQ-tU-^KTG@XNrEVSvo|HIP?H;7ZhYeZkhSqh-{reE!5di;1zk$#Y zCe7rOnlzFYJ6Z#Hm$GoidKB=2HBCwm`BbZVeZY4ukmG%1uz7p2URs6c9j-Gjj^oQV zsdDb3@k2e`C$1I5ML5U0Qs0C1GAp^?!*`=|Nm(vWz3j*j*8ucum2;r0^-6Aca=Gv) zc%}&;!+_*S2tlnnJnz0EKeRmw-Y!@9ob!XQBwiv}^u9MkaXHvM=!<3YX;+2#5Cj5pp?FEK750S3BgeSDtaE^ zXUM@xoV6yBFKfzvY20V&Lr0yC + + DHT22 basic temperature-humidity sensor + extras + +.. toctree:: + :caption: Other Links + + Download + CircuitPython Reference Documentation + CircuitPython Support Forum + Discord Chat + Adafruit Learning System + Adafruit Blog + Adafruit Store + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` From 662fe4528733985c935c1462db5d19e99f11ba21 Mon Sep 17 00:00:00 2001 From: sommersoft Date: Sat, 24 Feb 2018 20:02:23 -0600 Subject: [PATCH 09/62] updated .travis & .readthedocs yml --- readthedocs.yml => .readthedocs.yml | 2 ++ .travis.yml | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) rename readthedocs.yml => .readthedocs.yml (61%) diff --git a/readthedocs.yml b/.readthedocs.yml similarity index 61% rename from readthedocs.yml rename to .readthedocs.yml index a3a16c1..78a4671 100644 --- a/readthedocs.yml +++ b/.readthedocs.yml @@ -1,2 +1,4 @@ +python: + version: 3 requirements_file: requirements.txt diff --git a/.travis.yml b/.travis.yml index 65862d3..36ca9b5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,15 +16,16 @@ deploy: provider: releases api_key: $GITHUB_TOKEN file_glob: true - file: bundles/* + file: $TRAVIS_BUILD_DIR/bundles/* skip_cleanup: true on: tags: true install: - - pip install pylint circuitpython-build-tools + - pip install pylint circuitpython-build-tools Sphinx sphinx-rtd-theme script: - pylint adafruit_dht.py - ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name examples/*.py) - circuitpython-build-bundles --filename_prefix adafruit-circuitpython-dht --library_location . + - cd docs && sphinx-build -E -W -b html . _build/html From fecbbfa2b9300d73ff2d5435e252bfb425e9af7b Mon Sep 17 00:00:00 2001 From: sommersoft Date: Sat, 24 Feb 2018 20:04:35 -0600 Subject: [PATCH 10/62] updated README --- README.rst | 57 ++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/README.rst b/README.rst index 08f601d..9afb920 100644 --- a/README.rst +++ b/README.rst @@ -6,9 +6,10 @@ Introduction :target: https://circuitpython.readthedocs.io/projects/dht/en/latest/ :alt: Documentation Status -.. image :: https://badges.gitter.im/adafruit/circuitpython.svg - :target: https://gitter.im/adafruit/circuitpython?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge - :alt: Gitter + +.. image :: https://img.shields.io/discord/327254708534116352.svg + :target: https://discord.gg/nBQh6qu + :alt: Discord CircuitPython support for the DHT11 and DHT22 temperature and humidity devices. @@ -79,10 +80,50 @@ Contributions are welcome! Please read our `Code of Conduct `_ before contributing to help this project stay welcoming. -API Reference -============= +Building locally +================ + +To build this library locally you'll need to install the +`circuitpython-build-tools `_ package. + +.. code-block:: shell + + python3 -m venv .env + source .env/bin/activate + pip 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 + pip 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 -.. toctree:: - :maxdepth: 2 +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. - api From 49db26f432c93563c7a657f94d66590aa726cb2b Mon Sep 17 00:00:00 2001 From: sommersoft Date: Sat, 24 Feb 2018 20:08:23 -0600 Subject: [PATCH 11/62] sphinx fix; README --- README.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.rst b/README.rst index 9afb920..5748e01 100644 --- a/README.rst +++ b/README.rst @@ -24,17 +24,17 @@ This is easily achieved by downloading `the Adafruit library and driver bundle `_. Usage Example -============= +============== Hardware Set-up ---------------- +---------------- The DHT11 and DHT22 devices both need a pull-resistor on the data signal wire. This resistor is in the range of 1k to 5k. Please check your device datasheet for the appropriate value. Basics ------- +------- Of course, you must import the library to use it: @@ -61,7 +61,7 @@ OR initialize the DHT22 device: dht_device = adafruit_dht.DHT22() Read temperature and humidity ----------------------------- +------------------------------ Now get the temperature and humidity values From b5d59b39691bea5a147a5cd9e5c2fae0825270ba Mon Sep 17 00:00:00 2001 From: sommersoft Date: Sat, 24 Feb 2018 20:35:09 -0600 Subject: [PATCH 12/62] updated examples; requested change in PR #4 --- examples/dht_simpletest.py | 2 +- examples/dht_to_led_display.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/dht_simpletest.py b/examples/dht_simpletest.py index 1947174..ef2e81c 100644 --- a/examples/dht_simpletest.py +++ b/examples/dht_simpletest.py @@ -8,7 +8,7 @@ while True: try: # show the values to the serial port - temperature = dhtDevice.temperature*9/5+32 + temperature = dhtDevice.temperature * (9 / 5) + 32 humidity = dhtDevice.humidity print("Temp: {:.1f} F Humidity: {}% ".format(temperature, humidity)) diff --git a/examples/dht_to_led_display.py b/examples/dht_to_led_display.py index b3b7335..de7bed1 100644 --- a/examples/dht_to_led_display.py +++ b/examples/dht_to_led_display.py @@ -25,7 +25,7 @@ while True: try: # show the values to the serial port - temperature = dhtDevice.temperature*9/5+32 + temperature = dhtDevice.temperature * (9 / 5) + 32 humidity = dhtDevice.humidity #print("Temp: {:.1f} F Humidity: {}% ".format(temperature, humidity)) From cffe9190f63b70b89311a2ad2f8b959736a48d7d Mon Sep 17 00:00:00 2001 From: sommersoft Date: Sat, 10 Mar 2018 09:40:33 -0600 Subject: [PATCH 13/62] updated README; added Travis badge --- README.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.rst b/README.rst index 5748e01..36e310f 100644 --- a/README.rst +++ b/README.rst @@ -11,6 +11,10 @@ Introduction :target: https://discord.gg/nBQh6qu :alt: Discord +.. image:: https://travis-ci.org/adafruit/Adafruit_CircuitPython_DHT.svg?branch=master + :target: https://travis-ci.org/adafruit/Adafruit_CircuitPython_DHT + :alt: Build Status + CircuitPython support for the DHT11 and DHT22 temperature and humidity devices. Dependencies From 5794b1cae96e248cfbc383452939849df98e7832 Mon Sep 17 00:00:00 2001 From: sommersoft Date: Sat, 10 Mar 2018 09:40:49 -0600 Subject: [PATCH 14/62] updated conf.py; bus device intersphinx link --- docs/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index c853a13..4cfd5d3 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ ] intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None), - 'BusDevice': ('https://circuitpython.readthedocs.io/projects/bus_device/en/latest/', None), + 'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None), 'Register': ('https://circuitpython.readthedocs.io/projects/register/en/latest/', None), 'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} From 2531cb06ee2009bd95b9810f6a61464c08349655 Mon Sep 17 00:00:00 2001 From: sommersoft Date: Fri, 16 Mar 2018 18:28:24 -0500 Subject: [PATCH 15/62] added LICENSE file --- LICENSE | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..75d7f43 --- /dev/null +++ b/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2017 Mike McWethy for Adafruit Industries +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 354dbf94f9467a56e9038df8fb0ebb62d6402c02 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Mon, 16 Apr 2018 08:01:32 -0400 Subject: [PATCH 16/62] modifued get_pulses to reduce errors - wait for timeout then use last 81 pulses - adjust lockout for dht11 --- adafruit_dht.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index f455fe6..d15e6d9 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -100,7 +100,6 @@ def _get_pulses(self): pulses will have 81 elements for the DHT11/22 type devices. """ pulses = array.array('H') - tmono = time.monotonic() # create the PulseIn object using context manager with pulseio.PulseIn(self._pin, 81, True) as pulse_in: @@ -115,13 +114,15 @@ def _get_pulses(self): pulse_in.resume(self._trig_wait) # loop until we get the return pulse we need or - # time out after 1/2 seconds + # time out after 1/4 second + tmono = time.monotonic() while True: - if len(pulse_in) >= 80: - break - if time.monotonic()-tmono > 0.5: # time out after 1/2 seconds + #if len(pulse_in) >= 82: + # break + if time.monotonic()-tmono > 0.25: # time out after 1/4 seconds break + #print(len(pulse_in)) pulse_in.pause() while pulse_in: pulses.append(pulse_in.popleft()) @@ -137,11 +138,15 @@ def measure(self): Raises RuntimeError exception for checksum failure and for insuffcient data returned from the device (try again) """ - if time.monotonic()-self._last_called > 0.5: + delay_between_readings = 0.5 + if(self._dht11): + delay_between_readings = 1.0 + if time.monotonic()-self._last_called > delay_between_readings: self._last_called = time.monotonic() pulses = self._get_pulses() - ##print(pulses) + #print(pulses) + #print(len(pulses)) if len(pulses) >= 80: buf = array.array('B') @@ -169,6 +174,7 @@ def measure(self): # checksum is the last byte if chk_sum & 0xff != buf[4]: # check sum failed to validate + #print(pulses) raise RuntimeError("Checksum did not validate. Try again.") #print("checksum did not match. Temp: {} Humidity: {} Checksum:{}" #.format(self._temperature,self._humidity,bites[4])) From 053e0f46218f3cc51103f43db429a31baca3a521 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Mon, 16 Apr 2018 09:28:50 -0400 Subject: [PATCH 17/62] pylint fix --- adafruit_dht.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index d15e6d9..4c9b5b4 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -139,7 +139,7 @@ def measure(self): data returned from the device (try again) """ delay_between_readings = 0.5 - if(self._dht11): + if self._dht11 : delay_between_readings = 1.0 if time.monotonic()-self._last_called > delay_between_readings: self._last_called = time.monotonic() From 0cf82dc9e51c03c6930cc13556cf6a0f239e5322 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Mon, 16 Apr 2018 09:34:01 -0400 Subject: [PATCH 18/62] pylint fix --- adafruit_dht.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 4c9b5b4..57c9d88 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -139,7 +139,7 @@ def measure(self): data returned from the device (try again) """ delay_between_readings = 0.5 - if self._dht11 : + if self._dht11: delay_between_readings = 1.0 if time.monotonic()-self._last_called > delay_between_readings: self._last_called = time.monotonic() From 45a7fb5dba817581cce777f482052c137e617818 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Mon, 16 Apr 2018 13:39:39 -0400 Subject: [PATCH 19/62] remove commented code --- adafruit_dht.py | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 57c9d88..068405f 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -117,12 +117,9 @@ def _get_pulses(self): # time out after 1/4 second tmono = time.monotonic() while True: - #if len(pulse_in) >= 82: - # break if time.monotonic()-tmono > 0.25: # time out after 1/4 seconds break - #print(len(pulse_in)) pulse_in.pause() while pulse_in: pulses.append(pulse_in.popleft()) @@ -145,14 +142,11 @@ def measure(self): self._last_called = time.monotonic() pulses = self._get_pulses() - #print(pulses) - #print(len(pulses)) if len(pulses) >= 80: buf = array.array('B') for byte_start in range(0, 80, 16): buf.append(self._pulses_to_binary(pulses, byte_start, byte_start+16)) - #print(buf) # humidity is 2 bytes if self._dht11: @@ -160,7 +154,7 @@ def measure(self): else: self._humidity = ((buf[0]<<8) | buf[1]) / 10 - # tempature is 2 bytes + # temperature is 2 bytes if self._dht11: self._temperature = buf[2] else: @@ -174,17 +168,11 @@ def measure(self): # checksum is the last byte if chk_sum & 0xff != buf[4]: # check sum failed to validate - #print(pulses) raise RuntimeError("Checksum did not validate. Try again.") - #print("checksum did not match. Temp: {} Humidity: {} Checksum:{}" - #.format(self._temperature,self._humidity,bites[4])) - # checksum matches - #print("Temp: {} C Humidity: {}% ".format(self._temperature, self._humidity)) else: raise RuntimeError("A full buffer was not returned. Try again.") - #print("did not get a full return. number returned was: {}".format(len(r))) @property def temperature(self): From 2046e8efc00369bf3ae3420bbcc2a540dca31bdb Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Sat, 28 Apr 2018 16:14:34 -0400 Subject: [PATCH 20/62] fix DHT22 handling of negative temperatures --- adafruit_dht.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 068405f..b4d8da8 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -148,17 +148,23 @@ def measure(self): for byte_start in range(0, 80, 16): buf.append(self._pulses_to_binary(pulses, byte_start, byte_start+16)) - # humidity is 2 bytes if self._dht11: + # humidity is 1 byte self._humidity = buf[0] else: + # humidity is 2 bytes self._humidity = ((buf[0]<<8) | buf[1]) / 10 - # temperature is 2 bytes if self._dht11: + # temperature is 1 byte self._temperature = buf[2] else: - self._temperature = ((buf[2]<<8) | buf[3]) / 10 + # temperature is 2 bytes + # MSB ist sign, bits 0-14 are magnitude) + self._temperature = (((buf[2] & 0x7f)<<8) | buf[3]) / 10 + # set sign + if buf[2] & 0x80: + self._temperature = -self.temperature # calc checksum chk_sum = 0 From c8dbbdb7790693791c72a420e992c0306625fb27 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Sat, 28 Apr 2018 16:25:49 -0400 Subject: [PATCH 21/62] fix typo --- adafruit_dht.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index b4d8da8..9ed07b4 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -164,7 +164,7 @@ def measure(self): self._temperature = (((buf[2] & 0x7f)<<8) | buf[3]) / 10 # set sign if buf[2] & 0x80: - self._temperature = -self.temperature + self._temperature = -self._temperature # calc checksum chk_sum = 0 From 2aaaf1b340abbe5562ed1a11947dcf418534a1eb Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Sat, 28 Apr 2018 17:03:15 -0400 Subject: [PATCH 22/62] fix pylint issue --- adafruit_dht.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 9ed07b4..e7e8595 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -160,12 +160,12 @@ def measure(self): self._temperature = buf[2] else: # temperature is 2 bytes - # MSB ist sign, bits 0-14 are magnitude) - self._temperature = (((buf[2] & 0x7f)<<8) | buf[3]) / 10 + # MSB is sign, bits 0-14 are magnitude) + raw_temperature = (((buf[2] & 0x7f)<<8) | buf[3]) / 10 # set sign if buf[2] & 0x80: - self._temperature = -self._temperature - + raw_temperature = -raw_temperature + self._temperature = raw_temperature # calc checksum chk_sum = 0 for b in buf[0:4]: @@ -176,7 +176,6 @@ def measure(self): # check sum failed to validate raise RuntimeError("Checksum did not validate. Try again.") - else: raise RuntimeError("A full buffer was not returned. Try again.") From eaa625d6238558ab662cb87ba73d9a5a49418e92 Mon Sep 17 00:00:00 2001 From: Brennen Bearnes Date: Thu, 26 Jul 2018 23:56:25 -0600 Subject: [PATCH 23/62] add setup.py & better .gitignore, misc. tweaks for pypi Per instructions at: adafruit/circuitpython#979 --- .gitignore | 10 +++++++- .travis.yml | 34 +++++++++++++-------------- docs/conf.py | 2 -- requirements.txt | 1 + setup.py | 60 ++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 86 insertions(+), 21 deletions(-) create mode 100644 setup.py diff --git a/.gitignore b/.gitignore index 5b5b0c8..cc1a9c8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,12 @@ +*.mpy +.idea +__pycache__ +_build +*.pyc .env build* bundles - +*.DS_Store +.eggs +dist +**/*.egg-info diff --git a/.travis.yml b/.travis.yml index 36ca9b5..523a40c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,31 +1,29 @@ -# This is a common .travis.yml for generating library release zip files for -# CircuitPython library releases using circuitpython-build-tools. -# See https://github.com/adafruit/circuitpython-build-tools for detailed setup -# instructions. - dist: trusty sudo: false language: python python: - - "3.6" - +- '3.6' cache: - pip: true - + pip: true deploy: provider: releases - api_key: $GITHUB_TOKEN + api_key: "$GITHUB_TOKEN" file_glob: true - file: $TRAVIS_BUILD_DIR/bundles/* + file: "$TRAVIS_BUILD_DIR/bundles/*" skip_cleanup: true on: tags: true - +- provider: pypi + user: adafruit-travis + on: + tags: true + password: + secure: vygpUo9Cn8Jn2LqKP1MXzhlusmEoJLB/OBRbni7sI6V0STk04D6/8y3tCvqxhllhCz9CeGTygW8F97TmsgzjXo/jinEbb2wKpCUUa1m6JuJK3tgvg/VaR3OdTFzkbcphP9W00mQs1tjA3L5Kpnj3J3G8X3/Bmq8JKxbMygCyUfCYqNzxv8DptUye/XCG1vMBrJD+Pd+aSgw/OlWmc8rHrg19p8+boVSouOgI/fVFSGCc78iDly6Uzk0nlDtBwh2XH/2AhhgoxLGQZbwblFzJ/kV/NdVdp9BWD1xsY7+2Pi/yN7/7Xk+/ffpYKnGxA6gRcIbjAd6QJxmmJySnz4INABjSiohs1iI5zhqjiQeGevsmGQJx/mcNxExie+DVtjWjkbwEB/ayWDiLrphtVrN2hFzBznlkEPNp+eVECRe1bUnsRJf5rzLs/4VRP+XN4pYjXBFo8Dd/QpjiB8rC579c3IS/frdamC0Za1muHmWw4mXzhCt1gGJznewGBraFM7YRIk/5LeRgJxbLih66glmppHYnoDUkMd7jzcw46OMzmTzJGTXk17mHA/bTKaCUQYjBLOQ9PizJq3nZxan08A7cXOcepNrpodyorpn4sDujYbv3LyLCxe1nswjGknoTDojb+sFO6Yq/LnZyitx6uwv5Lkj3U0qvOj8DQLtkyKS6xIo= install: - - pip install pylint circuitpython-build-tools Sphinx sphinx-rtd-theme - +- pip install -r requirements.txt +- pip install pylint circuitpython-build-tools Sphinx sphinx-rtd-theme script: - - pylint adafruit_dht.py - - ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name examples/*.py) - - circuitpython-build-bundles --filename_prefix adafruit-circuitpython-dht --library_location . - - cd docs && sphinx-build -E -W -b html . _build/html +- pylint adafruit_dht.py +- ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name examples/*.py) +- circuitpython-build-bundles --filename_prefix adafruit-circuitpython-dht --library_location . +- cd docs && sphinx-build -E -W -b html . _build/html && cd .. diff --git a/docs/conf.py b/docs/conf.py index 4cfd5d3..92f399d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,8 +20,6 @@ 'Register': ('https://circuitpython.readthedocs.io/projects/register/en/latest/', None), 'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} -autodoc_mock_imports = ["pulseio"] - # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] diff --git a/requirements.txt b/requirements.txt index e69de29..edf9394 100644 --- a/requirements.txt +++ b/requirements.txt @@ -0,0 +1 @@ +Adafruit-Blinka diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..2817391 --- /dev/null +++ b/setup.py @@ -0,0 +1,60 @@ +"""A setuptools based setup module. + +See: +https://packaging.python.org/en/latest/distributing.html +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 + +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: + long_description = f.read() + +setup( + name='adafruit-circuitpython-dht', + + use_scm_version=True, + setup_requires=['setuptools_scm'], + + description='CircuitPython support for DHT11 and DHT22 type temperature/humidity devices', + long_description=long_description, + long_description_content_type='text/x-rst', + + # The project's main homepage. + url='https://github.com/adafruit/Adafruit_CircuitPython_DHT', + + # Author details + author='Adafruit Industries', + author_email='circuitpython@adafruit.com', + + install_requires=['Adafruit-Blinka'], + + # Choose your license + 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', + ], + + # What does your project relate to? + keywords='adafruit dht hardware sensors temperature humidity micropython circuitpython', + + # You can just specify the packages manually here if your project is + # simple. Or you can use find_packages(). + py_modules=['adafruit_dht'], +) From ef73b96de873f102c2afced4d44e86fe3d2fa0ef Mon Sep 17 00:00:00 2001 From: Kattni Rembor Date: Fri, 3 Aug 2018 12:39:15 -0400 Subject: [PATCH 24/62] Updates for PyPi, linting. --- .travis.yml | 4 +++- docs/conf.py | 2 ++ examples/dht_simpletest.py | 2 +- examples/dht_to_led_display.py | 6 +++--- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 523a40c..a64ee26 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,11 +6,12 @@ python: cache: pip: true deploy: - provider: releases +- provider: releases api_key: "$GITHUB_TOKEN" file_glob: true file: "$TRAVIS_BUILD_DIR/bundles/*" skip_cleanup: true + overwrite: true on: tags: true - provider: pypi @@ -22,6 +23,7 @@ deploy: 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_dht.py - ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name examples/*.py) diff --git a/docs/conf.py b/docs/conf.py index 92f399d..caed051 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -15,6 +15,8 @@ 'sphinx.ext.viewcode', ] +autodoc_mock_imports = ["pulseio"] + intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None), 'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None), 'Register': ('https://circuitpython.readthedocs.io/projects/register/en/latest/', None), diff --git a/examples/dht_simpletest.py b/examples/dht_simpletest.py index ef2e81c..4686c4d 100644 --- a/examples/dht_simpletest.py +++ b/examples/dht_simpletest.py @@ -1,6 +1,6 @@ import time -import adafruit_dht from board import D2 +import adafruit_dht #initial the dht device dhtDevice = adafruit_dht.DHT22(D2) diff --git a/examples/dht_to_led_display.py b/examples/dht_to_led_display.py index de7bed1..7eee861 100644 --- a/examples/dht_to_led_display.py +++ b/examples/dht_to_led_display.py @@ -5,16 +5,16 @@ """ # import for dht devices and 7-segment display devices import time +from board import D2, TX, RX, D1 import adafruit_dht -from adafruit_max7219 import bcddigits +from adafruit_max7219 import bcddigits import busio import digitalio -from board import D2, TX, RX, A2 clk = RX din = TX -cs = digitalio.DigitalInOut(A2) +cs = digitalio.DigitalInOut(D1) spi = busio.SPI(clk, MOSI=din) display = bcddigits.BCDDigits(spi, cs, nDigits=8) display.brightness(5) From bd8aa8e65e855ac00212b259422742335b1ef632 Mon Sep 17 00:00:00 2001 From: Kattni Rembor Date: Fri, 3 Aug 2018 12:43:10 -0400 Subject: [PATCH 25/62] linting --- examples/dht_to_led_display.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/dht_to_led_display.py b/examples/dht_to_led_display.py index 7eee861..3286f3b 100644 --- a/examples/dht_to_led_display.py +++ b/examples/dht_to_led_display.py @@ -6,10 +6,10 @@ # import for dht devices and 7-segment display devices import time from board import D2, TX, RX, D1 -import adafruit_dht -from adafruit_max7219 import bcddigits import busio import digitalio +import adafruit_dht +from adafruit_max7219 import bcddigits clk = RX From 23254cab7e6586af369a578027f8142e7eba23dc Mon Sep 17 00:00:00 2001 From: sommersoft Date: Tue, 14 Aug 2018 20:01:03 -0500 Subject: [PATCH 26/62] ignore the board module imports in .pylintrc Signed-off-by: sommersoft --- .pylintrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index e274ba9..8154969 100644 --- a/.pylintrc +++ b/.pylintrc @@ -155,7 +155,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. From 93aed219d41d03755b4b7a1425b6798ea2f8f033 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Sun, 14 Oct 2018 13:39:04 -0400 Subject: [PATCH 27/62] fix first read issue --- adafruit_dht.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index e7e8595..e7759a3 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -138,7 +138,7 @@ def measure(self): delay_between_readings = 0.5 if self._dht11: delay_between_readings = 1.0 - if time.monotonic()-self._last_called > delay_between_readings: + if (self._last_called == 0) or (time.monotonic()-self._last_called > delay_between_readings): self._last_called = time.monotonic() pulses = self._get_pulses() From 8d7ce76e7f3a30f3227b53527a8f43713fbd4b9f Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Sun, 14 Oct 2018 13:54:26 -0400 Subject: [PATCH 28/62] fix pylint issue - line too long --- adafruit_dht.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index e7759a3..490d13b 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -138,7 +138,8 @@ def measure(self): delay_between_readings = 0.5 if self._dht11: delay_between_readings = 1.0 - if (self._last_called == 0) or (time.monotonic()-self._last_called > delay_between_readings): + if (self._last_called == 0) or \ + (time.monotonic()-self._last_called > delay_between_readings): self._last_called = time.monotonic() pulses = self._get_pulses() From ddb9d66096b19eb8110cee303b1e3a223884ec78 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Mon, 15 Oct 2018 07:39:00 -0400 Subject: [PATCH 29/62] fix continuation line --- adafruit_dht.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 490d13b..2037c41 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -138,8 +138,8 @@ def measure(self): delay_between_readings = 0.5 if self._dht11: delay_between_readings = 1.0 - if (self._last_called == 0) or \ - (time.monotonic()-self._last_called > delay_between_readings): + if (self._last_called == 0 or + (time.monotonic()-self._last_called) > delay_between_readings): self._last_called = time.monotonic() pulses = self._get_pulses() From bcdc7a7469e936fb70e9c865ae0a2220b1fe7041 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Mon, 15 Oct 2018 07:50:31 -0400 Subject: [PATCH 30/62] fix continuation line - add comment --- adafruit_dht.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/adafruit_dht.py b/adafruit_dht.py index 2037c41..1049c5e 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -138,6 +138,9 @@ def measure(self): delay_between_readings = 0.5 if self._dht11: delay_between_readings = 1.0 + # Initialte new reading if this is the first call or if sufficient delay + # If delay not sufficient - return previous reading. + # This allows back to back access for temperature and humidity for same reading if (self._last_called == 0 or (time.monotonic()-self._last_called) > delay_between_readings): self._last_called = time.monotonic() From 125890ed6e9b33a7a96f58ce3055c529c018b452 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Tue, 16 Oct 2018 11:24:33 -0700 Subject: [PATCH 31/62] Fix typo --- adafruit_dht.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 1049c5e..e4842c3 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -138,7 +138,7 @@ def measure(self): delay_between_readings = 0.5 if self._dht11: delay_between_readings = 1.0 - # Initialte new reading if this is the first call or if sufficient delay + # Initiate new reading if this is the first call or if sufficient delay # If delay not sufficient - return previous reading. # This allows back to back access for temperature and humidity for same reading if (self._last_called == 0 or From d4ec646fb2c3efa88f6ca152672bc4483b75b66c Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Wed, 17 Oct 2018 06:34:29 -0400 Subject: [PATCH 32/62] resolve pr_14 conflicts - fix bug with sample delay --- adafruit_dht.py | 91 ++++++++++++++++++++++------------ examples/dht_simpletest.py | 17 ++++--- examples/dht_to_led_display.py | 2 +- 3 files changed, 69 insertions(+), 41 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index e4842c3..edf679c 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -30,12 +30,14 @@ import array import time +from digitalio import DigitalInOut, Pull, Direction +_USE_PULSEIO = False try: import pulseio -except ImportError as excpt: - print("adafruit_dht requires the pulseio library, but it failed to load."+ - " Note that CircuitPython does not support pulseio on all boards.") - raise excpt + _USE_PULSEIO = True +except ImportError: + pass # This is OK, we'll try to bitbang it! + __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_DHT.git" @@ -101,30 +103,51 @@ def _get_pulses(self): """ pulses = array.array('H') - # create the PulseIn object using context manager - with pulseio.PulseIn(self._pin, 81, True) as pulse_in: - - # The DHT type device use a specialize 1-wire protocol - # The microprocessor first sends a LOW signal for a - # specific length of time. Then the device sends back a - # series HIGH and LOW signals. The length the HIGH signals - # represents the device values. - pulse_in.pause() - pulse_in.clear() - pulse_in.resume(self._trig_wait) - - # loop until we get the return pulse we need or - # time out after 1/4 second - tmono = time.monotonic() - while True: - if time.monotonic()-tmono > 0.25: # time out after 1/4 seconds - break - - pulse_in.pause() - while pulse_in: - pulses.append(pulse_in.popleft()) - pulse_in.resume() - + if _USE_PULSEIO: + # create the PulseIn object using context manager + with pulseio.PulseIn(self._pin, 81, True) as pulse_in: + + # The DHT type device use a specialize 1-wire protocol + # The microprocessor first sends a LOW signal for a + # specific length of time. Then the device sends back a + # series HIGH and LOW signals. The length the HIGH signals + # represents the device values. + pulse_in.pause() + pulse_in.clear() + pulse_in.resume(self._trig_wait) + + # loop until we get the return pulse we need or + # time out after 1/4 second + tmono = time.monotonic() + while time.monotonic() - tmono < 0.25: + pass # time out after 1/4 seconds + pulse_in.pause() + while pulse_in: + pulses.append(pulse_in.popleft()) + pulse_in.resume() + else: + with DigitalInOut(self._pin) as dhtpin: + # we will bitbang if no pulsein capability + transitions = [] + # Signal by setting pin high, then low, and releasing + dhtpin.direction = Direction.OUTPUT + dhtpin.value = True + time.sleep(0.1) + dhtpin.value = False + time.sleep(0.001) + + timestamp = time.monotonic() # take timestamp + dhtval = True # start with dht pin true because its pulled up + dhtpin.direction = Direction.INPUT + dhtpin.pull = Pull.UP + while time.monotonic() - timestamp < 0.1: + if dhtval != dhtpin.value: + dhtval = not dhtval # we toggled + transitions.append(time.monotonic()) # save the timestamp + # convert transtions to microsecond delta pulses: + for i in range(1, len(transitions)): + pulses_micro_sec = int(1000000 * (transitions[i] - transitions[i-1])) + pulses.append(min(pulses_micro_sec, 65535)) return pulses def measure(self): @@ -135,9 +158,7 @@ def measure(self): Raises RuntimeError exception for checksum failure and for insuffcient data returned from the device (try again) """ - delay_between_readings = 0.5 - if self._dht11: - delay_between_readings = 1.0 + delay_between_readings = 2 # 2 seconds per read according to datasheet # Initiate new reading if this is the first call or if sufficient delay # If delay not sufficient - return previous reading. # This allows back to back access for temperature and humidity for same reading @@ -146,6 +167,7 @@ def measure(self): self._last_called = time.monotonic() pulses = self._get_pulses() + #print(len(pulses), "pulses:", [x for x in pulses]) if len(pulses) >= 80: buf = array.array('B') @@ -180,9 +202,12 @@ def measure(self): # check sum failed to validate raise RuntimeError("Checksum did not validate. Try again.") - else: + elif len(pulses) >= 10: + # We got *some* data just not 81 bits raise RuntimeError("A full buffer was not returned. Try again.") - + else: + # Probably a connection issue! + raise RuntimeError("DHT sensor not found, check wiring") @property def temperature(self): """ temperature current reading. It makes sure a reading is available diff --git a/examples/dht_simpletest.py b/examples/dht_simpletest.py index 4686c4d..e07c078 100644 --- a/examples/dht_simpletest.py +++ b/examples/dht_simpletest.py @@ -1,18 +1,21 @@ import time -from board import D2 +import board import adafruit_dht -#initial the dht device -dhtDevice = adafruit_dht.DHT22(D2) +# Initial the dht device, with data pin connected to: +dhtDevice = adafruit_dht.DHT22(board.D18) while True: try: - # show the values to the serial port - temperature = dhtDevice.temperature * (9 / 5) + 32 + # Print the values to the serial port + temperature_c = dhtDevice.temperature + temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity - print("Temp: {:.1f} F Humidity: {}% ".format(temperature, humidity)) + print("Temp: {:.1f} F / {:.1f} C Humidity: {}% " + .format(temperature_f, temperature_c, humidity)) except RuntimeError as error: - print(error.args) + # Errors happen fairly often, DHT's are hard to read, just keep going + print(error.args[0]) time.sleep(2.0) diff --git a/examples/dht_to_led_display.py b/examples/dht_to_led_display.py index 3286f3b..d3cb3a9 100644 --- a/examples/dht_to_led_display.py +++ b/examples/dht_to_led_display.py @@ -35,6 +35,6 @@ display.show() except RuntimeError as error: - print(error.args) + print(error.args[0]) time.sleep(2.0) From de4f5f38f5fb25f89847f2e17c58b14519d1ec80 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Wed, 17 Oct 2018 06:40:08 -0400 Subject: [PATCH 33/62] pylint - indent error --- adafruit_dht.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index edf679c..27e5e22 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -120,7 +120,7 @@ def _get_pulses(self): # time out after 1/4 second tmono = time.monotonic() while time.monotonic() - tmono < 0.25: - pass # time out after 1/4 seconds + pass # time out after 1/4 seconds pulse_in.pause() while pulse_in: pulses.append(pulse_in.popleft()) From d122696eda4a5e7858b23141ef67a556db4a5224 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Wed, 17 Oct 2018 07:36:43 -0400 Subject: [PATCH 34/62] tweak to RPi pulse detect --- adafruit_dht.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 27e5e22..5cd8748 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -145,7 +145,9 @@ def _get_pulses(self): dhtval = not dhtval # we toggled transitions.append(time.monotonic()) # save the timestamp # convert transtions to microsecond delta pulses: - for i in range(1, len(transitions)): + # use last 81 pulses + transition_start = max(1, len(transitions) - 81) + for i in range(transition_start, len(transitions)): pulses_micro_sec = int(1000000 * (transitions[i] - transitions[i-1])) pulses.append(min(pulses_micro_sec, 65535)) return pulses From d2da8739c030a66c5d17e731ed9debe9409e5e37 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Wed, 17 Oct 2018 14:57:53 -0400 Subject: [PATCH 35/62] make delay for bitbang same as for pulseio --- adafruit_dht.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 5cd8748..eebcdd6 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -140,7 +140,7 @@ def _get_pulses(self): dhtval = True # start with dht pin true because its pulled up dhtpin.direction = Direction.INPUT dhtpin.pull = Pull.UP - while time.monotonic() - timestamp < 0.1: + while time.monotonic() - timestamp < 0.25: if dhtval != dhtpin.value: dhtval = not dhtval # we toggled transitions.append(time.monotonic()) # save the timestamp From 105157930bfa10f0734f8ef308b11a8333583067 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Thu, 18 Oct 2018 22:07:09 -0400 Subject: [PATCH 36/62] create private functions for pulseio and bitbang version of getting pulses --- adafruit_dht.py | 115 +++++++++++++++++++++++++----------------------- 1 file changed, 61 insertions(+), 54 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index eebcdd6..2860bee 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -91,7 +91,7 @@ def _pulses_to_binary(self, pulses, start, stop): return binary - def _get_pulses(self): + def _get_pulses_pulseio(self): """ _get_pulses implements the communication protcol for DHT11 and DHT22 type devices. It sends a start signal of a specific length and listens and measures the @@ -102,54 +102,61 @@ def _get_pulses(self): pulses will have 81 elements for the DHT11/22 type devices. """ pulses = array.array('H') + # create the PulseIn object using context manager + with pulseio.PulseIn(self._pin, 81, True) as pulse_in: + # The DHT type device use a specialize 1-wire protocol + # The microprocessor first sends a LOW signal for a + # specific length of time. Then the device sends back a + # series HIGH and LOW signals. The length the HIGH signals + # represents the device values. + pulse_in.pause() + pulse_in.clear() + pulse_in.resume(self._trig_wait) + # loop until we get the return pulse we need or + # time out after 1/4 second + tmono = time.monotonic() + while time.monotonic() - tmono < 0.25: + pass # time out after 1/4 seconds + pulse_in.pause() + while pulse_in: + pulses.append(pulse_in.popleft()) + pulse_in.resume() + return pulses + + def _get_pulses_bitbang(self): + """ _get_pulses implements the communication protcol for + DHT11 and DHT22 type devices. It sends a start signal + of a specific length and listens and measures the + return signal lengths. - if _USE_PULSEIO: - # create the PulseIn object using context manager - with pulseio.PulseIn(self._pin, 81, True) as pulse_in: - - # The DHT type device use a specialize 1-wire protocol - # The microprocessor first sends a LOW signal for a - # specific length of time. Then the device sends back a - # series HIGH and LOW signals. The length the HIGH signals - # represents the device values. - pulse_in.pause() - pulse_in.clear() - pulse_in.resume(self._trig_wait) - - # loop until we get the return pulse we need or - # time out after 1/4 second - tmono = time.monotonic() - while time.monotonic() - tmono < 0.25: - pass # time out after 1/4 seconds - pulse_in.pause() - while pulse_in: - pulses.append(pulse_in.popleft()) - pulse_in.resume() - else: - with DigitalInOut(self._pin) as dhtpin: - # we will bitbang if no pulsein capability - transitions = [] - # Signal by setting pin high, then low, and releasing - dhtpin.direction = Direction.OUTPUT - dhtpin.value = True - time.sleep(0.1) - dhtpin.value = False - time.sleep(0.001) - - timestamp = time.monotonic() # take timestamp - dhtval = True # start with dht pin true because its pulled up - dhtpin.direction = Direction.INPUT - dhtpin.pull = Pull.UP - while time.monotonic() - timestamp < 0.25: - if dhtval != dhtpin.value: - dhtval = not dhtval # we toggled - transitions.append(time.monotonic()) # save the timestamp - # convert transtions to microsecond delta pulses: - # use last 81 pulses - transition_start = max(1, len(transitions) - 81) - for i in range(transition_start, len(transitions)): - pulses_micro_sec = int(1000000 * (transitions[i] - transitions[i-1])) - pulses.append(min(pulses_micro_sec, 65535)) + return pulses (array.array uint16) contains alternating high and low + transition times starting with a low transition time. Normally + pulses will have 81 elements for the DHT11/22 type devices. + """ + pulses = array.array('H') + with DigitalInOut(self._pin) as dhtpin: + # we will bitbang if no pulsein capability + transitions = [] + # Signal by setting pin high, then low, and releasing + dhtpin.direction = Direction.OUTPUT + dhtpin.value = True + time.sleep(0.1) + dhtpin.value = False + time.sleep(0.001) + timestamp = time.monotonic() # take timestamp + dhtval = True # start with dht pin true because its pulled up + dhtpin.direction = Direction.INPUT + dhtpin.pull = Pull.UP + while time.monotonic() - timestamp < 0.25: + if dhtval != dhtpin.value: + dhtval = not dhtval # we toggled + transitions.append(time.monotonic()) # save the timestamp + # convert transtions to microsecond delta pulses: + # use last 81 pulses + transition_start = max(1, len(transitions) - 81) + for i in range(transition_start, len(transitions)): + pulses_micro_sec = int(1000000 * (transitions[i] - transitions[i-1])) + pulses.append(min(pulses_micro_sec, 65535)) return pulses def measure(self): @@ -168,7 +175,10 @@ def measure(self): (time.monotonic()-self._last_called) > delay_between_readings): self._last_called = time.monotonic() - pulses = self._get_pulses() + if _USE_PULSEIO: + pulses = self._get_pulses_pulseio() + else: + pulses = self._get_pulses_bitbang() #print(len(pulses), "pulses:", [x for x in pulses]) if len(pulses) >= 80: @@ -179,14 +189,11 @@ def measure(self): if self._dht11: # humidity is 1 byte self._humidity = buf[0] - else: - # humidity is 2 bytes - self._humidity = ((buf[0]<<8) | buf[1]) / 10 - - if self._dht11: # temperature is 1 byte self._temperature = buf[2] else: + # humidity is 2 bytes + self._humidity = ((buf[0]<<8) | buf[1]) / 10 # temperature is 2 bytes # MSB is sign, bits 0-14 are magnitude) raw_temperature = (((buf[2] & 0x7f)<<8) | buf[3]) / 10 From 98fcb2b71913412cea7377977e894c341e597de5 Mon Sep 17 00:00:00 2001 From: ladyada Date: Sat, 1 Dec 2018 02:06:56 -0500 Subject: [PATCH 37/62] removed context for pulse_in to make linux happy, and change delay to not use time.monotonic --- adafruit_dht.py | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 2860bee..316fad6 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -60,7 +60,10 @@ def __init__(self, dht11, pin, trig_wait): self._last_called = 0 self._humidity = None self._temperature = None - + # We don't use a context because linux-based systems are sluggish + # and we're better off having a running process + if _USE_PULSEIO: + self.pulse_in = pulseio.PulseIn(self._pin, 81, True) def _pulses_to_binary(self, pulses, start, stop): """Takes pulses, a list of transition times, and converts @@ -102,25 +105,22 @@ def _get_pulses_pulseio(self): pulses will have 81 elements for the DHT11/22 type devices. """ pulses = array.array('H') - # create the PulseIn object using context manager - with pulseio.PulseIn(self._pin, 81, True) as pulse_in: - # The DHT type device use a specialize 1-wire protocol - # The microprocessor first sends a LOW signal for a - # specific length of time. Then the device sends back a - # series HIGH and LOW signals. The length the HIGH signals - # represents the device values. - pulse_in.pause() - pulse_in.clear() - pulse_in.resume(self._trig_wait) - # loop until we get the return pulse we need or - # time out after 1/4 second - tmono = time.monotonic() - while time.monotonic() - tmono < 0.25: - pass # time out after 1/4 seconds - pulse_in.pause() - while pulse_in: - pulses.append(pulse_in.popleft()) - pulse_in.resume() + if _USE_PULSEIO: + # The DHT type device use a specialize 1-wire protocol + # The microprocessor first sends a LOW signal for a + # specific length of time. Then the device sends back a + # series HIGH and LOW signals. The length the HIGH signals + # represents the device values. + self.pulse_in.pause() + self.pulse_in.clear() + self.pulse_in.resume(self._trig_wait) + + # loop until we get the return pulse we need or + # time out after 1/4 second + time.sleep(0.25) + self.pulse_in.pause() + while self.pulse_in: + pulses.append(self.pulse_in.popleft()) return pulses def _get_pulses_bitbang(self): From 90149ac09074621cddb7575079e4f363fd444e6f Mon Sep 17 00:00:00 2001 From: ladyada Date: Sat, 1 Dec 2018 02:08:04 -0500 Subject: [PATCH 38/62] nicetabs --- adafruit_dht.py | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 316fad6..017f9f2 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -106,21 +106,21 @@ def _get_pulses_pulseio(self): """ pulses = array.array('H') if _USE_PULSEIO: - # The DHT type device use a specialize 1-wire protocol - # The microprocessor first sends a LOW signal for a - # specific length of time. Then the device sends back a - # series HIGH and LOW signals. The length the HIGH signals - # represents the device values. - self.pulse_in.pause() - self.pulse_in.clear() - self.pulse_in.resume(self._trig_wait) - - # loop until we get the return pulse we need or - # time out after 1/4 second - time.sleep(0.25) - self.pulse_in.pause() - while self.pulse_in: - pulses.append(self.pulse_in.popleft()) + # The DHT type device use a specialize 1-wire protocol + # The microprocessor first sends a LOW signal for a + # specific length of time. Then the device sends back a + # series HIGH and LOW signals. The length the HIGH signals + # represents the device values. + self.pulse_in.pause() + self.pulse_in.clear() + self.pulse_in.resume(self._trig_wait) + + # loop until we get the return pulse we need or + # time out after 1/4 second + time.sleep(0.25) + self.pulse_in.pause() + while self.pulse_in: + pulses.append(self.pulse_in.popleft()) return pulses def _get_pulses_bitbang(self): From 62bb5c86d8ad7cbbce40fc73e4cbd631c3cd94cd Mon Sep 17 00:00:00 2001 From: sommersoft Date: Fri, 21 Dec 2018 13:25:35 -0600 Subject: [PATCH 39/62] change 'travis-ci.org' to 'travis-ci.com' --- README.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 36e310f..0eb7276 100644 --- a/README.rst +++ b/README.rst @@ -11,8 +11,8 @@ Introduction :target: https://discord.gg/nBQh6qu :alt: Discord -.. image:: https://travis-ci.org/adafruit/Adafruit_CircuitPython_DHT.svg?branch=master - :target: https://travis-ci.org/adafruit/Adafruit_CircuitPython_DHT +.. image:: https://travis-ci.com/adafruit/Adafruit_CircuitPython_DHT.svg?branch=master + :target: https://travis-ci.com/adafruit/Adafruit_CircuitPython_DHT :alt: Build Status CircuitPython support for the DHT11 and DHT22 temperature and humidity devices. From 0643ebbbcd8bdb4e233741511896069f29e1a917 Mon Sep 17 00:00:00 2001 From: Melissa LeBlanc-Williams Date: Wed, 11 Sep 2019 14:09:45 -0700 Subject: [PATCH 40/62] Lack of PulseIn detection now working --- adafruit_dht.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 017f9f2..2956cc7 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -33,7 +33,7 @@ from digitalio import DigitalInOut, Pull, Direction _USE_PULSEIO = False try: - import pulseio + from pulseio import PulseIn _USE_PULSEIO = True except ImportError: pass # This is OK, we'll try to bitbang it! @@ -63,7 +63,7 @@ def __init__(self, dht11, pin, trig_wait): # We don't use a context because linux-based systems are sluggish # and we're better off having a running process if _USE_PULSEIO: - self.pulse_in = pulseio.PulseIn(self._pin, 81, True) + self.pulse_in = PulseIn(self._pin, 81, True) def _pulses_to_binary(self, pulses, start, stop): """Takes pulses, a list of transition times, and converts From 097531b8fff209420e1951453aabe5bf4cd5e434 Mon Sep 17 00:00:00 2001 From: dherrada <33632497+dherrada@users.noreply.github.com> Date: Fri, 18 Oct 2019 10:55:46 -0400 Subject: [PATCH 41/62] Added PyPi installation instructions & documentation section --- README.rst | 74 +++++++++++++++++++++--------------------------------- 1 file changed, 28 insertions(+), 46 deletions(-) diff --git a/README.rst b/README.rst index 0eb7276..64b8eba 100644 --- a/README.rst +++ b/README.rst @@ -27,6 +27,31 @@ Please ensure all dependencies are available on the CircuitPython filesystem. This is easily achieved by downloading `the Adafruit library and driver bundle `_. +Installing from PyPI +==================== + +On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from +PyPI `_. To install for current user: + +.. code-block:: shell + + pip3 install adafruit-circuitpython-dht + +To install system-wide (this may be required in some cases): + +.. code-block:: shell + + sudo pip3 install adafruit-circuitpython-dht + +To install in a virtual environment in your current project: + +.. code-block:: shell + + mkdir project-name && cd project-name + python3 -m venv .env + source .env/bin/activate + pip3 install adafruit-circuitpython-dht + Usage Example ============== @@ -84,50 +109,7 @@ Contributions are welcome! Please read our `Code of Conduct `_ before contributing to help this project stay welcoming. -Building locally -================ - -To build this library locally you'll need to install the -`circuitpython-build-tools `_ package. - -.. code-block:: shell - - python3 -m venv .env - source .env/bin/activate - pip 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 - pip 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. +Documentation +============= +For information on building library documentation, please check out `this guide `_. From 3248e3e7919a811d6909a6f3d57b885bd57862b5 Mon Sep 17 00:00:00 2001 From: dherrada Date: Sat, 4 Jan 2020 15:14:45 -0500 Subject: [PATCH 42/62] Moved repository from Travis to GitHub Actions --- .github/workflows/build.yml | 50 +++++++++++++++++++++ .github/workflows/release.yml | 81 +++++++++++++++++++++++++++++++++++ .gitignore | 1 - .travis.yml | 31 -------------- README.rst | 4 +- 5 files changed, 133 insertions(+), 34 deletions(-) create mode 100644 .github/workflows/build.yml create mode 100644 .github/workflows/release.yml delete mode 100644 .travis.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..66ce4db --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,50 @@ +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 deps + run: | + source actions-ci/install.sh + - name: Library version + run: git describe --dirty --always --tags + - name: PyLint + run: | + pylint $( find . -path './adafruit*.py' ) + ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace 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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..18efb9c --- /dev/null +++ b/.github/workflows/release.yml @@ -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/* diff --git a/.gitignore b/.gitignore index cc1a9c8..1be1c4b 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,6 @@ __pycache__ _build *.pyc .env -build* bundles *.DS_Store .eggs diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index a64ee26..0000000 --- a/.travis.yml +++ /dev/null @@ -1,31 +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: vygpUo9Cn8Jn2LqKP1MXzhlusmEoJLB/OBRbni7sI6V0STk04D6/8y3tCvqxhllhCz9CeGTygW8F97TmsgzjXo/jinEbb2wKpCUUa1m6JuJK3tgvg/VaR3OdTFzkbcphP9W00mQs1tjA3L5Kpnj3J3G8X3/Bmq8JKxbMygCyUfCYqNzxv8DptUye/XCG1vMBrJD+Pd+aSgw/OlWmc8rHrg19p8+boVSouOgI/fVFSGCc78iDly6Uzk0nlDtBwh2XH/2AhhgoxLGQZbwblFzJ/kV/NdVdp9BWD1xsY7+2Pi/yN7/7Xk+/ffpYKnGxA6gRcIbjAd6QJxmmJySnz4INABjSiohs1iI5zhqjiQeGevsmGQJx/mcNxExie+DVtjWjkbwEB/ayWDiLrphtVrN2hFzBznlkEPNp+eVECRe1bUnsRJf5rzLs/4VRP+XN4pYjXBFo8Dd/QpjiB8rC579c3IS/frdamC0Za1muHmWw4mXzhCt1gGJznewGBraFM7YRIk/5LeRgJxbLih66glmppHYnoDUkMd7jzcw46OMzmTzJGTXk17mHA/bTKaCUQYjBLOQ9PizJq3nZxan08A7cXOcepNrpodyorpn4sDujYbv3LyLCxe1nswjGknoTDojb+sFO6Yq/LnZyitx6uwv5Lkj3U0qvOj8DQLtkyKS6xIo= -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_dht.py -- ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name examples/*.py) -- circuitpython-build-bundles --filename_prefix adafruit-circuitpython-dht --library_location . -- cd docs && sphinx-build -E -W -b html . _build/html && cd .. diff --git a/README.rst b/README.rst index 64b8eba..b7956c2 100644 --- a/README.rst +++ b/README.rst @@ -11,8 +11,8 @@ Introduction :target: https://discord.gg/nBQh6qu :alt: Discord -.. image:: https://travis-ci.com/adafruit/Adafruit_CircuitPython_DHT.svg?branch=master - :target: https://travis-ci.com/adafruit/Adafruit_CircuitPython_DHT +.. image:: https://github.com/adafruit/Adafruit_CircuitPython_DHT/workflows/Build%20CI/badge.svg + :target: https://github.com/adafruit/Adafruit_CircuitPython_DHT/actions :alt: Build Status CircuitPython support for the DHT11 and DHT22 temperature and humidity devices. From 0ea15b6a9f075ebecabc02f59dcff9cbcc6f3703 Mon Sep 17 00:00:00 2001 From: dherrada <33632497+dherrada@users.noreply.github.com> Date: Thu, 23 Jan 2020 10:51:32 -0500 Subject: [PATCH 43/62] Update pylint examples directive --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 66ce4db..11ce574 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -42,7 +42,7 @@ jobs: - name: PyLint run: | pylint $( find . -path './adafruit*.py' ) - ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace examples/*.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 From 7060d64d83b53713c35cc69e22de35bcfd359570 Mon Sep 17 00:00:00 2001 From: stefan Date: Fri, 28 Feb 2020 19:40:24 +0100 Subject: [PATCH 44/62] #34 update readme --- README.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index b7956c2..bdafd17 100644 --- a/README.rst +++ b/README.rst @@ -100,7 +100,8 @@ Now get the temperature and humidity values humidity = dht_device.humidity These properties may raise an exception if a problem occurs. You should use try/raise -logic and catch RuntimeError and then retry getting the values after 1/2 second. +logic and catch RuntimeError and then retry getting the values after at least 2 seconds. +If you try again to get a result within 2 seconds, cached values are returned. Contributing ============ From c23e7401f1840a1d402964e2113b85d56c220c30 Mon Sep 17 00:00:00 2001 From: sommersoft Date: Sun, 15 Mar 2020 23:31:42 -0500 Subject: [PATCH 45/62] update code of conduct --- CODE_OF_CONDUCT.md | 125 ++++++++++++++++++++++++++++++++------------- 1 file changed, 90 insertions(+), 35 deletions(-) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 1617586..134d510 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -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 don’t 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. -## Scope +## Moderation -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. +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 . -## Enforcement +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. -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. +Email and direct message reports will be kept confidential. -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. +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 community’s 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. 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 +, +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. From b9ef1b5bfff41e2e4456e20fac9404e0847046cd Mon Sep 17 00:00:00 2001 From: sommersoft Date: Thu, 5 Mar 2020 22:06:59 -0600 Subject: [PATCH 46/62] update pylintrc for black Signed-off-by: sommersoft --- .pylintrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index 8154969..5a43a10 100644 --- a/.pylintrc +++ b/.pylintrc @@ -52,7 +52,7 @@ confidence= # no Warning level messages displayed, use"--disable=all --enable=classes # --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 # either give multiple identifier separated by comma (,) or put this option From cd063e5094eb628a71d61ba36aba5abc18af927a Mon Sep 17 00:00:00 2001 From: sommersoft Date: Mon, 16 Mar 2020 21:12:48 -0500 Subject: [PATCH 47/62] update build.yml to pip install pylint black sphinx Signed-off-by: sommersoft --- .github/workflows/build.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 11ce574..fff3aa9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -34,9 +34,13 @@ jobs: with: repository: adafruit/actions-ci-circuitpython-libs path: actions-ci - - name: Install deps + - 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==1.9.2 black==19.10b0 Sphinx sphinx-rtd-theme - name: Library version run: git describe --dirty --always --tags - name: PyLint From 01c7d786e36e30dca88479afe81a9df5ca94d6ee Mon Sep 17 00:00:00 2001 From: dherrada Date: Fri, 20 Mar 2020 12:13:58 -0400 Subject: [PATCH 48/62] Ran black, updated to pylint 2.x --- .github/workflows/build.yml | 2 +- adafruit_dht.py | 43 +++++++----- docs/conf.py | 121 ++++++++++++++++++++------------- examples/dht_simpletest.py | 7 +- examples/dht_to_led_display.py | 6 +- setup.py | 50 ++++++-------- 6 files changed, 129 insertions(+), 100 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fff3aa9..1dad804 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,7 +40,7 @@ jobs: source actions-ci/install.sh - name: Pip install pylint, black, & Sphinx run: | - pip install --force-reinstall pylint==1.9.2 black==19.10b0 Sphinx sphinx-rtd-theme + pip install --force-reinstall pylint black==19.10b0 Sphinx sphinx-rtd-theme - name: Library version run: git describe --dirty --always --tags - name: PyLint diff --git a/adafruit_dht.py b/adafruit_dht.py index 2956cc7..4c9083f 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -31,17 +31,20 @@ import array import time from digitalio import DigitalInOut, Pull, Direction + _USE_PULSEIO = False try: from pulseio import PulseIn + _USE_PULSEIO = True except ImportError: - pass # This is OK, we'll try to bitbang it! + pass # This is OK, we'll try to bitbang it! __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_DHT.git" + class DHTBase: """ base support for DHT11 and DHT22 devices """ @@ -88,7 +91,7 @@ def _pulses_to_binary(self, pulses, start, stop): bit = 0 if pulses[bit_inx] > self.__hiLevel: bit = 1 - binary = binary<<1 | bit + binary = binary << 1 | bit hi_sig = not hi_sig @@ -104,7 +107,7 @@ def _get_pulses_pulseio(self): transition times starting with a low transition time. Normally pulses will have 81 elements for the DHT11/22 type devices. """ - pulses = array.array('H') + pulses = array.array("H") if _USE_PULSEIO: # The DHT type device use a specialize 1-wire protocol # The microprocessor first sends a LOW signal for a @@ -133,7 +136,7 @@ def _get_pulses_bitbang(self): transition times starting with a low transition time. Normally pulses will have 81 elements for the DHT11/22 type devices. """ - pulses = array.array('H') + pulses = array.array("H") with DigitalInOut(self._pin) as dhtpin: # we will bitbang if no pulsein capability transitions = [] @@ -143,19 +146,19 @@ def _get_pulses_bitbang(self): time.sleep(0.1) dhtpin.value = False time.sleep(0.001) - timestamp = time.monotonic() # take timestamp - dhtval = True # start with dht pin true because its pulled up + timestamp = time.monotonic() # take timestamp + dhtval = True # start with dht pin true because its pulled up dhtpin.direction = Direction.INPUT dhtpin.pull = Pull.UP while time.monotonic() - timestamp < 0.25: if dhtval != dhtpin.value: dhtval = not dhtval # we toggled - transitions.append(time.monotonic()) # save the timestamp + transitions.append(time.monotonic()) # save the timestamp # convert transtions to microsecond delta pulses: # use last 81 pulses transition_start = max(1, len(transitions) - 81) for i in range(transition_start, len(transitions)): - pulses_micro_sec = int(1000000 * (transitions[i] - transitions[i-1])) + pulses_micro_sec = int(1000000 * (transitions[i] - transitions[i - 1])) pulses.append(min(pulses_micro_sec, 65535)) return pulses @@ -171,20 +174,24 @@ def measure(self): # Initiate new reading if this is the first call or if sufficient delay # If delay not sufficient - return previous reading. # This allows back to back access for temperature and humidity for same reading - if (self._last_called == 0 or - (time.monotonic()-self._last_called) > delay_between_readings): + if ( + self._last_called == 0 + or (time.monotonic() - self._last_called) > delay_between_readings + ): self._last_called = time.monotonic() if _USE_PULSEIO: pulses = self._get_pulses_pulseio() else: pulses = self._get_pulses_bitbang() - #print(len(pulses), "pulses:", [x for x in pulses]) + # print(len(pulses), "pulses:", [x for x in pulses]) if len(pulses) >= 80: - buf = array.array('B') + buf = array.array("B") for byte_start in range(0, 80, 16): - buf.append(self._pulses_to_binary(pulses, byte_start, byte_start+16)) + buf.append( + self._pulses_to_binary(pulses, byte_start, byte_start + 16) + ) if self._dht11: # humidity is 1 byte @@ -193,10 +200,10 @@ def measure(self): self._temperature = buf[2] else: # humidity is 2 bytes - self._humidity = ((buf[0]<<8) | buf[1]) / 10 + self._humidity = ((buf[0] << 8) | buf[1]) / 10 # temperature is 2 bytes # MSB is sign, bits 0-14 are magnitude) - raw_temperature = (((buf[2] & 0x7f)<<8) | buf[3]) / 10 + raw_temperature = (((buf[2] & 0x7F) << 8) | buf[3]) / 10 # set sign if buf[2] & 0x80: raw_temperature = -raw_temperature @@ -207,7 +214,7 @@ def measure(self): chk_sum += b # checksum is the last byte - if chk_sum & 0xff != buf[4]: + if chk_sum & 0xFF != buf[4]: # check sum failed to validate raise RuntimeError("Checksum did not validate. Try again.") @@ -217,6 +224,7 @@ def measure(self): else: # Probably a connection issue! raise RuntimeError("DHT sensor not found, check wiring") + @property def temperature(self): """ temperature current reading. It makes sure a reading is available @@ -237,11 +245,13 @@ def humidity(self): self.measure() return self._humidity + class DHT11(DHTBase): """ Support for DHT11 device. :param ~board.Pin pin: digital pin used for communication """ + def __init__(self, pin): super().__init__(True, pin, 18000) @@ -251,5 +261,6 @@ class DHT22(DHTBase): :param ~board.Pin pin: digital pin used for communication """ + def __init__(self, pin): super().__init__(False, pin, 1000) diff --git a/docs/conf.py b/docs/conf.py index caed051..b628bfa 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -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,39 +11,47 @@ # 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", ] autodoc_mock_imports = ["pulseio"] -intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None), - 'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None), - 'Register': ('https://circuitpython.readthedocs.io/projects/register/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, + ), + "Register": ( + "https://circuitpython.readthedocs.io/projects/register/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 CircuitPython DHT Library' -copyright = u'2017 Mike McWethy' -author = u'Mike McWethy' +project = u"Adafruit CircuitPython DHT Library" +copyright = u"2017 Mike McWethy" +author = u"Mike McWethy" # 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 = u"1.0" # The full version, including alpha/beta/rc tags. -release = u'1.0' +release = u"1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -54,7 +63,7 @@ # 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. @@ -66,7 +75,7 @@ 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 @@ -80,59 +89,62 @@ # 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 = 'AdafruitCircuitPythonDHTLibrarydoc' +htmlhelp_basename = "AdafruitCircuitPythonDHTLibrarydoc" # -- Options for LaTeX output --------------------------------------------- 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', + # 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', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'AdafruitCircuitPythonDHTLibrary.tex', u'Adafruit CircuitPython DHT Library Documentation', - author, 'manual'), + ( + master_doc, + "AdafruitCircuitPythonDHTLibrary.tex", + u"Adafruit CircuitPython DHT Library Documentation", + author, + "manual", + ), ] # -- Options for manual page output --------------------------------------- @@ -140,8 +152,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'adafruitCircuitPythonDHTlibrary', u'Adafruit CircuitPython DHT Library Documentation', - [author], 1) + ( + master_doc, + "adafruitCircuitPythonDHTlibrary", + u"Adafruit CircuitPython DHT Library Documentation", + [author], + 1, + ) ] # -- Options for Texinfo output ------------------------------------------- @@ -150,7 +167,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'AdafruitCircuitPythonDHTLibrary', u'Adafruit CircuitPython DHT Library Documentation', - author, 'AdafruitCircuitPythonDHTLibrary', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "AdafruitCircuitPythonDHTLibrary", + u"Adafruit CircuitPython DHT Library Documentation", + author, + "AdafruitCircuitPythonDHTLibrary", + "One line description of project.", + "Miscellaneous", + ), ] diff --git a/examples/dht_simpletest.py b/examples/dht_simpletest.py index e07c078..9a054d1 100644 --- a/examples/dht_simpletest.py +++ b/examples/dht_simpletest.py @@ -11,8 +11,11 @@ temperature_c = dhtDevice.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity - print("Temp: {:.1f} F / {:.1f} C Humidity: {}% " - .format(temperature_f, temperature_c, humidity)) + print( + "Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format( + temperature_f, temperature_c, humidity + ) + ) except RuntimeError as error: # Errors happen fairly often, DHT's are hard to read, just keep going diff --git a/examples/dht_to_led_display.py b/examples/dht_to_led_display.py index d3cb3a9..41baaa5 100644 --- a/examples/dht_to_led_display.py +++ b/examples/dht_to_led_display.py @@ -19,7 +19,7 @@ display = bcddigits.BCDDigits(spi, cs, nDigits=8) display.brightness(5) -#initial the dht device +# initial the dht device dhtDevice = adafruit_dht.DHT22(D2) while True: @@ -27,11 +27,11 @@ # show the values to the serial port temperature = dhtDevice.temperature * (9 / 5) + 32 humidity = dhtDevice.humidity - #print("Temp: {:.1f} F Humidity: {}% ".format(temperature, humidity)) + # print("Temp: {:.1f} F Humidity: {}% ".format(temperature, humidity)) # now show the values on the 8 digit 7-segment display display.clear_all() - display.show_str(0, '{:5.1f}{:5.1f}'.format(temperature, humidity)) + display.show_str(0, "{:5.1f}{:5.1f}".format(temperature, humidity)) display.show() except RuntimeError as error: diff --git a/setup.py b/setup.py index 2817391..834fba2 100644 --- a/setup.py +++ b/setup.py @@ -7,6 +7,7 @@ # 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 @@ 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-dht', - + name="adafruit-circuitpython-dht", use_scm_version=True, - setup_requires=['setuptools_scm'], - - description='CircuitPython support for DHT11 and DHT22 type temperature/humidity devices', + setup_requires=["setuptools_scm"], + description="CircuitPython support for DHT11 and DHT22 type temperature/humidity devices", 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_DHT', - + url="https://github.com/adafruit/Adafruit_CircuitPython_DHT", # Author details - author='Adafruit Industries', - author_email='circuitpython@adafruit.com', - - install_requires=['Adafruit-Blinka'], - + author="Adafruit Industries", + author_email="circuitpython@adafruit.com", + install_requires=["Adafruit-Blinka"], # 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 dht hardware sensors temperature humidity micropython circuitpython', - + keywords="adafruit dht hardware sensors temperature humidity micropython circuitpython", # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). - py_modules=['adafruit_dht'], + py_modules=["adafruit_dht"], ) From 1833318bde1138203a453d2c0f1d2edc10ed0e56 Mon Sep 17 00:00:00 2001 From: Michael Lass Date: Tue, 28 Jan 2020 21:13:37 +0100 Subject: [PATCH 49/62] Do not update sensor values on error Currently, we update self._temperature and self._humidity, even if it turns out that the data returned by the sensor was bogus. If the user queries the data within two seconds after an error, they will actually get wrong data. Fix this by updating _temperature and _humidity attributes only if no error was detected. --- adafruit_dht.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 4c9083f..2f3c473 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -180,6 +180,9 @@ def measure(self): ): self._last_called = time.monotonic() + new_temperature = 0 + new_humidity = 0 + if _USE_PULSEIO: pulses = self._get_pulses_pulseio() else: @@ -195,19 +198,19 @@ def measure(self): if self._dht11: # humidity is 1 byte - self._humidity = buf[0] + new_humidity = buf[0] # temperature is 1 byte - self._temperature = buf[2] + new_temperature = buf[2] else: # humidity is 2 bytes - self._humidity = ((buf[0] << 8) | buf[1]) / 10 + new_humidity = ((buf[0] << 8) | buf[1]) / 10 # temperature is 2 bytes # MSB is sign, bits 0-14 are magnitude) raw_temperature = (((buf[2] & 0x7F) << 8) | buf[3]) / 10 # set sign if buf[2] & 0x80: raw_temperature = -raw_temperature - self._temperature = raw_temperature + new_temperature = raw_temperature # calc checksum chk_sum = 0 for b in buf[0:4]: @@ -220,11 +223,14 @@ def measure(self): elif len(pulses) >= 10: # We got *some* data just not 81 bits - raise RuntimeError("A full buffer was not returned. Try again.") + raise RuntimeError("A full buffer was not returned. Try again.") else: # Probably a connection issue! raise RuntimeError("DHT sensor not found, check wiring") + self._temperature = new_temperature + self._humidity = new_humidity + @property def temperature(self): """ temperature current reading. It makes sure a reading is available From e6880d74f633e72d3588eb62402117e5c266c7b4 Mon Sep 17 00:00:00 2001 From: Michael Lass Date: Tue, 28 Jan 2020 21:19:30 +0100 Subject: [PATCH 50/62] Reject humidity outside of range (0, 100) as unplausible --- adafruit_dht.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/adafruit_dht.py b/adafruit_dht.py index 2f3c473..6f40d54 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -221,6 +221,10 @@ def measure(self): # check sum failed to validate raise RuntimeError("Checksum did not validate. Try again.") + if new_humidity < 0 or new_humidity > 100: + # We received unplausible data + raise RuntimeError("Received unplausible data. Try again.") + elif len(pulses) >= 10: # We got *some* data just not 81 bits raise RuntimeError("A full buffer was not returned. Try again.") From efda9b8e9d4dae0e85c0b0854e9edbf0ce77fe1c Mon Sep 17 00:00:00 2001 From: Michael Lass Date: Sun, 2 Feb 2020 20:35:37 +0100 Subject: [PATCH 51/62] Reduce number of branches to make pylint happy --- adafruit_dht.py | 75 ++++++++++++++++++++++++------------------------- 1 file changed, 36 insertions(+), 39 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index 6f40d54..fb2b188 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -189,48 +189,45 @@ def measure(self): pulses = self._get_pulses_bitbang() # print(len(pulses), "pulses:", [x for x in pulses]) - if len(pulses) >= 80: - buf = array.array("B") - for byte_start in range(0, 80, 16): - buf.append( - self._pulses_to_binary(pulses, byte_start, byte_start + 16) - ) - - if self._dht11: - # humidity is 1 byte - new_humidity = buf[0] - # temperature is 1 byte - new_temperature = buf[2] - else: - # humidity is 2 bytes - new_humidity = ((buf[0] << 8) | buf[1]) / 10 - # temperature is 2 bytes - # MSB is sign, bits 0-14 are magnitude) - raw_temperature = (((buf[2] & 0x7F) << 8) | buf[3]) / 10 - # set sign - if buf[2] & 0x80: - raw_temperature = -raw_temperature - new_temperature = raw_temperature - # calc checksum - chk_sum = 0 - for b in buf[0:4]: - chk_sum += b - - # checksum is the last byte - if chk_sum & 0xFF != buf[4]: - # check sum failed to validate - raise RuntimeError("Checksum did not validate. Try again.") - - if new_humidity < 0 or new_humidity > 100: - # We received unplausible data - raise RuntimeError("Received unplausible data. Try again.") - - elif len(pulses) >= 10: + if len(pulses) < 10: + # Probably a connection issue! + raise RuntimeError("DHT sensor not found, check wiring") + + if len(pulses) < 80: # We got *some* data just not 81 bits raise RuntimeError("A full buffer was not returned. Try again.") + + buf = array.array("B") + for byte_start in range(0, 80, 16): + buf.append(self._pulses_to_binary(pulses, byte_start, byte_start + 16)) + + if self._dht11: + # humidity is 1 byte + new_humidity = buf[0] + # temperature is 1 byte + new_temperature = buf[2] else: - # Probably a connection issue! - raise RuntimeError("DHT sensor not found, check wiring") + # humidity is 2 bytes + new_humidity = ((buf[0] << 8) | buf[1]) / 10 + # temperature is 2 bytes + # MSB is sign, bits 0-14 are magnitude) + new_temperature = (((buf[2] & 0x7F) << 8) | buf[3]) / 10 + # set sign + if buf[2] & 0x80: + new_temperature = -new_temperature + # calc checksum + chk_sum = 0 + for b in buf[0:4]: + chk_sum += b + + # checksum is the last byte + if chk_sum & 0xFF != buf[4]: + # check sum failed to validate + raise RuntimeError("Checksum did not validate. Try again.") + + if new_humidity < 0 or new_humidity > 100: + # We received unplausible data + raise RuntimeError("Received unplausible data. Try again.") self._temperature = new_temperature self._humidity = new_humidity From b770bb45adcbd7a395fd2e09f323f0e17dd32530 Mon Sep 17 00:00:00 2001 From: sommersoft Date: Tue, 7 Apr 2020 15:02:31 -0500 Subject: [PATCH 52/62] build.yml: add black formatting check Signed-off-by: sommersoft --- .github/workflows/build.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1dad804..b6977a9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -43,6 +43,9 @@ jobs: 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' ) From b9acab847837b2fb97d630dbbc65d862c40a9991 Mon Sep 17 00:00:00 2001 From: Kattni Rembor Date: Wed, 8 Apr 2020 14:34:33 -0400 Subject: [PATCH 53/62] Black reformatting with Python 3 target. --- docs/conf.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index b628bfa..736346b 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -40,18 +40,18 @@ master_doc = "index" # General information about the project. -project = u"Adafruit CircuitPython DHT Library" -copyright = u"2017 Mike McWethy" -author = u"Mike McWethy" +project = "Adafruit CircuitPython DHT Library" +copyright = "2017 Mike McWethy" +author = "Mike McWethy" # 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. @@ -141,7 +141,7 @@ ( master_doc, "AdafruitCircuitPythonDHTLibrary.tex", - u"Adafruit CircuitPython DHT Library Documentation", + "Adafruit CircuitPython DHT Library Documentation", author, "manual", ), @@ -155,7 +155,7 @@ ( master_doc, "adafruitCircuitPythonDHTlibrary", - u"Adafruit CircuitPython DHT Library Documentation", + "Adafruit CircuitPython DHT Library Documentation", [author], 1, ) @@ -170,7 +170,7 @@ ( master_doc, "AdafruitCircuitPythonDHTLibrary", - u"Adafruit CircuitPython DHT Library Documentation", + "Adafruit CircuitPython DHT Library Documentation", author, "AdafruitCircuitPythonDHTLibrary", "One line description of project.", From 35cc6b451822e3a0f77f21a6f109cb843d660887 Mon Sep 17 00:00:00 2001 From: dherrada Date: Wed, 8 Jul 2020 16:49:04 -0400 Subject: [PATCH 54/62] Fixed discord invite link --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index bdafd17..3b54da9 100644 --- a/README.rst +++ b/README.rst @@ -8,7 +8,7 @@ Introduction .. image :: https://img.shields.io/discord/327254708534116352.svg - :target: https://discord.gg/nBQh6qu + :target: https://adafru.it/discord :alt: Discord .. image:: https://github.com/adafruit/Adafruit_CircuitPython_DHT/workflows/Build%20CI/badge.svg From 5c1da73177420274319d2b42d9e18d003e352db9 Mon Sep 17 00:00:00 2001 From: dherrada Date: Thu, 16 Jul 2020 15:45:13 -0400 Subject: [PATCH 55/62] Deinitialize pulsein object on exit, gave option to choose whether or not to use pulseio --- adafruit_dht.py | 22 ++++++++++++++-------- examples/dht_simpletest.py | 7 ++++++- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index fb2b188..bbd9984 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -51,7 +51,7 @@ class DHTBase: __hiLevel = 51 - def __init__(self, dht11, pin, trig_wait): + def __init__(self, dht11, pin, trig_wait, use_pulseio): """ :param boolean dht11: True if device is DHT11, otherwise DHT22. :param ~board.Pin pin: digital pin used for communication @@ -63,11 +63,17 @@ def __init__(self, dht11, pin, trig_wait): self._last_called = 0 self._humidity = None self._temperature = None + self._use_pulseio = use_pulseio # We don't use a context because linux-based systems are sluggish # and we're better off having a running process - if _USE_PULSEIO: + if self._use_pulseio: self.pulse_in = PulseIn(self._pin, 81, True) + def exit(self): + if self._use_pulseio: + print("De-initializing self.pulse_in") + self.pulse_in.deinit() + def _pulses_to_binary(self, pulses, start, stop): """Takes pulses, a list of transition times, and converts them to a 1's or 0's. The pulses array contains the transition times. @@ -108,7 +114,7 @@ def _get_pulses_pulseio(self): pulses will have 81 elements for the DHT11/22 type devices. """ pulses = array.array("H") - if _USE_PULSEIO: + if self._use_pulseio: # The DHT type device use a specialize 1-wire protocol # The microprocessor first sends a LOW signal for a # specific length of time. Then the device sends back a @@ -183,7 +189,7 @@ def measure(self): new_temperature = 0 new_humidity = 0 - if _USE_PULSEIO: + if self._use_pulseio: pulses = self._get_pulses_pulseio() else: pulses = self._get_pulses_bitbang() @@ -259,8 +265,8 @@ class DHT11(DHTBase): :param ~board.Pin pin: digital pin used for communication """ - def __init__(self, pin): - super().__init__(True, pin, 18000) + def __init__(self, pin, use_pulseio=_USE_PULSEIO): + super().__init__(True, pin, 18000, use_pulseio) class DHT22(DHTBase): @@ -269,5 +275,5 @@ class DHT22(DHTBase): :param ~board.Pin pin: digital pin used for communication """ - def __init__(self, pin): - super().__init__(False, pin, 1000) + def __init__(self, pin, use_pulseio=_USE_PULSEIO): + super().__init__(False, pin, 1000, use_pulseio) diff --git a/examples/dht_simpletest.py b/examples/dht_simpletest.py index 9a054d1..fcce603 100644 --- a/examples/dht_simpletest.py +++ b/examples/dht_simpletest.py @@ -3,7 +3,7 @@ import adafruit_dht # Initial the dht device, with data pin connected to: -dhtDevice = adafruit_dht.DHT22(board.D18) +dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False) while True: try: @@ -20,5 +20,10 @@ except RuntimeError as error: # Errors happen fairly often, DHT's are hard to read, just keep going print(error.args[0]) + time.sleep(2.0) + continue + except Exception as error: + dhtDevice.exit() + raise error time.sleep(2.0) From 16400df13d2193dc43b8cc88e5dc6fc1b0c3db3f Mon Sep 17 00:00:00 2001 From: dherrada Date: Fri, 17 Jul 2020 09:44:15 -0400 Subject: [PATCH 56/62] Cleaned up example --- examples/dht_simpletest.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/examples/dht_simpletest.py b/examples/dht_simpletest.py index fcce603..ba2d806 100644 --- a/examples/dht_simpletest.py +++ b/examples/dht_simpletest.py @@ -3,7 +3,12 @@ import adafruit_dht # Initial the dht device, with data pin connected to: -dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False) +dhtDevice = adafruit_dht.DHT22(board.D18) + +# you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio. +# This may be necessary on a Linux single board computer like the Raspberry Pi, +# but it will not work in CircuitPython. +#dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False) while True: try: From 5ea758917ba854383f4b08e856efbef4d6727f02 Mon Sep 17 00:00:00 2001 From: dherrada Date: Fri, 17 Jul 2020 09:49:04 -0400 Subject: [PATCH 57/62] Formatting --- adafruit_dht.py | 1 + examples/dht_simpletest.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index bbd9984..3f6935b 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -70,6 +70,7 @@ def __init__(self, dht11, pin, trig_wait, use_pulseio): self.pulse_in = PulseIn(self._pin, 81, True) def exit(self): + """ Cleans up the PulseIn process. Must be called explicitly """ if self._use_pulseio: print("De-initializing self.pulse_in") self.pulse_in.deinit() diff --git a/examples/dht_simpletest.py b/examples/dht_simpletest.py index ba2d806..2b4cdec 100644 --- a/examples/dht_simpletest.py +++ b/examples/dht_simpletest.py @@ -8,7 +8,7 @@ # you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio. # This may be necessary on a Linux single board computer like the Raspberry Pi, # but it will not work in CircuitPython. -#dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False) +# dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False) while True: try: From a554d72194a16ef11930e8325557643a26b5c693 Mon Sep 17 00:00:00 2001 From: dherrada Date: Fri, 24 Jul 2020 14:50:10 -0400 Subject: [PATCH 58/62] Added exception for trying to bitbang in circuitpython --- adafruit_dht.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/adafruit_dht.py b/adafruit_dht.py index 3f6935b..f6af34d 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -30,6 +30,7 @@ import array import time +from os import uname from digitalio import DigitalInOut, Pull, Direction _USE_PULSEIO = False @@ -64,6 +65,8 @@ def __init__(self, dht11, pin, trig_wait, use_pulseio): self._humidity = None self._temperature = None self._use_pulseio = use_pulseio + if "Linux" not in uname() and not self._use_pulseio: + raise Exception("Bitbanging is not supported when using CircuitPython.") # We don't use a context because linux-based systems are sluggish # and we're better off having a running process if self._use_pulseio: From 847ce956b08efc24015d871c464288d94efaa7b1 Mon Sep 17 00:00:00 2001 From: Michael Lass Date: Thu, 6 Aug 2020 14:52:37 +0200 Subject: [PATCH 59/62] Immediately pause pulse_in after initialization Right now, pulse_in is active until the first reading and only paused after that. Let's immediately pause it to free up the CPU. --- adafruit_dht.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index fb2b188..137994a 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -67,6 +67,7 @@ def __init__(self, dht11, pin, trig_wait): # and we're better off having a running process if _USE_PULSEIO: self.pulse_in = PulseIn(self._pin, 81, True) + self.pulse_in.pause() def _pulses_to_binary(self, pulses, start, stop): """Takes pulses, a list of transition times, and converts @@ -114,7 +115,6 @@ def _get_pulses_pulseio(self): # specific length of time. Then the device sends back a # series HIGH and LOW signals. The length the HIGH signals # represents the device values. - self.pulse_in.pause() self.pulse_in.clear() self.pulse_in.resume(self._trig_wait) From a515f920f5c187c04f9e2fb4deb299c53dcb5218 Mon Sep 17 00:00:00 2001 From: Jerry Needell Date: Wed, 19 Aug 2020 14:44:39 -0400 Subject: [PATCH 60/62] add docstring for use_pulseio kwarg --- adafruit_dht.py | 1 + 1 file changed, 1 insertion(+) diff --git a/adafruit_dht.py b/adafruit_dht.py index f6af34d..973a9c2 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -57,6 +57,7 @@ def __init__(self, dht11, pin, trig_wait, use_pulseio): :param boolean dht11: True if device is DHT11, otherwise DHT22. :param ~board.Pin pin: digital pin used for communication :param int trig_wait: length of time to hold trigger in LOW state (microseconds) + :param boolean use_pulseio: False to force bitbang when pulseio available (only with Blinka) """ self._dht11 = dht11 self._pin = pin From 9a0cb0be14635de9e69f5a5100991cfa2b360c62 Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 31 Aug 2020 12:25:24 -0400 Subject: [PATCH 61/62] Linted --- examples/dht_to_led_display.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/dht_to_led_display.py b/examples/dht_to_led_display.py index 41baaa5..2a116ee 100644 --- a/examples/dht_to_led_display.py +++ b/examples/dht_to_led_display.py @@ -8,8 +8,8 @@ from board import D2, TX, RX, D1 import busio import digitalio -import adafruit_dht from adafruit_max7219 import bcddigits +import adafruit_dht clk = RX From 5fad2ce54d37cc27fd5694a2dc8333dcb2f127f7 Mon Sep 17 00:00:00 2001 From: Jordan ERNST Date: Fri, 13 Nov 2020 16:19:26 +0100 Subject: [PATCH 62/62] Removed a print() in exit function This was polluting stdout --- adafruit_dht.py | 1 - 1 file changed, 1 deletion(-) diff --git a/adafruit_dht.py b/adafruit_dht.py index e7f1a64..0089428 100644 --- a/adafruit_dht.py +++ b/adafruit_dht.py @@ -77,7 +77,6 @@ def __init__(self, dht11, pin, trig_wait, use_pulseio): def exit(self): """ Cleans up the PulseIn process. Must be called explicitly """ if self._use_pulseio: - print("De-initializing self.pulse_in") self.pulse_in.deinit() def _pulses_to_binary(self, pulses, start, stop):