Compare commits
49 commits
build-badg
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ae9f4a744 | ||
|
|
27a5165d4f | ||
|
|
d31993ec02 | ||
|
|
481d615920 | ||
|
|
3de883529e | ||
|
|
793f54519b | ||
|
|
1e52da58bc | ||
|
|
a2ffcc5fe0 | ||
|
|
66ff5687ff | ||
|
|
fb15dd14e4 | ||
|
|
a63edd3d3e | ||
|
|
2a25de68f0 | ||
|
|
6e5b83506b | ||
|
|
f095d52711 | ||
|
|
7443b9ee10 | ||
|
|
7de637927e | ||
|
|
61f06a1ba8 | ||
|
|
dbe4058572 | ||
|
|
f6b6b1d704 | ||
|
|
ccc5a196d5 | ||
|
|
c21f5419a9 | ||
|
|
edc5bdf561 | ||
|
|
f060e9a4fb | ||
|
|
71f24d99c4 | ||
|
|
e9b8614294 | ||
|
|
ab19bce079 | ||
|
|
aeabd11344 | ||
|
|
a533c4b2a0 | ||
|
|
948e27fd71 | ||
|
|
8bb976dca0 | ||
|
|
a8dc88f6bd | ||
|
|
30611acc78 | ||
|
|
cd1a886a46 | ||
|
|
9771f90e57 | ||
|
|
0d05248312 | ||
|
|
650c36937b | ||
|
|
5e099acd2f | ||
|
|
33ba756ac4 | ||
|
|
741932cb93 | ||
|
|
596708b090 | ||
|
|
daea74352e | ||
|
|
ef6951fec1 | ||
|
|
86c35fbc68 | ||
|
|
867f2f854c | ||
|
|
70cb1ca0f5 | ||
|
|
a7d36942f7 | ||
|
|
c7a4a8e7e6 | ||
|
|
727b08fe07 | ||
|
|
18feec7cc7 |
14 changed files with 529 additions and 173 deletions
57
.github/workflows/build.yml
vendored
Normal file
57
.github/workflows/build.yml
vendored
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
name: Build CI
|
||||
|
||||
on: [pull_request, push]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dump GitHub context
|
||||
env:
|
||||
GITHUB_CONTEXT: ${{ toJson(github) }}
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- name: Translate Repo Name For Build Tools filename_prefix
|
||||
id: repo-name
|
||||
run: |
|
||||
echo ::set-output name=repo-name::$(
|
||||
echo ${{ github.repository }} |
|
||||
awk -F '\/' '{ print tolower($2) }' |
|
||||
tr '_' '-'
|
||||
)
|
||||
- name: Set up Python 3.6
|
||||
uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: 3.6
|
||||
- name: Versions
|
||||
run: |
|
||||
python3 --version
|
||||
- name: Checkout Current Repo
|
||||
uses: actions/checkout@v1
|
||||
with:
|
||||
submodules: true
|
||||
- name: Checkout tools repo
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
repository: adafruit/actions-ci-circuitpython-libs
|
||||
path: actions-ci
|
||||
- name: Install dependencies
|
||||
# (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.)
|
||||
run: |
|
||||
source actions-ci/install.sh
|
||||
- name: Pip install pylint, black, & Sphinx
|
||||
run: |
|
||||
pip install --force-reinstall pylint black==19.10b0 Sphinx sphinx-rtd-theme
|
||||
- name: Library version
|
||||
run: git describe --dirty --always --tags
|
||||
- name: Check formatting
|
||||
run: |
|
||||
black --check --target-version=py35 .
|
||||
- name: PyLint
|
||||
run: |
|
||||
pylint $( find . -path './adafruit*.py' )
|
||||
([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace $( find . -path "./examples/*.py" ))
|
||||
- name: Build assets
|
||||
run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location .
|
||||
- name: Build docs
|
||||
working-directory: docs
|
||||
run: sphinx-build -E -W -b html . _build/html
|
||||
81
.github/workflows/release.yml
vendored
Normal file
81
.github/workflows/release.yml
vendored
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
name: Release Actions
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
upload-release-assets:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dump GitHub context
|
||||
env:
|
||||
GITHUB_CONTEXT: ${{ toJson(github) }}
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- name: Translate Repo Name For Build Tools filename_prefix
|
||||
id: repo-name
|
||||
run: |
|
||||
echo ::set-output name=repo-name::$(
|
||||
echo ${{ github.repository }} |
|
||||
awk -F '\/' '{ print tolower($2) }' |
|
||||
tr '_' '-'
|
||||
)
|
||||
- name: Set up Python 3.6
|
||||
uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: 3.6
|
||||
- name: Versions
|
||||
run: |
|
||||
python3 --version
|
||||
- name: Checkout Current Repo
|
||||
uses: actions/checkout@v1
|
||||
with:
|
||||
submodules: true
|
||||
- name: Checkout tools repo
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
repository: adafruit/actions-ci-circuitpython-libs
|
||||
path: actions-ci
|
||||
- name: Install deps
|
||||
run: |
|
||||
source actions-ci/install.sh
|
||||
- name: Build assets
|
||||
run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location .
|
||||
- name: Upload Release Assets
|
||||
# the 'official' actions version does not yet support dynamically
|
||||
# supplying asset names to upload. @csexton's version chosen based on
|
||||
# discussion in the issue below, as its the simplest to implement and
|
||||
# allows for selecting files with a pattern.
|
||||
# https://github.com/actions/upload-release-asset/issues/4
|
||||
#uses: actions/upload-release-asset@v1.0.1
|
||||
uses: csexton/release-asset-action@master
|
||||
with:
|
||||
pattern: "bundles/*"
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
upload-pypi:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Check For setup.py
|
||||
id: need-pypi
|
||||
run: |
|
||||
echo ::set-output name=setup-py::$( find . -wholename './setup.py' )
|
||||
- name: Set up Python
|
||||
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
|
||||
uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: '3.x'
|
||||
- name: Install dependencies
|
||||
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install setuptools wheel twine
|
||||
- name: Build and publish
|
||||
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
|
||||
env:
|
||||
TWINE_USERNAME: ${{ secrets.pypi_username }}
|
||||
TWINE_PASSWORD: ${{ secrets.pypi_password }}
|
||||
run: |
|
||||
python setup.py sdist
|
||||
twine upload dist/*
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,2 +1 @@
|
|||
|
||||
*.mpy
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
33
.travis.yml
33
.travis.yml
|
|
@ -1,33 +0,0 @@
|
|||
# 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: xenial
|
||||
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
|
||||
|
||||
install:
|
||||
- pip install -r requirements.txt
|
||||
- pip install circuitpython-build-tools Sphinx sphinx-rtd-theme
|
||||
- pip install --force-reinstall pylint==1.9.2
|
||||
|
||||
script:
|
||||
- pylint adafruit_debouncer.py
|
||||
- ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace examples/*.py)
|
||||
- circuitpython-build-bundles --filename_prefix adafruit-circuitpython-debouncer --library_location .
|
||||
- cd docs && sphinx-build -E -W -b html . _build/html && cd ..
|
||||
|
|
@ -34,6 +34,8 @@ Examples of unacceptable behavior by participants include:
|
|||
* 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
|
||||
|
|
@ -72,10 +74,10 @@ You may report in the following ways:
|
|||
In any situation, you may send an email to <support@adafruit.com>.
|
||||
|
||||
On the Adafruit Discord, you may send an open message from any channel
|
||||
to all Community Helpers by tagging @community helpers. 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, or
|
||||
@Andon#8175.
|
||||
to all Community Moderators by tagging @community moderators. You may
|
||||
also send an open message from any channel, or a direct message to
|
||||
@kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442,
|
||||
@sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175.
|
||||
|
||||
Email and direct message reports will be kept confidential.
|
||||
|
||||
|
|
|
|||
70
README.rst
70
README.rst
|
|
@ -9,8 +9,8 @@ Introduction
|
|||
:target: https://discord.gg/nBQh6qu
|
||||
:alt: Discord
|
||||
|
||||
.. image:: https://travis-ci.com/adafruit/Adafruit_CircuitPython_Debouncer.svg?branch=master
|
||||
:target: https://travis-ci.com/adafruit/Adafruit_CircuitPython_Debouncer
|
||||
.. image:: https://github.com/adafruit/Adafruit_CircuitPython_Debouncer/workflows/Build%20CI/badge.svg
|
||||
:target: https://github.com/adafruit/Adafruit_CircuitPython_Debouncer/actions/
|
||||
:alt: Build Status
|
||||
|
||||
Debounces an arbitrary predicate function (typically created as a lambda) of 0 arguments.
|
||||
|
|
@ -33,14 +33,17 @@ Usage Example
|
|||
|
||||
.. code-block:: python
|
||||
|
||||
import board
|
||||
from digitalio import Pull
|
||||
from adafruit_debouncer import Debouncer
|
||||
import board
|
||||
import digitalio
|
||||
from adafruit_debouncer import Debouncer
|
||||
|
||||
switch = Debouncer(board.D12, Pull.UP)
|
||||
pin = digitalio.DigitalInOut(board.D12)
|
||||
pin.direction = digitalio.Direction.INPUT
|
||||
pin.pull = digitalio.Pull.UP
|
||||
switch = Debouncer(pin)
|
||||
|
||||
while True:
|
||||
switch.update()
|
||||
while True:
|
||||
switch.update()
|
||||
if switch.fell:
|
||||
print('Just pressed')
|
||||
if switch.rose:
|
||||
|
|
@ -58,52 +61,7 @@ Contributions are welcome! Please read our `Code of Conduct
|
|||
<https://github.com/adafruit/Adafruit_CircuitPython_debouncer/blob/master/CODE_OF_CONDUCT.md>`_
|
||||
before contributing to help this project stay welcoming.
|
||||
|
||||
Building locally
|
||||
================
|
||||
Documentation
|
||||
=============
|
||||
|
||||
Zip release files
|
||||
-----------------
|
||||
|
||||
To build this library locally you'll need to install the
|
||||
`circuitpython-build-tools <https://github.com/adafruit/circuitpython-build-tools>`_ package.
|
||||
|
||||
.. code-block:: shell
|
||||
|
||||
python3 -m venv .env
|
||||
source .env/bin/activate
|
||||
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-debouncer --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.
|
||||
For information on building library documentation, please check out `this guide <https://learn.adafruit.com/creating-and-sharing-a-circuitpython-library/sharing-our-docs-on-readthedocs#sphinx-5-1>`_.
|
||||
|
|
|
|||
|
|
@ -23,9 +23,9 @@
|
|||
`adafruit_debouncer`
|
||||
====================================================
|
||||
|
||||
Debounces an arbitrary predicate function (typically created as a lambda) of 0 arguments.
|
||||
Since a very common use is debouncing a digital input pin, the initializer accepts a pin number
|
||||
instead of a lambda.
|
||||
Debounces an arbitrary predicate function (typically created as a lambda) of 0
|
||||
arguments. Since a very common use is debouncing a digital input pin, the
|
||||
initializer accepts a DigitalInOut object instead of a lambda.
|
||||
|
||||
* Author(s): Dave Astels
|
||||
|
||||
|
|
@ -34,6 +34,16 @@ Implementation Notes
|
|||
|
||||
**Hardware:**
|
||||
|
||||
Not all hardware / CircuitPython combinations are capable of running the
|
||||
debouncer correctly for an extended length of time. If this line works
|
||||
on your microcontroller, then the debouncer should work forever:
|
||||
|
||||
``from time import monotonic_ns``
|
||||
|
||||
If it gives an ImportError, then the time values available in Python become
|
||||
less accurate over the days, and the debouncer will take longer to react to
|
||||
button presses.
|
||||
|
||||
**Software and Dependencies:**
|
||||
|
||||
* Adafruit CircuitPython firmware for the supported boards:
|
||||
|
|
@ -46,79 +56,106 @@ __version__ = "0.0.0-auto.0"
|
|||
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Debouncer.git"
|
||||
|
||||
import time
|
||||
import digitalio
|
||||
from micropython import const
|
||||
|
||||
_DEBOUNCED_STATE = 0x01
|
||||
_UNSTABLE_STATE = 0x02
|
||||
_CHANGED_STATE = 0x04
|
||||
_DEBOUNCED_STATE = const(0x01)
|
||||
_UNSTABLE_STATE = const(0x02)
|
||||
_CHANGED_STATE = const(0x04)
|
||||
|
||||
class Debouncer(object):
|
||||
# Find out whether the current CircuitPython supports time.monotonic_ns(),
|
||||
# which doesn't have the accuracy limitation.
|
||||
if hasattr(time, "monotonic_ns"):
|
||||
TICKS_PER_SEC = 1_000_000_000
|
||||
MONOTONIC_TICKS = time.monotonic_ns
|
||||
else:
|
||||
TICKS_PER_SEC = 1
|
||||
MONOTONIC_TICKS = time.monotonic
|
||||
|
||||
|
||||
class Debouncer:
|
||||
"""Debounce an input pin or an arbitrary predicate"""
|
||||
|
||||
def __init__(self, io_or_predicate, interval=0.010):
|
||||
"""Make am instance.
|
||||
:param DigitalInOut/function io_or_predicate: the pin (from board) to debounce
|
||||
:param DigitalInOut/function io_or_predicate: the DigitalIO or function to debounce
|
||||
:param int interval: bounce threshold in seconds (default is 0.010, i.e. 10 milliseconds)
|
||||
"""
|
||||
self.state = 0x00
|
||||
if isinstance(io_or_predicate, digitalio.DigitalInOut):
|
||||
if hasattr(io_or_predicate, "value"):
|
||||
self.function = lambda: io_or_predicate.value
|
||||
else:
|
||||
self.function = io_or_predicate
|
||||
if self.function():
|
||||
self._set_state(_DEBOUNCED_STATE | _UNSTABLE_STATE)
|
||||
self.previous_time = 0
|
||||
if interval is None:
|
||||
self.interval = 0.010
|
||||
else:
|
||||
self.interval = interval
|
||||
self._last_bounce_ticks = 0
|
||||
self._last_duration_ticks = 0
|
||||
self._state_changed_ticks = 0
|
||||
|
||||
# Could use the .interval setter, but pylint prefers that we explicitly
|
||||
# set the real underlying attribute:
|
||||
self._interval_ticks = interval * TICKS_PER_SEC
|
||||
|
||||
def _set_state(self, bits):
|
||||
self.state |= bits
|
||||
|
||||
|
||||
def _unset_state(self, bits):
|
||||
self.state &= ~bits
|
||||
|
||||
|
||||
def _toggle_state(self, bits):
|
||||
self.state ^= bits
|
||||
|
||||
|
||||
def _get_state(self, bits):
|
||||
return (self.state & bits) != 0
|
||||
|
||||
|
||||
def update(self):
|
||||
"""Update the debouncer state. MUST be called frequently"""
|
||||
now = time.monotonic()
|
||||
now_ticks = MONOTONIC_TICKS()
|
||||
self._unset_state(_CHANGED_STATE)
|
||||
current_state = self.function()
|
||||
if current_state != self._get_state(_UNSTABLE_STATE):
|
||||
self.previous_time = now
|
||||
self._last_bounce_ticks = now_ticks
|
||||
self._toggle_state(_UNSTABLE_STATE)
|
||||
else:
|
||||
if now - self.previous_time >= self.interval:
|
||||
if now_ticks - self._last_bounce_ticks >= self._interval_ticks:
|
||||
if current_state != self._get_state(_DEBOUNCED_STATE):
|
||||
self.previous_time = now
|
||||
self._last_bounce_ticks = now_ticks
|
||||
self._toggle_state(_DEBOUNCED_STATE)
|
||||
self._set_state(_CHANGED_STATE)
|
||||
self._last_duration_ticks = now_ticks - self._state_changed_ticks
|
||||
self._state_changed_ticks = now_ticks
|
||||
|
||||
@property
|
||||
def interval(self):
|
||||
"""The debounce delay, in seconds"""
|
||||
return self._interval_ticks / TICKS_PER_SEC
|
||||
|
||||
@interval.setter
|
||||
def interval(self, new_interval_s):
|
||||
self._interval_ticks = new_interval_s * TICKS_PER_SEC
|
||||
|
||||
@property
|
||||
def value(self):
|
||||
"""Return the current debounced value."""
|
||||
return self._get_state(_DEBOUNCED_STATE)
|
||||
|
||||
|
||||
@property
|
||||
def rose(self):
|
||||
"""Return whether the debounced value went from low to high at the most recent update."""
|
||||
return self._get_state(_DEBOUNCED_STATE) and self._get_state(_CHANGED_STATE)
|
||||
|
||||
|
||||
@property
|
||||
def fell(self):
|
||||
"""Return whether the debounced value went from high to low at the most recent update."""
|
||||
return (not self._get_state(_DEBOUNCED_STATE)) and self._get_state(_CHANGED_STATE)
|
||||
return (not self._get_state(_DEBOUNCED_STATE)) and self._get_state(
|
||||
_CHANGED_STATE
|
||||
)
|
||||
|
||||
@property
|
||||
def last_duration(self):
|
||||
"""Return the number of seconds the state was stable prior to the most recent transition."""
|
||||
return self._last_duration_ticks / TICKS_PER_SEC
|
||||
|
||||
@property
|
||||
def current_duration(self):
|
||||
"""Return the number of seconds since the most recent transition."""
|
||||
return (MONOTONIC_TICKS() - self._state_changed_ticks) / TICKS_PER_SEC
|
||||
|
|
|
|||
112
docs/conf.py
112
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,10 +11,10 @@ sys.path.insert(0, os.path.abspath('..'))
|
|||
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
|
||||
# ones.
|
||||
extensions = [
|
||||
'sphinx.ext.autodoc',
|
||||
'sphinx.ext.intersphinx',
|
||||
'sphinx.ext.napoleon',
|
||||
'sphinx.ext.todo',
|
||||
"sphinx.ext.autodoc",
|
||||
"sphinx.ext.intersphinx",
|
||||
"sphinx.ext.napoleon",
|
||||
"sphinx.ext.todo",
|
||||
]
|
||||
|
||||
# TODO: Please Read!
|
||||
|
|
@ -23,29 +24,32 @@ extensions = [
|
|||
autodoc_mock_imports = ["digitalio"]
|
||||
|
||||
|
||||
intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)}
|
||||
intersphinx_mapping = {
|
||||
"python": ("https://docs.python.org/3.4", 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 Debouncer Library'
|
||||
copyright = u'2019 Dave Astels'
|
||||
author = u'Dave Astels'
|
||||
project = "Adafruit Debouncer Library"
|
||||
copyright = "2019 Dave Astels"
|
||||
author = "Dave Astels"
|
||||
|
||||
# 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.
|
||||
|
|
@ -57,7 +61,7 @@ language = None
|
|||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
# This patterns also effect to html_static_path and html_extra_path
|
||||
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md']
|
||||
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"]
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all
|
||||
# documents.
|
||||
|
|
@ -69,7 +73,7 @@ default_role = "any"
|
|||
add_function_parentheses = True
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = 'sphinx'
|
||||
pygments_style = "sphinx"
|
||||
|
||||
# If true, `todo` and `todoList` produce output, else they produce nothing.
|
||||
todo_include_todos = False
|
||||
|
|
@ -84,59 +88,62 @@ napoleon_numpy_docstring = False
|
|||
# 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 = 'AdafruitDebouncerLibrarydoc'
|
||||
htmlhelp_basename = "AdafruitDebouncerLibrarydoc"
|
||||
|
||||
# -- 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, 'AdafruitdebouncerLibrary.tex', u'Adafruitdebouncer Library Documentation',
|
||||
author, 'manual'),
|
||||
(
|
||||
master_doc,
|
||||
"AdafruitdebouncerLibrary.tex",
|
||||
"Adafruitdebouncer Library Documentation",
|
||||
author,
|
||||
"manual",
|
||||
),
|
||||
]
|
||||
|
||||
# -- Options for manual page output ---------------------------------------
|
||||
|
|
@ -144,8 +151,13 @@ latex_documents = [
|
|||
# One entry per manual page. List of tuples
|
||||
# (source start file, name, description, authors, manual section).
|
||||
man_pages = [
|
||||
(master_doc, 'Adafruitdebouncerlibrary', u'Adafruit debouncer Library Documentation',
|
||||
[author], 1)
|
||||
(
|
||||
master_doc,
|
||||
"Adafruitdebouncerlibrary",
|
||||
"Adafruit debouncer Library Documentation",
|
||||
[author],
|
||||
1,
|
||||
)
|
||||
]
|
||||
|
||||
# -- Options for Texinfo output -------------------------------------------
|
||||
|
|
@ -154,7 +166,13 @@ man_pages = [
|
|||
# (source start file, target name, title, author,
|
||||
# dir menu entry, description, category)
|
||||
texinfo_documents = [
|
||||
(master_doc, 'AdafruitdebouncerLibrary', u'Adafruit debouncer Library Documentation',
|
||||
author, 'AdafruitdebouncerLibrary', 'One line description of project.',
|
||||
'Miscellaneous'),
|
||||
(
|
||||
master_doc,
|
||||
"AdafruitdebouncerLibrary",
|
||||
"Adafruit debouncer Library Documentation",
|
||||
author,
|
||||
"AdafruitdebouncerLibrary",
|
||||
"One line description of project.",
|
||||
"Miscellaneous",
|
||||
),
|
||||
]
|
||||
|
|
|
|||
|
|
@ -34,11 +34,13 @@ from adafruit_debouncer import Debouncer
|
|||
|
||||
ss = crickit.seesaw
|
||||
|
||||
|
||||
def make_crikit_signal_debouncer(pin):
|
||||
"""Return a lambda to read the specified pin"""
|
||||
ss.pin_mode(pin, ss.INPUT_PULLUP)
|
||||
return Debouncer(lambda: ss.digital_read(pin))
|
||||
|
||||
|
||||
# Two buttons are pullups, connect to ground to activate
|
||||
clock = make_crikit_signal_debouncer(crickit.SIGNAL1)
|
||||
signal_2 = make_crikit_signal_debouncer(crickit.SIGNAL2)
|
||||
|
|
@ -54,6 +56,9 @@ while True:
|
|||
signal_5.update()
|
||||
|
||||
if clock.fell:
|
||||
print('%u %u %u %u' % (signal_2.value, signal_3.value, signal_4.value, signal_5.value))
|
||||
print(
|
||||
"%u %u %u %u"
|
||||
% (signal_2.value, signal_3.value, signal_4.value, signal_5.value)
|
||||
)
|
||||
|
||||
time.sleep(0.1)
|
||||
|
|
|
|||
|
|
@ -36,10 +36,10 @@ switch = Debouncer(pin)
|
|||
while True:
|
||||
switch.update()
|
||||
if switch.fell:
|
||||
print('Just pressed')
|
||||
print("Just pressed")
|
||||
if switch.rose:
|
||||
print('Just released')
|
||||
print("Just released")
|
||||
if switch.value:
|
||||
print('not pressed')
|
||||
print("not pressed")
|
||||
else:
|
||||
print('pressed')
|
||||
print("pressed")
|
||||
|
|
|
|||
21
examples/debouncer_timing_test.py
Normal file
21
examples/debouncer_timing_test.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import time
|
||||
import board
|
||||
from digitalio import DigitalInOut, Direction, Pull
|
||||
from adafruit_debouncer import Debouncer
|
||||
|
||||
button = DigitalInOut(board.D4)
|
||||
button.direction = Direction.INPUT
|
||||
button.pull = Pull.UP
|
||||
switch = Debouncer(button)
|
||||
|
||||
while True:
|
||||
switch.update()
|
||||
if switch.fell:
|
||||
print("pressed")
|
||||
print("was released for ", switch.last_duration)
|
||||
elif switch.rose:
|
||||
print("released")
|
||||
print("was pressed for ", switch.last_duration)
|
||||
else:
|
||||
print("Stable for ", switch.current_duration)
|
||||
time.sleep(0.1)
|
||||
60
setup.py
Normal file
60
setup.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
|
||||
# SPDX-FileCopyrightText: Copyright (c) 2020 Dave Astels for Adafruit Industries
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""A setuptools based setup module.
|
||||
|
||||
See:
|
||||
https://packaging.python.org/en/latest/distributing.html
|
||||
https://github.com/pypa/sampleproject
|
||||
"""
|
||||
|
||||
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-debouncer",
|
||||
use_scm_version=True,
|
||||
setup_requires=["setuptools_scm"],
|
||||
description="CircuitPython pin or arbitrary predicate debouncer.",
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/x-rst",
|
||||
# The project's main homepage.
|
||||
url="https://github.com/adafruit/Adafruit_CircuitPython_Debouncer",
|
||||
# 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 blinka circuitpython micropython debouncer debounce",
|
||||
# You can just specify the packages manually here if your project is
|
||||
# simple. Or you can use find_packages().
|
||||
# TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER,
|
||||
# CHANGE `py_modules=['...']` TO `packages=['...']`
|
||||
py_modules=["adafruit_debouncer"],
|
||||
)
|
||||
151
tests/tests.py
Normal file
151
tests/tests.py
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
"""
|
||||
How to use this test file:
|
||||
|
||||
Copy adafruit_debouncer's dependencies to lib/ on your circuitpython device.
|
||||
Copy adafruit_debouncer.py to / on the device
|
||||
Copy this tests.py file to /main.py on the device
|
||||
Connect to the serial terminal (e.g. sudo screen /dev/ttyACM0 115200)
|
||||
Press Ctrl-D, if needed to start the tests running
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
import adafruit_debouncer
|
||||
|
||||
|
||||
def _true():
|
||||
return True
|
||||
|
||||
|
||||
def _false():
|
||||
return False
|
||||
|
||||
|
||||
def assertEqual(a, b):
|
||||
assert a == b, "Want %r, got %r" % (a, b)
|
||||
|
||||
|
||||
def test_back_and_forth():
|
||||
# Start false
|
||||
db = adafruit_debouncer.Debouncer(_false)
|
||||
assertEqual(db.value, False)
|
||||
|
||||
# Set the raw state to true, update, and make sure the debounced
|
||||
# state has not changed yet:
|
||||
db.function = _true
|
||||
db.update()
|
||||
assertEqual(db.value, False)
|
||||
assert not db.last_duration, "There was no previous interval??"
|
||||
|
||||
# Sleep longer than the debounce interval, so state can change:
|
||||
time.sleep(0.02)
|
||||
db.update()
|
||||
assert db.last_duration # is actually duration between powerup and now
|
||||
assertEqual(db.value, True)
|
||||
assertEqual(db.rose, True)
|
||||
assertEqual(db.fell, False)
|
||||
# Duration since last change has only been long enough to run these
|
||||
# asserts, which should be well under 1/10 second
|
||||
assert db.current_duration < 0.1, "Unit error? %d" % db.current_duration
|
||||
|
||||
# Set raw state back to false, make sure it's not instantly reflected,
|
||||
# then wait and make sure it IS reflected after the interval has passed.
|
||||
db.function = _false
|
||||
db.update()
|
||||
assertEqual(db.value, True)
|
||||
assertEqual(db.fell, False)
|
||||
assertEqual(db.rose, False)
|
||||
time.sleep(0.02)
|
||||
assert 0.019 < db.current_duration <= 1, (
|
||||
"Unit error? sleep .02 -> duration %d" % db.current_duration
|
||||
)
|
||||
db.update()
|
||||
assertEqual(db.value, False)
|
||||
assertEqual(db.rose, False)
|
||||
assertEqual(db.fell, True)
|
||||
|
||||
assert 0 < db.current_duration <= 0.1, (
|
||||
"Unit error? time to run asserts %d" % db.current_duration
|
||||
)
|
||||
assert 0 < db.last_duration < 0.1, (
|
||||
"Unit error? Last dur should be ~.02, is %d" % db.last_duration
|
||||
)
|
||||
|
||||
|
||||
def test_interval_is_the_same():
|
||||
db = adafruit_debouncer.Debouncer(_false, interval=0.25)
|
||||
assertEqual(db.value, False)
|
||||
db.update()
|
||||
db.function = _true
|
||||
db.update()
|
||||
|
||||
time.sleep(0.1) # longer than default interval
|
||||
db.update()
|
||||
assertEqual(db.value, False)
|
||||
|
||||
time.sleep(0.2) # 0.1 + 0.2 > 0.25
|
||||
db.update()
|
||||
assertEqual(db.value, True)
|
||||
assertEqual(db.rose, True)
|
||||
assertEqual(db.interval, 0.25)
|
||||
|
||||
|
||||
def test_setting_interval():
|
||||
# Check that setting the interval does change the time the debouncer waits
|
||||
db = adafruit_debouncer.Debouncer(_false, interval=0.01)
|
||||
db.update()
|
||||
|
||||
# set the interval to a longer time, sleep for a time between
|
||||
# the two interval settings, and assert that the value hasn't changed.
|
||||
|
||||
db.function = _true
|
||||
db.interval = 0.2
|
||||
db.update()
|
||||
assert db.interval - 0.2 < 0.00001, "interval is not consistent"
|
||||
time.sleep(0.11)
|
||||
db.update()
|
||||
|
||||
assertEqual(db.value, False)
|
||||
assertEqual(db.rose, False)
|
||||
assertEqual(db.fell, False)
|
||||
|
||||
# and then once the whole time has passed make sure it did change
|
||||
time.sleep(0.11)
|
||||
db.update()
|
||||
assertEqual(db.value, True)
|
||||
assertEqual(db.rose, True)
|
||||
assertEqual(db.fell, False)
|
||||
|
||||
|
||||
def run():
|
||||
passes = 0
|
||||
fails = 0
|
||||
for name, test in locals().items():
|
||||
if name.startswith("test_") and callable(test):
|
||||
try:
|
||||
print()
|
||||
print(name)
|
||||
test()
|
||||
print("PASS")
|
||||
passes += 1
|
||||
except Exception as e:
|
||||
sys.print_exception(e)
|
||||
print("FAIL")
|
||||
fails += 1
|
||||
|
||||
print(passes, "passed,", fails, "failed")
|
||||
if passes and not fails:
|
||||
print(
|
||||
r"""
|
||||
________
|
||||
< YATTA! >
|
||||
--------
|
||||
\ ^__^
|
||||
\ (oo)\_______
|
||||
(__)\ )\/\
|
||||
||----w |
|
||||
|| ||"""
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
Loading…
Reference in a new issue