From c78be5491bcb027581a18d3ae397263dce20b3f9 Mon Sep 17 00:00:00 2001 From: brentru Date: Wed, 29 May 2019 16:46:54 -0400 Subject: [PATCH 01/47] add initial cookiecutter --- .gitignore | 12 + .pylintrc | 433 ++++++++++++++++++++++++++++++++++ .readthedocs.yml | 3 + .travis.yml | 48 ++++ CODE_OF_CONDUCT.md | 127 ++++++++++ LICENSE | 21 ++ README.md | 1 - README.rst | 117 +++++++++ adafruit_rgbled.py | 53 +++++ docs/_static/favicon.ico | Bin 0 -> 4414 bytes docs/api.rst | 8 + docs/conf.py | 160 +++++++++++++ docs/examples.rst | 8 + docs/index.rst | 51 ++++ examples/rgbled_simpletest.py | 0 requirements.txt | 1 + setup.py | 63 +++++ 17 files changed, 1105 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 .pylintrc create mode 100644 .readthedocs.yml create mode 100644 .travis.yml create mode 100644 CODE_OF_CONDUCT.md create mode 100644 LICENSE delete mode 100644 README.md create mode 100644 README.rst create mode 100644 adafruit_rgbled.py create mode 100644 docs/_static/favicon.ico create mode 100644 docs/api.rst create mode 100644 docs/conf.py create mode 100644 docs/examples.rst create mode 100644 docs/index.rst create mode 100644 examples/rgbled_simpletest.py create mode 100644 requirements.txt create mode 100644 setup.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..55f127b --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +*.mpy +.idea +__pycache__ +_build +*.pyc +.env +build* +bundles +*.DS_Store +.eggs +dist +**/*.egg-info \ No newline at end of file diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..039eaec --- /dev/null +++ b/.pylintrc @@ -0,0 +1,433 @@ +[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 +notes=FIXME,XXX + + +[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=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. +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,w,i,j,k,n,x,y,z,ex,ok,Run,_ + +# Include a hint for the correct naming format with invalid-name +include-naming-hint=no + +# 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=1 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "Exception" +overgeneral-exceptions=Exception diff --git a/.readthedocs.yml b/.readthedocs.yml new file mode 100644 index 0000000..f4243ad --- /dev/null +++ b/.readthedocs.yml @@ -0,0 +1,3 @@ +python: + version: 3 +requirements_file: requirements.txt diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..c3f40dc --- /dev/null +++ b/.travis.yml @@ -0,0 +1,48 @@ +# 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 + +# TODO: if deployment to PyPi is desired, change 'DEPLOY_PYPI' to "true", +# or remove the env block entirely and remove the condition in the +# deploy block. +env: + - DEPLOY_PYPI="false" + +deploy: + - provider: releases + api_key: "$GITHUB_TOKEN" + file_glob: true + file: "$TRAVIS_BUILD_DIR/bundles/*" + skip_cleanup: true + overwrite: true + on: + tags: true + # TODO: Use 'travis encrypt --com -r adafruit/' to generate + # the encrypted password for adafruit-travis. Paste result below. + - provider: pypi + user: adafruit-travis + password: + secure: #-- PASTE ENCRYPTED PASSWORD HERE --# + on: + tags: true + condition: $DEPLOY_PYPI = "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_rgbled.py + - ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace examples/*.py) + - circuitpython-build-bundles --filename_prefix adafruit-circuitpython-rgbled --library_location . + - cd docs && sphinx-build -E -W -b html . _build/html && cd .. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..7ca3a1d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,127 @@ +# Adafruit Community Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +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 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 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 +* 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 + +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 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 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 community member for other behaviors that they deem +inappropriate, threatening, offensive, or harmful. + +## Moderation + +Instances of behaviors that violate the Adafruit Community Code of Conduct +may be reported by any member of the community. Community members are +encouraged to report these situations, including situations they witness +involving other community members. + +You may report in the following ways: + +In any situation, you may send an email to . + +On the Adafruit Discord, you may send an open message from any channel +to all Community Helpers 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, or +@Andon#8175. + +Email and direct message reports will be kept confidential. + +In situations on Discord where the issue is particularly egregious, possibly +illegal, requires immediate action, or violates the Discord terms of service, +you should also report the message directly to Discord. + +These are the steps for upholding our 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 +, +and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). + +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. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d4fbf1d --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Brent Rubell 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. diff --git a/README.md b/README.md deleted file mode 100644 index 05fd984..0000000 --- a/README.md +++ /dev/null @@ -1 +0,0 @@ -# CircuitPython_RGBLED diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..4b0ff67 --- /dev/null +++ b/README.rst @@ -0,0 +1,117 @@ +Introduction +============ + +.. image:: https://readthedocs.org/projects/adafruit-circuitpython-rgbled/badge/?version=latest + :target: https://circuitpython.readthedocs.io/projects/rgbled/en/latest/ + :alt: Documentation Status + +.. image:: https://img.shields.io/discord/327254708534116352.svg + :target: https://discord.gg/nBQh6qu + :alt: Discord + +.. image:: https://travis-ci.com/adafruit/Adafruit_CircuitPython_RGBLED.svg?branch=master + :target: https://travis-ci.com/adafruit/Adafruit_CircuitPython_RGBLED + :alt: Build Status + +CircuitPython driver for RGB LEDs + + +Dependencies +============= +This driver depends on: + +* `Adafruit CircuitPython `_ + +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 +-------------------- +.. note:: This library is not available on PyPI yet. Install documentation is included + as a standard element. Stay tuned for PyPI availability! +.. todo:: Remove the above note if PyPI version is/will be available at time of release. + If the library is not planned for PyPI, remove the entire 'Installing from PyPI' section. +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-rgbled + +To install system-wide (this may be required in some cases): + +.. code-block:: shell + + sudo pip3 install adafruit-circuitpython-rgbled + +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-rgbled + +Usage Example +============= + +.. todo:: Add a quick, simple example. It and other examples should live in the examples folder and be included in docs/examples.rst. + +Contributing +============ + +Contributions are welcome! Please read our `Code of Conduct +`_ +before contributing to help this project stay welcoming. + +Building locally +================ + +Zip release files +----------------- + +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-rgbled --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. diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py new file mode 100644 index 0000000..f364afe --- /dev/null +++ b/adafruit_rgbled.py @@ -0,0 +1,53 @@ +# The MIT License (MIT) +# +# Copyright (c) 2019 Brent Rubell 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. +""" +`adafruit_rgbled` +================================================================================ + +CircuitPython driver for RGB LEDs + + +* Author(s): Brent Rubell + +Implementation Notes +-------------------- + +**Hardware:** + +.. todo:: Add links to any specific hardware product page(s), or category page(s). Use unordered list & hyperlink rST + inline format: "* `Link Text `_" + +**Software and Dependencies:** + +* Adafruit CircuitPython firmware for the supported boards: + https://github.com/adafruit/circuitpython/releases + +.. todo:: Uncomment or remove the Bus Device and/or the Register library dependencies based on the library's use of either. + +# * Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice +# * Adafruit's Register library: https://github.com/adafruit/Adafruit_CircuitPython_Register +""" + +# imports + +__version__ = "0.0.0-auto.0" +__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGBLED.git" 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 + CircuitPython Reference Documentation + CircuitPython Support Forum + Discord Chat + Adafruit Learning System + Adafruit Blog + Adafruit Store + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/examples/rgbled_simpletest.py b/examples/rgbled_simpletest.py new file mode 100644 index 0000000..e69de29 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..edf9394 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +Adafruit-Blinka diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..5276bfa --- /dev/null +++ b/setup.py @@ -0,0 +1,63 @@ +"""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-rgbled', + + use_scm_version=True, + setup_requires=['setuptools_scm'], + + description='CircuitPython driver for RGB LEDs', + long_description=long_description, + long_description_content_type='text/x-rst', + + # The project's main homepage. + url='https://github.com/adafruit/Adafruit_CircuitPython_RGBLED', + + # 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 rgbled rgb, led, driver, pwm', + + # 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_rgbled'], +) From 5d77fb8536771eaca851385ff6c88ca6febf4322 Mon Sep 17 00:00:00 2001 From: brentru Date: Wed, 29 May 2019 16:51:33 -0400 Subject: [PATCH 02/47] continue cookiecutting --- README.rst | 10 +++------- adafruit_rgbled.py | 10 ---------- docs/index.rst | 6 ------ 3 files changed, 3 insertions(+), 23 deletions(-) diff --git a/README.rst b/README.rst index 4b0ff67..93251c0 100644 --- a/README.rst +++ b/README.rst @@ -1,5 +1,5 @@ -Introduction -============ +CircuitPython_RGBLED +==================== .. image:: https://readthedocs.org/projects/adafruit-circuitpython-rgbled/badge/?version=latest :target: https://circuitpython.readthedocs.io/projects/rgbled/en/latest/ @@ -13,7 +13,7 @@ Introduction :target: https://travis-ci.com/adafruit/Adafruit_CircuitPython_RGBLED :alt: Build Status -CircuitPython driver for RGB LEDs +CircuitPython driver for RGB LEDs. Dependencies @@ -28,10 +28,6 @@ This is easily achieved by downloading Installing from PyPI -------------------- -.. note:: This library is not available on PyPI yet. Install documentation is included - as a standard element. Stay tuned for PyPI availability! -.. todo:: Remove the above note if PyPI version is/will be available at time of release. - If the library is not planned for PyPI, remove the entire 'Installing from PyPI' section. On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from PyPI `_. To install for current user: diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index f364afe..b182515 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -31,20 +31,10 @@ Implementation Notes -------------------- -**Hardware:** - -.. todo:: Add links to any specific hardware product page(s), or category page(s). Use unordered list & hyperlink rST - inline format: "* `Link Text `_" - **Software and Dependencies:** * Adafruit CircuitPython firmware for the supported boards: https://github.com/adafruit/circuitpython/releases - -.. todo:: Uncomment or remove the Bus Device and/or the Register library dependencies based on the library's use of either. - -# * Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice -# * Adafruit's Register library: https://github.com/adafruit/Adafruit_CircuitPython_Register """ # imports diff --git a/docs/index.rst b/docs/index.rst index e4a7bda..1435e6d 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -23,15 +23,9 @@ Table of Contents .. toctree:: :caption: Tutorials -.. todo:: Add any Learn guide links here. If there are none, then simply delete this todo and leave - the toctree above for use later. - .. toctree:: :caption: Related Products -.. todo:: Add any product links here. If there are none, then simply delete this todo and leave - the toctree above for use later. - .. toctree:: :caption: Other Links From 689ca0462db47293ac04bbaba54029a233af8364 Mon Sep 17 00:00:00 2001 From: brentru Date: Wed, 29 May 2019 17:05:43 -0400 Subject: [PATCH 03/47] adding init/deinit/brightness methods --- adafruit_rgbled.py | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index b182515..6e36273 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -36,8 +36,34 @@ * Adafruit CircuitPython firmware for the supported boards: https://github.com/adafruit/circuitpython/releases """ - -# imports +import math +from board import * +import pulseio __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGBLED.git" + +class RGBLED: + """ + RGB LED Driver Class. + """ + def init(self, red_pin, green_pin, blue_pin, brightness=1.0): + """Initializes a RGB LED. + :param int red_pin: Red Anode Pin. + :param int green_pin: Green Anode Pin. + :param int blue_pin: Blue Anode Pin. + """ + self._red_led = pulseio.PWMOut(red_pin, variable_frequency=True) + self._green_led = pulseio.PWMOut(green_pin, variable_frequency=True) + self._blue_led = pulseio.PWMOut(blue_pin, variable_frequency=True) + self.brightness = brightness + + def deinit(self): + """Turn the LEDs off, deinit pwmout and release hardware resources. + """ + self._red_led.duty_cycle = 0 + self._green_led.duty_cycle = 0 + self._blue_led.duty_cycle = 0 + self._red_led.deinit() + self._blue_led.deinit() + self._green_led.deinit() \ No newline at end of file From 00d7911a3aa78d266a8e14cd2e29ec061b25d5dd Mon Sep 17 00:00:00 2001 From: brentru Date: Wed, 29 May 2019 18:08:59 -0400 Subject: [PATCH 04/47] add color setter, duty cycle method --- adafruit_rgbled.py | 50 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 6e36273..6d2c419 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -47,7 +47,7 @@ class RGBLED: """ RGB LED Driver Class. """ - def init(self, red_pin, green_pin, blue_pin, brightness=1.0): + def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0): """Initializes a RGB LED. :param int red_pin: Red Anode Pin. :param int green_pin: Green Anode Pin. @@ -56,14 +56,48 @@ def init(self, red_pin, green_pin, blue_pin, brightness=1.0): self._red_led = pulseio.PWMOut(red_pin, variable_frequency=True) self._green_led = pulseio.PWMOut(green_pin, variable_frequency=True) self._blue_led = pulseio.PWMOut(blue_pin, variable_frequency=True) - self.brightness = brightness + self._rgb_led_pins = [self._red_led, self._blue_led, self._green_led] + self._brightness = brightness + self._current_color = 'Off' def deinit(self): """Turn the LEDs off, deinit pwmout and release hardware resources. """ - self._red_led.duty_cycle = 0 - self._green_led.duty_cycle = 0 - self._blue_led.duty_cycle = 0 - self._red_led.deinit() - self._blue_led.deinit() - self._green_led.deinit() \ No newline at end of file + for pin in pins: + pin.duty_cycle = 0 + pin.deinit() + self._current_color = None + + @property + def brightness(self): + """Returns the brightness of the RGB LED. + """ + return self._brightness + + @property + def color(self): + """Returns the RGB LED's current color. + """ + return self._current_color + + @color.setter + def color(self, value): + """Sets the RGB LED to a desired color. + :param type value: RGB LED desired value - can be a tuple, 24-bit integer, + or a hex value. + """ + print('Setting to: ', value) + if isinstance(value, int): + if value>>24: + raise ValueError("only bits 0->23 valid for integer input") + for i in range(0,3): + color = self._set_duty_cycle(value[i]) + print(color) + self._rgb_led_pins[i].duty_cycle=color + print(self._rgb_led_pins[i].duty_cycle) + + def _set_duty_cycle(self, percent): + """Converts a given percent value into a 16-bit + integer, duty_cycle. + """ + return int(percent / 100.0 * 65535.0) \ No newline at end of file From d1ecb9469d2825825903cd8a39d38cb314cce75b Mon Sep 17 00:00:00 2001 From: brentru Date: Wed, 29 May 2019 18:14:06 -0400 Subject: [PATCH 05/47] working RGB tuples --- adafruit_rgbled.py | 1 - 1 file changed, 1 deletion(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 6d2c419..377897c 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -94,7 +94,6 @@ def color(self, value): color = self._set_duty_cycle(value[i]) print(color) self._rgb_led_pins[i].duty_cycle=color - print(self._rgb_led_pins[i].duty_cycle) def _set_duty_cycle(self, percent): """Converts a given percent value into a 16-bit From 332a5e0bc1d8adeaea12b28b9615e5f90be6451b Mon Sep 17 00:00:00 2001 From: brentru Date: Wed, 29 May 2019 18:18:13 -0400 Subject: [PATCH 06/47] add explicit isinstance check for a tuple --- adafruit_rgbled.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 377897c..824ef50 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -87,13 +87,13 @@ def color(self, value): or a hex value. """ print('Setting to: ', value) - if isinstance(value, int): + if isinstance(value, tuple): + for i in range(0,3): + color = self._set_duty_cycle(value[i]) + self._rgb_led_pins[i].duty_cycle=color + elif isinstance(value, int): if value>>24: raise ValueError("only bits 0->23 valid for integer input") - for i in range(0,3): - color = self._set_duty_cycle(value[i]) - print(color) - self._rgb_led_pins[i].duty_cycle=color def _set_duty_cycle(self, percent): """Converts a given percent value into a 16-bit From 138e28b74c4db2f4efdf863cbe61717ca46a450b Mon Sep 17 00:00:00 2001 From: brentru Date: Wed, 29 May 2019 18:28:20 -0400 Subject: [PATCH 07/47] adding a getter/setter for PWM frequency --- adafruit_rgbled.py | 27 +++++++++++++++++++++++++-- code.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100755 code.py diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 824ef50..e4eeac9 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -47,11 +47,13 @@ class RGBLED: """ RGB LED Driver Class. """ - def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0): + def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0, frequency = 0): """Initializes a RGB LED. :param int red_pin: Red Anode Pin. :param int green_pin: Green Anode Pin. :param int blue_pin: Blue Anode Pin. + :param float brightness: Optional RGB LED brightness. + :param int frequency: 32 bit PWM frequency value, in Hz. """ self._red_led = pulseio.PWMOut(red_pin, variable_frequency=True) self._green_led = pulseio.PWMOut(green_pin, variable_frequency=True) @@ -68,6 +70,19 @@ def deinit(self): pin.deinit() self._current_color = None + @property + def frequency(self): + """Returns the frequency of the RGB LED. + """ + return self.frequency + + @frequency.setter + def frequency(self, frequency_val): + """Sets the RGB LED's PWM frequency. + :param int frequency: 32 bit frequency value, in Hz. + """ + self.frequency = frequency_val + @property def brightness(self): """Returns the brightness of the RGB LED. @@ -86,7 +101,7 @@ def color(self, value): :param type value: RGB LED desired value - can be a tuple, 24-bit integer, or a hex value. """ - print('Setting to: ', value) + print('Setting to ', value) if isinstance(value, tuple): for i in range(0,3): color = self._set_duty_cycle(value[i]) @@ -94,6 +109,14 @@ def color(self, value): elif isinstance(value, int): if value>>24: raise ValueError("only bits 0->23 valid for integer input") + r = value >> 16 + g = (value >> 8) & 0xff + b = value & 0xff + rgb = (r, g, b) + for i in range(0,3): + color = self._set_duty_cycle(rgb[i]) + print(color) + self._rgb_led_pins[i].duty_cycle=color def _set_duty_cycle(self, percent): """Converts a given percent value into a 16-bit diff --git a/code.py b/code.py new file mode 100755 index 0000000..d1cb87d --- /dev/null +++ b/code.py @@ -0,0 +1,29 @@ +import time +import board +import adafruit_rgbled + +# color types +red_tuple = (100, 0, 0) +green_tuple = (0, 100, 0) +blue_tuple = (0, 0, 100) + +# hex types +red_hex = 0x100000 + +# TODO: integer types + +led = adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7) +print('RGB LED Brightness: ', led.brightness) + +color = led.color +print(color) + + +led.color = red_tuple +time.sleep(1) +led.color = green_tuple +time.sleep(1) +led.color = blue_tuple +time.sleep(1) +led.color = red_hex +time.sleep(1) \ No newline at end of file From 7a3a87c2fb797ef7f9d3b6da6d05891af8a1d646 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 11:35:51 -0400 Subject: [PATCH 08/47] change current color init. value to a valid tuple --- adafruit_rgbled.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index e4eeac9..93c87e4 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -60,8 +60,8 @@ def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0, frequency = 0): self._blue_led = pulseio.PWMOut(blue_pin, variable_frequency=True) self._rgb_led_pins = [self._red_led, self._blue_led, self._green_led] self._brightness = brightness - self._current_color = 'Off' - + self._current_color = (0, 0, 0) + def deinit(self): """Turn the LEDs off, deinit pwmout and release hardware resources. """ @@ -98,8 +98,7 @@ def color(self): @color.setter def color(self, value): """Sets the RGB LED to a desired color. - :param type value: RGB LED desired value - can be a tuple, 24-bit integer, - or a hex value. + :param type value: RGB LED desired value - can be a tuple or a 24-bit integer. """ print('Setting to ', value) if isinstance(value, tuple): @@ -117,6 +116,8 @@ def color(self, value): color = self._set_duty_cycle(rgb[i]) print(color) self._rgb_led_pins[i].duty_cycle=color + else: + raise ValueError('Color must be a tuple or 24-bit integer value.') def _set_duty_cycle(self, percent): """Converts a given percent value into a 16-bit From fadf4369f472eef0165bc250530e618e604ac69f Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 11:45:01 -0400 Subject: [PATCH 09/47] start playing with common anode and inverting PWM --- adafruit_rgbled.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 93c87e4..8c7d762 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -61,6 +61,7 @@ def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0, frequency = 0): self._rgb_led_pins = [self._red_led, self._blue_led, self._green_led] self._brightness = brightness self._current_color = (0, 0, 0) + self.color = self._current_color def deinit(self): """Turn the LEDs off, deinit pwmout and release hardware resources. @@ -98,7 +99,8 @@ def color(self): @color.setter def color(self, value): """Sets the RGB LED to a desired color. - :param type value: RGB LED desired value - can be a tuple or a 24-bit integer. + :param type value: RGB LED desired value - can be a tuple, 24-bit integer, + """ print('Setting to ', value) if isinstance(value, tuple): @@ -123,4 +125,11 @@ def _set_duty_cycle(self, percent): """Converts a given percent value into a 16-bit integer, duty_cycle. """ - return int(percent / 100.0 * 65535.0) \ No newline at end of file + data = int(percent / 100.0 * 65535.0) + data -= 65535 + print('Disp:', data) + if data < 0: + data = abs(data) + print('Disp2: ', data) + return data + # return int(percent / 100.0 * 65535.0) \ No newline at end of file From 0219288950421f6d3c6888471b5e2487f3779b1a Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 11:59:21 -0400 Subject: [PATCH 10/47] add inverted pwm toggle kwarg --- adafruit_rgbled.py | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 8c7d762..8de752a 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -47,7 +47,7 @@ class RGBLED: """ RGB LED Driver Class. """ - def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0, frequency = 0): + def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0, frequency = 500, invert_pwm=False): """Initializes a RGB LED. :param int red_pin: Red Anode Pin. :param int green_pin: Green Anode Pin. @@ -55,11 +55,12 @@ def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0, frequency = 0): :param float brightness: Optional RGB LED brightness. :param int frequency: 32 bit PWM frequency value, in Hz. """ - self._red_led = pulseio.PWMOut(red_pin, variable_frequency=True) - self._green_led = pulseio.PWMOut(green_pin, variable_frequency=True) - self._blue_led = pulseio.PWMOut(blue_pin, variable_frequency=True) - self._rgb_led_pins = [self._red_led, self._blue_led, self._green_led] + self._red_led = pulseio.PWMOut(red_pin, frequency = frequency) + self._green_led = pulseio.PWMOut(green_pin, frequency = frequency) + self._blue_led = pulseio.PWMOut(blue_pin, frequency = frequency) + self._rgb_led_pins = [self._red_led, self._green_led, self._blue_led] self._brightness = brightness + self._invert_pwm = invert_pwm self._current_color = (0, 0, 0) self.color = self._current_color @@ -122,14 +123,12 @@ def color(self, value): raise ValueError('Color must be a tuple or 24-bit integer value.') def _set_duty_cycle(self, percent): - """Converts a given percent value into a 16-bit - integer, duty_cycle. + """Converts a provided percentage into a 16-bit integer duty_cycle. + :param int percent: Percentage value, from 0% to 100%. """ - data = int(percent / 100.0 * 65535.0) - data -= 65535 - print('Disp:', data) - if data < 0: - data = abs(data) - print('Disp2: ', data) - return data - # return int(percent / 100.0 * 65535.0) \ No newline at end of file + if self._invert_pwm: + data = int(percent / 100.0 * 65535.0) - 65535 + if data < 0: + data = abs(data) + return data + return int(percent / 100.0 * 65535.0) \ No newline at end of file From 638cbba02d9246ff1a08420483974986b918e330 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 12:40:26 -0400 Subject: [PATCH 11/47] add 8b->16b value conversion and inversion handling for hex vals --- adafruit_rgbled.py | 41 +++++++++++++++++++++++++++++++---------- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 8de752a..6537d85 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -47,17 +47,17 @@ class RGBLED: """ RGB LED Driver Class. """ - def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0, frequency = 500, invert_pwm=False): + def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0, invert_pwm=False): """Initializes a RGB LED. :param int red_pin: Red Anode Pin. :param int green_pin: Green Anode Pin. :param int blue_pin: Blue Anode Pin. :param float brightness: Optional RGB LED brightness. - :param int frequency: 32 bit PWM frequency value, in Hz. + :param bool invert_pwm: Use inverted PWM (Common anode). """ - self._red_led = pulseio.PWMOut(red_pin, frequency = frequency) - self._green_led = pulseio.PWMOut(green_pin, frequency = frequency) - self._blue_led = pulseio.PWMOut(blue_pin, frequency = frequency) + self._red_led = pulseio.PWMOut(red_pin) + self._green_led = pulseio.PWMOut(green_pin) + self._blue_led = pulseio.PWMOut(blue_pin) self._rgb_led_pins = [self._red_led, self._green_led, self._blue_led] self._brightness = brightness self._invert_pwm = invert_pwm @@ -97,6 +97,18 @@ def color(self): """ return self._current_color + def map_range(self, x, in_min, in_max, out_min, out_max): + """ + Maps a number from one range to another. + Note: This implementation handles values < in_min differently than arduino's map function does. + :return: Returns value mapped to new range + :rtype: float + """ + mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min + if out_min <= out_max: + return max(min(mapped, out_max), out_min) + return min(max(mapped, out_max), out_min) + @color.setter def color(self, value): """Sets the RGB LED to a desired color. @@ -112,13 +124,22 @@ def color(self, value): if value>>24: raise ValueError("only bits 0->23 valid for integer input") r = value >> 16 + print(r) g = (value >> 8) & 0xff b = value & 0xff - rgb = (r, g, b) - for i in range(0,3): - color = self._set_duty_cycle(rgb[i]) - print(color) - self._rgb_led_pins[i].duty_cycle=color + print('RGB Val: ', r, g, b) + r = int(self.map_range(r, 0, 255, 0, 65535)) + g = int(self.map_range(g, 0, 255, 0, 65535)) + b = int(self.map_range(b, 0, 255, 0, 65535)) + print('post map: ', r, g, b) + if self._invert_pwm: + r -= 65535 + g -= 65535 + b -= 65535 + print('Invert: ', r, g, b) + self._rgb_led_pins[0].duty_cycle = abs(r) + self._rgb_led_pins[1].duty_cycle = abs(g) + self._rgb_led_pins[2].duty_cycle = abs(b) else: raise ValueError('Color must be a tuple or 24-bit integer value.') From d225da62a7c561d5f60bd7e533b16334b919fb4e Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 12:45:44 -0400 Subject: [PATCH 12/47] remove internal map_range in favor of simpleio map range, limit pulseio import to pwmout only --- adafruit_rgbled.py | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 6537d85..b83ebac 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -38,7 +38,8 @@ """ import math from board import * -import pulseio +from pulseio import PWMOut +from simpleio import map_range __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGBLED.git" @@ -55,9 +56,9 @@ def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0, invert_pwm=Fals :param float brightness: Optional RGB LED brightness. :param bool invert_pwm: Use inverted PWM (Common anode). """ - self._red_led = pulseio.PWMOut(red_pin) - self._green_led = pulseio.PWMOut(green_pin) - self._blue_led = pulseio.PWMOut(blue_pin) + self._red_led = PWMOut(red_pin) + self._green_led = PWMOut(green_pin) + self._blue_led = PWMOut(blue_pin) self._rgb_led_pins = [self._red_led, self._green_led, self._blue_led] self._brightness = brightness self._invert_pwm = invert_pwm @@ -97,18 +98,6 @@ def color(self): """ return self._current_color - def map_range(self, x, in_min, in_max, out_min, out_max): - """ - Maps a number from one range to another. - Note: This implementation handles values < in_min differently than arduino's map function does. - :return: Returns value mapped to new range - :rtype: float - """ - mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min - if out_min <= out_max: - return max(min(mapped, out_max), out_min) - return min(max(mapped, out_max), out_min) - @color.setter def color(self, value): """Sets the RGB LED to a desired color. @@ -124,13 +113,12 @@ def color(self, value): if value>>24: raise ValueError("only bits 0->23 valid for integer input") r = value >> 16 - print(r) g = (value >> 8) & 0xff b = value & 0xff - print('RGB Val: ', r, g, b) - r = int(self.map_range(r, 0, 255, 0, 65535)) - g = int(self.map_range(g, 0, 255, 0, 65535)) - b = int(self.map_range(b, 0, 255, 0, 65535)) + rgb = (r, g, b) + r = int(map_range(r, 0, 255, 0, 65535)) + g = int(map_range(g, 0, 255, 0, 65535)) + b = int(map_range(b, 0, 255, 0, 65535)) print('post map: ', r, g, b) if self._invert_pwm: r -= 65535 From 8a96059652b10623055e03dbe92436f52544d4c4 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 12:57:31 -0400 Subject: [PATCH 13/47] reducing line count... --- adafruit_rgbled.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index b83ebac..eeafba2 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -102,9 +102,7 @@ def color(self): def color(self, value): """Sets the RGB LED to a desired color. :param type value: RGB LED desired value - can be a tuple, 24-bit integer, - """ - print('Setting to ', value) if isinstance(value, tuple): for i in range(0,3): color = self._set_duty_cycle(value[i]) @@ -115,19 +113,21 @@ def color(self, value): r = value >> 16 g = (value >> 8) & 0xff b = value & 0xff - rgb = (r, g, b) - r = int(map_range(r, 0, 255, 0, 65535)) - g = int(map_range(g, 0, 255, 0, 65535)) - b = int(map_range(b, 0, 255, 0, 65535)) - print('post map: ', r, g, b) + rgb = [r, g, b] + print('RGB: ', rgb) + for color in range(0, 3): + print('Color: ', rgb[color]) + rgb[color] = int(map_range(rgb[color], 0, 255, 0, 65535)) + print(rgb[color]) + print(rgb) if self._invert_pwm: - r -= 65535 - g -= 65535 - b -= 65535 - print('Invert: ', r, g, b) - self._rgb_led_pins[0].duty_cycle = abs(r) - self._rgb_led_pins[1].duty_cycle = abs(g) - self._rgb_led_pins[2].duty_cycle = abs(b) + rgb[0] -= 65535 + rgb[1] -= 65535 + rgb[2] -= 65535 + print('Invert: ', rgb) + self._rgb_led_pins[0].duty_cycle = abs(rgb[0]) + self._rgb_led_pins[1].duty_cycle = abs(rgb[1]) + self._rgb_led_pins[2].duty_cycle = abs(rgb[2]) else: raise ValueError('Color must be a tuple or 24-bit integer value.') From 40f448000f35e4d4728c1d85f849f08883cd477d Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 13:07:26 -0400 Subject: [PATCH 14/47] simplify the pwm inversion to a line for all LEDs --- adafruit_rgbled.py | 40 ++++++++++++---------------------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index eeafba2..fda2903 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -25,7 +25,6 @@ CircuitPython driver for RGB LEDs - * Author(s): Brent Rubell Implementation Notes @@ -35,9 +34,9 @@ * Adafruit CircuitPython firmware for the supported boards: https://github.com/adafruit/circuitpython/releases + +* Adafruit's SimpleIO library: https://github.com/adafruit/Adafruit_CircuitPython_SimpleIO """ -import math -from board import * from pulseio import PWMOut from simpleio import map_range @@ -66,8 +65,7 @@ def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0, invert_pwm=Fals self.color = self._current_color def deinit(self): - """Turn the LEDs off, deinit pwmout and release hardware resources. - """ + """Turn the LEDs off, deinit pwmout and release hardware resources.""" for pin in pins: pin.duty_cycle = 0 pin.deinit() @@ -75,8 +73,7 @@ def deinit(self): @property def frequency(self): - """Returns the frequency of the RGB LED. - """ + """Returns the frequency of the RGB LED.""" return self.frequency @frequency.setter @@ -88,14 +85,12 @@ def frequency(self, frequency_val): @property def brightness(self): - """Returns the brightness of the RGB LED. - """ + """Returns the brightness of the RGB LED.""" return self._brightness @property def color(self): - """Returns the RGB LED's current color. - """ + """Returns the RGB LED's current color.""" return self._current_color @color.setter @@ -109,35 +104,24 @@ def color(self, value): self._rgb_led_pins[i].duty_cycle=color elif isinstance(value, int): if value>>24: - raise ValueError("only bits 0->23 valid for integer input") + raise ValueError("Only bits 0->23 valid for integer input") r = value >> 16 g = (value >> 8) & 0xff b = value & 0xff rgb = [r, g, b] - print('RGB: ', rgb) for color in range(0, 3): - print('Color: ', rgb[color]) rgb[color] = int(map_range(rgb[color], 0, 255, 0, 65535)) - print(rgb[color]) - print(rgb) - if self._invert_pwm: - rgb[0] -= 65535 - rgb[1] -= 65535 - rgb[2] -= 65535 - print('Invert: ', rgb) - self._rgb_led_pins[0].duty_cycle = abs(rgb[0]) - self._rgb_led_pins[1].duty_cycle = abs(rgb[1]) - self._rgb_led_pins[2].duty_cycle = abs(rgb[2]) + if self._invert_pwm: + rgb[color] -= 65535 + self._rgb_led_pins[color].duty_cycle = abs(rgb[color]) else: raise ValueError('Color must be a tuple or 24-bit integer value.') def _set_duty_cycle(self, percent): - """Converts a provided percentage into a 16-bit integer duty_cycle. + """Converts a percentage into a 16-bit duty_cycle integer value. :param int percent: Percentage value, from 0% to 100%. """ if self._invert_pwm: data = int(percent / 100.0 * 65535.0) - 65535 - if data < 0: - data = abs(data) - return data + return abs(data) return int(percent / 100.0 * 65535.0) \ No newline at end of file From fc36c538a28746bc49f2441610487a97672a2944 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 13:10:37 -0400 Subject: [PATCH 15/47] passing pylint --- adafruit_rgbled.py | 31 +++++-------------------------- 1 file changed, 5 insertions(+), 26 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index fda2903..01324a8 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -47,47 +47,26 @@ class RGBLED: """ RGB LED Driver Class. """ - def __init__(self, red_pin, green_pin, blue_pin, brightness=1.0, invert_pwm=False): + def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): """Initializes a RGB LED. :param int red_pin: Red Anode Pin. :param int green_pin: Green Anode Pin. :param int blue_pin: Blue Anode Pin. - :param float brightness: Optional RGB LED brightness. :param bool invert_pwm: Use inverted PWM (Common anode). """ self._red_led = PWMOut(red_pin) self._green_led = PWMOut(green_pin) self._blue_led = PWMOut(blue_pin) self._rgb_led_pins = [self._red_led, self._green_led, self._blue_led] - self._brightness = brightness self._invert_pwm = invert_pwm self._current_color = (0, 0, 0) self.color = self._current_color def deinit(self): """Turn the LEDs off, deinit pwmout and release hardware resources.""" - for pin in pins: - pin.duty_cycle = 0 + for pin in self._rgb_led_pins: pin.deinit() - self._current_color = None - @property - def frequency(self): - """Returns the frequency of the RGB LED.""" - return self.frequency - - @frequency.setter - def frequency(self, frequency_val): - """Sets the RGB LED's PWM frequency. - :param int frequency: 32 bit frequency value, in Hz. - """ - self.frequency = frequency_val - - @property - def brightness(self): - """Returns the brightness of the RGB LED.""" - return self._brightness - @property def color(self): """Returns the RGB LED's current color.""" @@ -99,9 +78,9 @@ def color(self, value): :param type value: RGB LED desired value - can be a tuple, 24-bit integer, """ if isinstance(value, tuple): - for i in range(0,3): + for i in range(0, 3): color = self._set_duty_cycle(value[i]) - self._rgb_led_pins[i].duty_cycle=color + self._rgb_led_pins[i].duty_cycle = color elif isinstance(value, int): if value>>24: raise ValueError("Only bits 0->23 valid for integer input") @@ -124,4 +103,4 @@ def _set_duty_cycle(self, percent): if self._invert_pwm: data = int(percent / 100.0 * 65535.0) - 65535 return abs(data) - return int(percent / 100.0 * 65535.0) \ No newline at end of file + return int(percent / 100.0 * 65535.0) From 72b203948874fca8a5d5556a994c49ac3ff880c8 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 13:42:23 -0400 Subject: [PATCH 16/47] add example of blinking a single-color channel rgb led --- examples/rgbled_blink.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100755 examples/rgbled_blink.py diff --git a/examples/rgbled_blink.py b/examples/rgbled_blink.py new file mode 100755 index 0000000..d94231b --- /dev/null +++ b/examples/rgbled_blink.py @@ -0,0 +1,26 @@ +# This example shows how to create a single RGB LED with a specific color channel +# order and blink it. +import time +import board +import adafruit_rgbled + +# Configure the setup +RED_LED = board.D5 # Pin the Red LED is connected to +GREEN_LED = board.D6 # Pin the Green LED is connected to +BLUE_LED = board.D7 # Pin the Blue LED is connected to +COLOR = (100, 50, 150) # color to blink +CLEAR = (0, 0, 0) # clear (or second color) +DELAY = 0.25 # blink rate in seconds + +# Create the RGB LED object +led = adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7) + +# Optionally create the RGB LED object with inverted PWM +# led = adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7, invert_pwm=True) + +# Loop forever and blink the color +while True: + led.color = COLOR + time.sleep(DELAY) + led.color = CLEAR + time.sleep(DELAY) \ No newline at end of file From af92d161da16d4ee130984f51bc5a46246fb0ff2 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 14:00:30 -0400 Subject: [PATCH 17/47] accept a 8b tuple --- adafruit_rgbled.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 01324a8..3107175 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -73,14 +73,18 @@ def color(self): return self._current_color @color.setter - def color(self, value): + def color(self, value, is_percent=False): """Sets the RGB LED to a desired color. - :param type value: RGB LED desired value - can be a tuple, 24-bit integer, + :param type value: RGB LED desired value - can be a RGB tuple or a 24-bit integer. + :param bool is_percent: Value is a tuple expressed in percentage, from 0% to 100%. """ - if isinstance(value, tuple): + if isinstance(value, tuple) and is_percent: for i in range(0, 3): color = self._set_duty_cycle(value[i]) self._rgb_led_pins[i].duty_cycle = color + elif isinstance(value, tuple): + for i in range(0, 3): + self._rgb_led_pins[i].duty_cycle = int(map_range(value[i], 0, 255, 0, 65535)) elif isinstance(value, int): if value>>24: raise ValueError("Only bits 0->23 valid for integer input") From a9ab0db8f128a45359a8bb8745b689dbdde64f30 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 14:05:04 -0400 Subject: [PATCH 18/47] handle pwm inversion for 8b tuples --- adafruit_rgbled.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 3107175..0060cd9 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -84,7 +84,10 @@ def color(self, value, is_percent=False): self._rgb_led_pins[i].duty_cycle = color elif isinstance(value, tuple): for i in range(0, 3): - self._rgb_led_pins[i].duty_cycle = int(map_range(value[i], 0, 255, 0, 65535)) + color = int(map_range(value[i], 0, 255, 0, 65535)) + if self._invert_pwm: + color -= 65535 + self._rgb_led_pins[i].duty_cycle = abs(color) elif isinstance(value, int): if value>>24: raise ValueError("Only bits 0->23 valid for integer input") From 69958b0fa435197fff6f37baef17b6f6007f8d51 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 14:55:48 -0400 Subject: [PATCH 19/47] set the current color to the value kwarg --- adafruit_rgbled.py | 1 + 1 file changed, 1 insertion(+) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 0060cd9..d1e99e9 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -78,6 +78,7 @@ def color(self, value, is_percent=False): :param type value: RGB LED desired value - can be a RGB tuple or a 24-bit integer. :param bool is_percent: Value is a tuple expressed in percentage, from 0% to 100%. """ + self._current_color = value if isinstance(value, tuple) and is_percent: for i in range(0, 3): color = self._set_duty_cycle(value[i]) From bf25a1d483de55b3fa4c9710365cbb0643b4f702 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 15:00:30 -0400 Subject: [PATCH 20/47] addin a simpletest! --- examples/rgbled_simpletest.py | 61 +++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/examples/rgbled_simpletest.py b/examples/rgbled_simpletest.py index e69de29..c7218fc 100644 --- a/examples/rgbled_simpletest.py +++ b/examples/rgbled_simpletest.py @@ -0,0 +1,61 @@ +import time +import board +import adafruit_rgbled + +# Pin the Red LED is connected to +RED_LED = board.D5 + +# Pin the Green LED is connected to +GREEN_LED = board.D6 + +# Pin the Blue LED is connected to +BLUE_LED = board.D7 + +# Create the RGB LED object +led = adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7) + +# Optionally, you can also create the RGB LED object with inverted PWM +# led = adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7, invert_pwm=True) + +def wheel(pos): + # Input a value 0 to 255 to get a color value. + # The colours are a transition r - g - b - back to r. + if pos < 0 or pos > 255: + return 0, 0, 0 + if pos < 85: + return int(255 - pos * 3), int(pos * 3), 0 + if pos < 170: + pos -= 85 + return 0, int(255 - pos * 3), int(pos * 3) + pos -= 170 + return int(pos * 3), 0, int(255 - (pos * 3)) + +def rainbow_cycle(wait): + for i in range(255): + i = (i + 1) % 256 + led.color = wheel(i) + time.sleep(wait) + +while True: + # setting RGB LED color to RGB Tuples (R, G, B) + led.color = (255, 0, 0) + time.sleep(1) + + led.color = (0, 255, 0) + time.sleep(1) + + led.color = (0, 0, 255) + time.sleep(1) + + # setting RGB LED color to 24-bit integer values + led.color = 0xFF0000 + time.sleep(1) + + led.color = 0x00FF00 + time.sleep(1) + + led.color = 0x0000FF + time.sleep(1) + + # rainbow cycle the RGB LED + rainbow_cycle(0.1) \ No newline at end of file From dc53f20a46672bc645f01b1c1d29b3bb2bcf8fb3 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 15:03:22 -0400 Subject: [PATCH 21/47] pylinting --- adafruit_rgbled.py | 4 ++-- examples/rgbled_blink.py | 2 +- examples/rgbled_simpletest.py | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index d1e99e9..d43b314 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -81,7 +81,7 @@ def color(self, value, is_percent=False): self._current_color = value if isinstance(value, tuple) and is_percent: for i in range(0, 3): - color = self._set_duty_cycle(value[i]) + color = self._convert_percent_to_duty_cycle(value[i]) self._rgb_led_pins[i].duty_cycle = color elif isinstance(value, tuple): for i in range(0, 3): @@ -104,7 +104,7 @@ def color(self, value, is_percent=False): else: raise ValueError('Color must be a tuple or 24-bit integer value.') - def _set_duty_cycle(self, percent): + def _convert_percent_to_duty_cycle(self, percent): """Converts a percentage into a 16-bit duty_cycle integer value. :param int percent: Percentage value, from 0% to 100%. """ diff --git a/examples/rgbled_blink.py b/examples/rgbled_blink.py index d94231b..0ea9b4b 100755 --- a/examples/rgbled_blink.py +++ b/examples/rgbled_blink.py @@ -23,4 +23,4 @@ led.color = COLOR time.sleep(DELAY) led.color = CLEAR - time.sleep(DELAY) \ No newline at end of file + time.sleep(DELAY) diff --git a/examples/rgbled_simpletest.py b/examples/rgbled_simpletest.py index c7218fc..04e30d4 100644 --- a/examples/rgbled_simpletest.py +++ b/examples/rgbled_simpletest.py @@ -47,7 +47,7 @@ def rainbow_cycle(wait): led.color = (0, 0, 255) time.sleep(1) - # setting RGB LED color to 24-bit integer values + # setting RGB LED color to 24-bit integer values led.color = 0xFF0000 time.sleep(1) @@ -56,6 +56,6 @@ def rainbow_cycle(wait): led.color = 0x0000FF time.sleep(1) - + # rainbow cycle the RGB LED - rainbow_cycle(0.1) \ No newline at end of file + rainbow_cycle(0.1) From e715a08c4679ed2fecc02c48825bc9445f8fa99d Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 15:23:29 -0400 Subject: [PATCH 22/47] fix examples, add correct pinout --- README.rst | 2 +- examples/rgbled_blink.py | 6 +++--- examples/rgbled_simpletest.py | 4 ++-- requirements.txt | 1 + 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/README.rst b/README.rst index 93251c0..21eec91 100644 --- a/README.rst +++ b/README.rst @@ -15,12 +15,12 @@ CircuitPython_RGBLED CircuitPython driver for RGB LEDs. - Dependencies ============= This driver depends on: * `Adafruit CircuitPython `_ +* `SimpleIO Library `_ Please ensure all dependencies are available on the CircuitPython filesystem. This is easily achieved by downloading diff --git a/examples/rgbled_blink.py b/examples/rgbled_blink.py index 0ea9b4b..27d3f9e 100755 --- a/examples/rgbled_blink.py +++ b/examples/rgbled_blink.py @@ -13,10 +13,10 @@ DELAY = 0.25 # blink rate in seconds # Create the RGB LED object -led = adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7) +led = adafruit_rgbled.RGBLED(RED_LED, GREEN_LED, BLUE_LED) -# Optionally create the RGB LED object with inverted PWM -# led = adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7, invert_pwm=True) +# Optionally, you can also create the RGB LED object with inverted PWM +# led = adafruit_rgbled.RGBLED(RED_LED, GREEN_LED, BLUE_LED, invert_pwm=True) # Loop forever and blink the color while True: diff --git a/examples/rgbled_simpletest.py b/examples/rgbled_simpletest.py index 04e30d4..f4cd4ee 100644 --- a/examples/rgbled_simpletest.py +++ b/examples/rgbled_simpletest.py @@ -12,10 +12,10 @@ BLUE_LED = board.D7 # Create the RGB LED object -led = adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7) +led = adafruit_rgbled.RGBLED(RED_LED, GREEN_LED, BLUE_LED) # Optionally, you can also create the RGB LED object with inverted PWM -# led = adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7, invert_pwm=True) +# led = adafruit_rgbled.RGBLED(RED_LED, GREEN_LED, BLUE_LED, invert_pwm=True) def wheel(pos): # Input a value 0 to 255 to get a color value. diff --git a/requirements.txt b/requirements.txt index edf9394..deb055b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,2 @@ Adafruit-Blinka +simpleio \ No newline at end of file From a2fb613134ba3a559958634fb2597b2b9888e168 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 15:27:27 -0400 Subject: [PATCH 23/47] adding examples to readme --- README.rst | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 21eec91..239963b 100644 --- a/README.rst +++ b/README.rst @@ -53,7 +53,40 @@ To install in a virtual environment in your current project: Usage Example ============= -.. todo:: Add a quick, simple example. It and other examples should live in the examples folder and be included in docs/examples.rst. +This example demonstrates the library with the single built-in NeoPixel on the +`Feather M0 Express `_ and +`Metro M0 Express `_. + +Initialize a RGB LED with three PWM-capable pins. + +.. code-block:: python + + import board + import adafruit_rgbled + + # Pin the Red LED is connected to + RED_LED = board.D5 + + # Pin the Green LED is connected to + GREEN_LED = board.D6 + + # Pin the Blue LED is connected to + BLUE_LED = board.D7 + + # Create a RGB LED object + led = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) + +Set the RGB LED's color to a RGB Tuple (Red, Green, Blue). + +.. code-block:: python + + led.color = (255, 0, 0) + +Set the RGB LED's color to a 24-bit integer (in hex syntax), 0x100000. + +.. code-block:: python + + led.color = (255, 0, 0) Contributing ============ From 72e365888526643c56d35fb891ffb7485424c614 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 17:16:15 -0400 Subject: [PATCH 24/47] remove the percentage-based pwm code --- adafruit_rgbled.py | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index d43b314..63214cf 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -73,17 +73,12 @@ def color(self): return self._current_color @color.setter - def color(self, value, is_percent=False): + def color(self, value): """Sets the RGB LED to a desired color. :param type value: RGB LED desired value - can be a RGB tuple or a 24-bit integer. - :param bool is_percent: Value is a tuple expressed in percentage, from 0% to 100%. """ self._current_color = value - if isinstance(value, tuple) and is_percent: - for i in range(0, 3): - color = self._convert_percent_to_duty_cycle(value[i]) - self._rgb_led_pins[i].duty_cycle = color - elif isinstance(value, tuple): + if isinstance(value, tuple): for i in range(0, 3): color = int(map_range(value[i], 0, 255, 0, 65535)) if self._invert_pwm: @@ -103,12 +98,3 @@ def color(self, value, is_percent=False): self._rgb_led_pins[color].duty_cycle = abs(rgb[color]) else: raise ValueError('Color must be a tuple or 24-bit integer value.') - - def _convert_percent_to_duty_cycle(self, percent): - """Converts a percentage into a 16-bit duty_cycle integer value. - :param int percent: Percentage value, from 0% to 100%. - """ - if self._invert_pwm: - data = int(percent / 100.0 * 65535.0) - 65535 - return abs(data) - return int(percent / 100.0 * 65535.0) From dc1a3691edaec08ae0b3c5d844bc2c58a605e943 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 17:22:27 -0400 Subject: [PATCH 25/47] fix requirements.txt --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index deb055b..3e78577 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ Adafruit-Blinka -simpleio \ No newline at end of file +adafruit-circuitpython-simpleio \ No newline at end of file From 5f641cc6b302f7506d9ec0e3a6bbdae665e49d87 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 17:25:23 -0400 Subject: [PATCH 26/47] remove code.py top level --- code.py | 29 ----------------------------- 1 file changed, 29 deletions(-) delete mode 100755 code.py diff --git a/code.py b/code.py deleted file mode 100755 index d1cb87d..0000000 --- a/code.py +++ /dev/null @@ -1,29 +0,0 @@ -import time -import board -import adafruit_rgbled - -# color types -red_tuple = (100, 0, 0) -green_tuple = (0, 100, 0) -blue_tuple = (0, 0, 100) - -# hex types -red_hex = 0x100000 - -# TODO: integer types - -led = adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7) -print('RGB LED Brightness: ', led.brightness) - -color = led.color -print(color) - - -led.color = red_tuple -time.sleep(1) -led.color = green_tuple -time.sleep(1) -led.color = blue_tuple -time.sleep(1) -led.color = red_hex -time.sleep(1) \ No newline at end of file From b9117299264a3fdaf61b23a3ad2d2ad0a821e8f5 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 17:27:57 -0400 Subject: [PATCH 27/47] fix pwmout? --- adafruit_rgbled.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 63214cf..bca3fa2 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -37,7 +37,7 @@ * Adafruit's SimpleIO library: https://github.com/adafruit/Adafruit_CircuitPython_SimpleIO """ -from pulseio import PWMOut +import pulseio from simpleio import map_range __version__ = "0.0.0-auto.0" @@ -54,9 +54,9 @@ def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): :param int blue_pin: Blue Anode Pin. :param bool invert_pwm: Use inverted PWM (Common anode). """ - self._red_led = PWMOut(red_pin) - self._green_led = PWMOut(green_pin) - self._blue_led = PWMOut(blue_pin) + self._red_led = pulseio.PWMOut(red_pin) + self._green_led = pulseio.PWMOut(green_pin) + self._blue_led = pulseio.PWMOut(blue_pin) self._rgb_led_pins = [self._red_led, self._green_led, self._blue_led] self._invert_pwm = invert_pwm self._current_color = (0, 0, 0) From 69009a049d9ac0c785ffddeb86f28eb464385130 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 17:29:14 -0400 Subject: [PATCH 28/47] add pulseio to autodoc --- docs/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index 6fefa51..00bd13a 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,7 +20,7 @@ # Uncomment the below if you use native CircuitPython modules such as # digitalio, micropython and busio. List the modules you use. Without it, the # autodoc module docs will fail to generate with a warning. -# autodoc_mock_imports = ["digitalio", "busio"] +autodoc_mock_imports = ["pulseio"] intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} From 07a347c16dd7b05c18b1124b6e018aa55b9e0f91 Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 17:32:05 -0400 Subject: [PATCH 29/47] add pylint ignore --- adafruit_rgbled.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index bca3fa2..5179b7c 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -37,7 +37,7 @@ * Adafruit's SimpleIO library: https://github.com/adafruit/Adafruit_CircuitPython_SimpleIO """ -import pulseio +from pulseio import PWMOut from simpleio import map_range __version__ = "0.0.0-auto.0" @@ -54,9 +54,9 @@ def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): :param int blue_pin: Blue Anode Pin. :param bool invert_pwm: Use inverted PWM (Common anode). """ - self._red_led = pulseio.PWMOut(red_pin) - self._green_led = pulseio.PWMOut(green_pin) - self._blue_led = pulseio.PWMOut(blue_pin) + self._red_led = PWMOut(red_pin) + self._green_led = PWMOut(green_pin) + self._blue_led = PWMOut(blue_pin) self._rgb_led_pins = [self._red_led, self._green_led, self._blue_led] self._invert_pwm = invert_pwm self._current_color = (0, 0, 0) @@ -65,6 +65,7 @@ def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): def deinit(self): """Turn the LEDs off, deinit pwmout and release hardware resources.""" for pin in self._rgb_led_pins: + #pylint: no-member pin.deinit() @property From cb531463ad52bf743bf70aace44c45351adba54e Mon Sep 17 00:00:00 2001 From: brentru Date: Thu, 30 May 2019 17:34:41 -0400 Subject: [PATCH 30/47] fix pylint ignore --- adafruit_rgbled.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 5179b7c..b807423 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -65,8 +65,7 @@ def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): def deinit(self): """Turn the LEDs off, deinit pwmout and release hardware resources.""" for pin in self._rgb_led_pins: - #pylint: no-member - pin.deinit() + pin.deinit() #pylint: no-member @property def color(self): From 17b83033e5e42a784842566fe0f2be21a82ed217 Mon Sep 17 00:00:00 2001 From: brentru Date: Fri, 31 May 2019 09:56:28 -0400 Subject: [PATCH 31/47] add enter/exit for contextmanager --- adafruit_rgbled.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index b807423..2511aad 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -62,6 +62,12 @@ def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): self._current_color = (0, 0, 0) self.color = self._current_color + def __enter__(self): + return self + + def __exit__(self, exception_type, exception_value, traceback): + self.deinit() + def deinit(self): """Turn the LEDs off, deinit pwmout and release hardware resources.""" for pin in self._rgb_led_pins: From 8c899dd76831b5a52b3a5d0b10512e6d6657efd1 Mon Sep 17 00:00:00 2001 From: brentru Date: Fri, 31 May 2019 10:03:15 -0400 Subject: [PATCH 32/47] add inline code examples, class description --- README.rst | 2 +- adafruit_rgbled.py | 42 +++++++++++++++++++++++++++++++++++------- 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/README.rst b/README.rst index 239963b..9cdb494 100644 --- a/README.rst +++ b/README.rst @@ -86,7 +86,7 @@ Set the RGB LED's color to a 24-bit integer (in hex syntax), 0x100000. .. code-block:: python - led.color = (255, 0, 0) + led.color = 0x100000 Contributing ============ diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 2511aad..f148566 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -45,15 +45,43 @@ class RGBLED: """ - RGB LED Driver Class. + A RGB LED. + + :param ~microcontroller.Pin red_pin: The red RGB LED pin to output PWM on. + :param ~microcontroller.Pin green_pin: The green RGB LED pin to output PWM on. + :param ~microcontroller.Pin blue_pin: The blue RGB LED pin to output PWM on. + :param bool invert_pwm: False if the RGB LED is common cathode, true if the RGB LED is common anode. + + Example for setting a RGB LED using a RGB Tuple (Red, Green, Blue): + + .. code-block:: python + import board + import adafruit_rgbled + + RED_LED = board.D5 + GREEN_LED = board.D6 + BLUE_LED = board.D7 + + # Create a RGB LED object + led = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) + led.color = (255, 0, 0) + + Example for setting a RGB LED using a 24-bit integer (hex syntax): + + .. code-block:: python + import board + import adafruit_rgbled + + RED_LED = board.D5 + GREEN_LED = board.D6 + BLUE_LED = board.D7 + + # Create a RGB LED object + led = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) + led.color = 0x100000 + """ def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): - """Initializes a RGB LED. - :param int red_pin: Red Anode Pin. - :param int green_pin: Green Anode Pin. - :param int blue_pin: Blue Anode Pin. - :param bool invert_pwm: Use inverted PWM (Common anode). - """ self._red_led = PWMOut(red_pin) self._green_led = PWMOut(green_pin) self._blue_led = PWMOut(blue_pin) From 817586c6c08e9c9e57501cb0c4b2580677b3d4bc Mon Sep 17 00:00:00 2001 From: brentru Date: Fri, 31 May 2019 11:17:43 -0400 Subject: [PATCH 33/47] add inline example for common anode and contextmanager usage --- adafruit_rgbled.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index f148566..2748fab 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -80,6 +80,22 @@ class RGBLED: led = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) led.color = 0x100000 + Example for setting a RGB LED using a ContextManager: + + .. code-block:: python + import board + import adafruit_rgbled + with adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7) as rgb_led: + rgb_led.color = (255, 0, 0) + + Example for setting a common-anode RGB LED using a ContextManager: + + .. code-block:: python + import board + import adafruit_rgbled + with adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7, invert_pwm=True) as rgb_led: + rgb_led.color = (0, 255, 0) + """ def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): self._red_led = PWMOut(red_pin) From 2bf441b6664e71c1d9007ffe653bf859e6d57e27 Mon Sep 17 00:00:00 2001 From: brentru Date: Fri, 31 May 2019 11:36:00 -0400 Subject: [PATCH 34/47] add invert pwm example, contextmanager example to readme --- README.rst | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 9cdb494..c690e4f 100644 --- a/README.rst +++ b/README.rst @@ -57,7 +57,7 @@ This example demonstrates the library with the single built-in NeoPixel on the `Feather M0 Express `_ and `Metro M0 Express `_. -Initialize a RGB LED with three PWM-capable pins. +Initialize a common-cathode RGB LED with three PWM-capable pins. .. code-block:: python @@ -76,6 +76,25 @@ Initialize a RGB LED with three PWM-capable pins. # Create a RGB LED object led = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) +Initialize a common-anode RGB LED with three PWM-capable pins + +.. code-block:: python + + import board + import adafruit_rgbled + + # Pin the Red LED is connected to + RED_LED = board.D5 + + # Pin the Green LED is connected to + GREEN_LED = board.D6 + + # Pin the Blue LED is connected to + BLUE_LED = board.D7 + + # Create a RGB LED object + led = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED, invert_pwm = True) + Set the RGB LED's color to a RGB Tuple (Red, Green, Blue). .. code-block:: python @@ -88,6 +107,14 @@ Set the RGB LED's color to a 24-bit integer (in hex syntax), 0x100000. led.color = 0x100000 +Setting a common-anode RGB LED using a ContextManager: + +.. code-block:: python + import board + import adafruit_rgbled + with adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7, invert_pwm = True) as rgb_led: + rgb_led.color = (0, 255, 0) + Contributing ============ From 2c98215fe391766829dd97c2d9b8045622f6a41c Mon Sep 17 00:00:00 2001 From: brentru Date: Fri, 31 May 2019 11:40:47 -0400 Subject: [PATCH 35/47] pylinting --- adafruit_rgbled.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 2748fab..bffb758 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -50,7 +50,8 @@ class RGBLED: :param ~microcontroller.Pin red_pin: The red RGB LED pin to output PWM on. :param ~microcontroller.Pin green_pin: The green RGB LED pin to output PWM on. :param ~microcontroller.Pin blue_pin: The blue RGB LED pin to output PWM on. - :param bool invert_pwm: False if the RGB LED is common cathode, true if the RGB LED is common anode. + :param bool invert_pwm: False if the RGB LED is common cathode, + true if the RGB LED is common anode. Example for setting a RGB LED using a RGB Tuple (Red, Green, Blue): @@ -65,7 +66,7 @@ class RGBLED: # Create a RGB LED object led = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) led.color = (255, 0, 0) - + Example for setting a RGB LED using a 24-bit integer (hex syntax): .. code-block:: python @@ -108,7 +109,7 @@ def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): def __enter__(self): return self - + def __exit__(self, exception_type, exception_value, traceback): self.deinit() From 7353f7692f6d4a1bba58697186c396ede000b33e Mon Sep 17 00:00:00 2001 From: brentru Date: Fri, 31 May 2019 11:49:15 -0400 Subject: [PATCH 36/47] adding indent to docstring --- adafruit_rgbled.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index bffb758..e9ba734 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -51,7 +51,7 @@ class RGBLED: :param ~microcontroller.Pin green_pin: The green RGB LED pin to output PWM on. :param ~microcontroller.Pin blue_pin: The blue RGB LED pin to output PWM on. :param bool invert_pwm: False if the RGB LED is common cathode, - true if the RGB LED is common anode. + true if the RGB LED is common anode. Example for setting a RGB LED using a RGB Tuple (Red, Green, Blue): From 325d8cf5d03f6a2c523ded71d624b841906ba4c2 Mon Sep 17 00:00:00 2001 From: brentru Date: Mon, 3 Jun 2019 14:11:55 -0400 Subject: [PATCH 37/47] adding support for PCA9685 PWM driver --- adafruit_rgbled.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index e9ba734..42e3894 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -99,10 +99,11 @@ class RGBLED: """ def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): - self._red_led = PWMOut(red_pin) - self._green_led = PWMOut(green_pin) - self._blue_led = PWMOut(blue_pin) - self._rgb_led_pins = [self._red_led, self._green_led, self._blue_led] + self._rgb_led_pins = [red_pin, green_pin, blue_pin] + for i in range(len(self._rgb_led_pins)): + pin_type = str(type(self._rgb_led_pins[i])) + if pin_type == "": + self._rgb_led_pins[i] = PWMOut(self._rgb_led_pins[i]) self._invert_pwm = invert_pwm self._current_color = (0, 0, 0) self.color = self._current_color From 917432162d57e3aa90277ef8ec3d4611e6d96a15 Mon Sep 17 00:00:00 2001 From: brentru Date: Mon, 3 Jun 2019 14:22:44 -0400 Subject: [PATCH 38/47] color should revert to initial tuple when de-init'd --- adafruit_rgbled.py | 1 + 1 file changed, 1 insertion(+) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 42e3894..929b91e 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -118,6 +118,7 @@ def deinit(self): """Turn the LEDs off, deinit pwmout and release hardware resources.""" for pin in self._rgb_led_pins: pin.deinit() #pylint: no-member + self._current_color = (0, 0, 0) @property def color(self): From 5b0102ff434c47941b118cdfcde8e9918245117e Mon Sep 17 00:00:00 2001 From: brentru Date: Mon, 3 Jun 2019 14:26:22 -0400 Subject: [PATCH 39/47] add example for using this library with the pca9685, useful for Pi, etc! --- examples/rgbled_pca9685.py | 67 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 examples/rgbled_pca9685.py diff --git a/examples/rgbled_pca9685.py b/examples/rgbled_pca9685.py new file mode 100644 index 0000000..87d5c05 --- /dev/null +++ b/examples/rgbled_pca9685.py @@ -0,0 +1,67 @@ +import time +import board +import busio +import adafruit_pca9685 +import adafruit_rgbled + +# PCA9685 Initialization +i2c = busio.I2C(board.SCL, board.SDA) +pca = adafruit_pca9685.PCA9685(i2c) +pca.frequency=60 + +# PCA9685 LED Channels +RED_LED = pca.channels[0] +GREEN_LED = pca.channels[1] +BLUE_LED = pca.channels[2] + +# Create the RGB LED object +led = adafruit_rgbled.RGBLED(RED_LED, GREEN_LED, BLUE_LED, invert_pwm=True) + +# Optionally, you can also create the RGB LED object with inverted PWM +# led = adafruit_rgbled.RGBLED(RED_LED, GREEN_LED, BLUE_LED, invert_pwm=True) + +def wheel(pos): + # Input a value 0 to 255 to get a color value. + # The colours are a transition r - g - b - back to r. + if pos < 0 or pos > 255: + return 0, 0, 0 + if pos < 85: + return int(255 - pos * 3), int(pos * 3), 0 + if pos < 170: + pos -= 85 + return 0, int(255 - pos * 3), int(pos * 3) + pos -= 170 + return int(pos * 3), 0, int(255 - (pos * 3)) + +def rainbow_cycle(wait): + for i in range(255): + i = (i + 1) % 256 + led.color = wheel(i) + time.sleep(wait) + +while True: + # setting RGB LED color to RGB Tuples (R, G, B) + print('setting color 1') + led.color = (255, 0, 0) + time.sleep(1) + + print('setting color 2') + led.color = (0, 255, 0) + time.sleep(1) + + print('setting color 3') + led.color = (0, 0, 255) + time.sleep(1) + + # setting RGB LED color to 24-bit integer values + led.color = 0xFF0000 + time.sleep(1) + + led.color = 0x00FF00 + time.sleep(1) + + led.color = 0x0000FF + time.sleep(1) + + # rainbow cycle the RGB LED + rainbow_cycle(0.01) From b53be359275bbf126dd4aa35e3be4e2d4dd5ea07 Mon Sep 17 00:00:00 2001 From: brentru Date: Mon, 3 Jun 2019 14:30:52 -0400 Subject: [PATCH 40/47] update README.rst to reflect compatibility with PCA, blinka --- README.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index c690e4f..274158c 100644 --- a/README.rst +++ b/README.rst @@ -13,7 +13,8 @@ CircuitPython_RGBLED :target: https://travis-ci.com/adafruit/Adafruit_CircuitPython_RGBLED :alt: Build Status -CircuitPython driver for RGB LEDs. +CircuitPython driver for RGB LEDs. Works with native microcontroller pins, +`Adafruit Blinka `_, or the `PCA9685 PWM driver `_. Dependencies ============= From 4271d90a322df91c201f61d148bc8c0baef81b66 Mon Sep 17 00:00:00 2001 From: brentru Date: Mon, 3 Jun 2019 14:36:12 -0400 Subject: [PATCH 41/47] update docstrings in main .py to satisfy travis --- adafruit_rgbled.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 929b91e..3270ccd 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -56,6 +56,7 @@ class RGBLED: Example for setting a RGB LED using a RGB Tuple (Red, Green, Blue): .. code-block:: python + import board import adafruit_rgbled @@ -70,6 +71,7 @@ class RGBLED: Example for setting a RGB LED using a 24-bit integer (hex syntax): .. code-block:: python + import board import adafruit_rgbled @@ -84,6 +86,7 @@ class RGBLED: Example for setting a RGB LED using a ContextManager: .. code-block:: python + import board import adafruit_rgbled with adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7) as rgb_led: @@ -92,6 +95,7 @@ class RGBLED: Example for setting a common-anode RGB LED using a ContextManager: .. code-block:: python + import board import adafruit_rgbled with adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7, invert_pwm=True) as rgb_led: From 2f386cbea020c26c2875df6b0b27646d4c7ce460 Mon Sep 17 00:00:00 2001 From: brentru Date: Mon, 3 Jun 2019 14:39:50 -0400 Subject: [PATCH 42/47] fix code block... --- README.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/README.rst b/README.rst index 274158c..c15cb46 100644 --- a/README.rst +++ b/README.rst @@ -111,6 +111,7 @@ Set the RGB LED's color to a 24-bit integer (in hex syntax), 0x100000. Setting a common-anode RGB LED using a ContextManager: .. code-block:: python + import board import adafruit_rgbled with adafruit_rgbled.RGBLED(board.D5, board.D6, board.D7, invert_pwm = True) as rgb_led: From 2fe47a2f6be33eb346690acc06f505c4d101e59d Mon Sep 17 00:00:00 2001 From: brentru Date: Mon, 3 Jun 2019 14:57:31 -0400 Subject: [PATCH 43/47] fix readme neopixel leftover --- README.rst | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/README.rst b/README.rst index c15cb46..a990f5f 100644 --- a/README.rst +++ b/README.rst @@ -52,11 +52,7 @@ To install in a virtual environment in your current project: pip3 install adafruit-circuitpython-rgbled Usage Example -============= - -This example demonstrates the library with the single built-in NeoPixel on the -`Feather M0 Express `_ and -`Metro M0 Express `_. +============== Initialize a common-cathode RGB LED with three PWM-capable pins. From 38abddbba35115d63386506525d0e77f0c1657de Mon Sep 17 00:00:00 2001 From: brentru Date: Mon, 3 Jun 2019 15:06:48 -0400 Subject: [PATCH 44/47] detect PWMChannel, PWMOut, or Pin --- adafruit_rgbled.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 3270ccd..3dfa752 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -108,6 +108,12 @@ def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): pin_type = str(type(self._rgb_led_pins[i])) if pin_type == "": self._rgb_led_pins[i] = PWMOut(self._rgb_led_pins[i]) + self._rgb_led_pins[i].duty_cycle = 0 + elif pin_type == "" or pin_type == "": + # PWMChannel/PWMOut do not require extra setup + self._rgb_led_pins[i].duty_cycle = 0 + else: + raise TypeError('Must provide a pin, PWMOut, or PWMChannel.') self._invert_pwm = invert_pwm self._current_color = (0, 0, 0) self.color = self._current_color From fc354d670046d11e21cfc6069121bd85152507d7 Mon Sep 17 00:00:00 2001 From: brentru Date: Mon, 3 Jun 2019 15:15:39 -0400 Subject: [PATCH 45/47] redo docstrings to show inclusion of pwmchannel, pwmout, microcontroller pin --- adafruit_rgbled.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 3dfa752..6c900b6 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -47,9 +47,18 @@ class RGBLED: """ A RGB LED. - :param ~microcontroller.Pin red_pin: The red RGB LED pin to output PWM on. - :param ~microcontroller.Pin green_pin: The green RGB LED pin to output PWM on. - :param ~microcontroller.Pin blue_pin: The blue RGB LED pin to output PWM on. + :param red_pin: The physical pin connected to a red LED anode. + :type ~microcontroller.Pin: Microcontroller's red_pin. + :type pulseio.PWMOut: PWMOut object associated with red_pin. + :type PWMChannel: PCA9685 PWM channel associated with red_pin. + :param green_pin: The physical pin connected to a green LED anode. + :type ~microcontroller.Pin: Microcontroller's green_pin. + :type pulseio.PWMOut: PWMOut object associated with green_pin. + :type PWMChannel: PCA9685 PWM channel associated with green_pin. + :param blue_pin: The physical pin connected to a blue LED anode. + :type ~microcontroller.Pin: Microcontroller's blue_pin. + :type pulseio.PWMOut: PWMOut object associated with blue_pin. + :type PWMChannel: PCA9685 PWM channel associated with blue_pin. :param bool invert_pwm: False if the RGB LED is common cathode, true if the RGB LED is common anode. From 265f9ab92a3b982df2296a93fc6970a479e7e381 Mon Sep 17 00:00:00 2001 From: brentru Date: Mon, 3 Jun 2019 15:16:40 -0400 Subject: [PATCH 46/47] add more info to class docstring --- adafruit_rgbled.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index 6c900b6..f18249d 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -45,7 +45,7 @@ class RGBLED: """ - A RGB LED. + Creates a RGBLED object given three physical pins or PWMOut objects. :param red_pin: The physical pin connected to a red LED anode. :type ~microcontroller.Pin: Microcontroller's red_pin. From b9a3b1a0aed5654f83fb16a66583a2347b91d5bb Mon Sep 17 00:00:00 2001 From: brentru Date: Tue, 4 Jun 2019 09:41:05 -0400 Subject: [PATCH 47/47] check for frequency property btween pwmpins --- adafruit_rgbled.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/adafruit_rgbled.py b/adafruit_rgbled.py index f18249d..23632b1 100644 --- a/adafruit_rgbled.py +++ b/adafruit_rgbled.py @@ -114,12 +114,10 @@ class RGBLED: def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): self._rgb_led_pins = [red_pin, green_pin, blue_pin] for i in range(len(self._rgb_led_pins)): - pin_type = str(type(self._rgb_led_pins[i])) - if pin_type == "": - self._rgb_led_pins[i] = PWMOut(self._rgb_led_pins[i]) + if hasattr(self._rgb_led_pins[i], 'frequency'): self._rgb_led_pins[i].duty_cycle = 0 - elif pin_type == "" or pin_type == "": - # PWMChannel/PWMOut do not require extra setup + elif str(type(self._rgb_led_pins[i])) == "": + self._rgb_led_pins[i] = PWMOut(self._rgb_led_pins[i]) self._rgb_led_pins[i].duty_cycle = 0 else: raise TypeError('Must provide a pin, PWMOut, or PWMChannel.')