diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..773bfd6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +# Compiled source # +################### +*.com +*.class +*.dll +*.exe +*.o +*.so + +# Packages # +############ +# it's better to unpack these files and commit the raw source +# git has its own built in compression methods +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Logs and databases # +###################### +*.log +*.sql +*.sqlite + +# OS generated files # +###################### +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..2b899a2 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,435 @@ +[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, global-statement, simplifiable-if-statement + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable= + + +[REPORTS] + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio).You can also give a reporter class, eg +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + + +[LOGGING] + +# Logging modules to check that the string format arguments are in logging +# function parameter format +logging-modules=logging + + +[SPELLING] + +# Spelling dictionary name. Available dictionaries: none. To make it working +# install python-enchant package. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME,XXX,TODO + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis. It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid to define new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_,_cb + +# A regular expression matching the name of dummy variables (i.e. expectedly +# not used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,future.builtins + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +# expected-line-ending-format= +expected-line-ending-format=LF + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module +max-module-lines=1000 + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma,dict-separator + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[BASIC] + +# Naming hint for argument names +argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Regular expression matching correct argument names +argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Naming hint for attribute names +attr-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Regular expression matching correct attribute names +attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Bad variable names which should always be refused, separated by a comma +bad-names=foo,bar,baz,toto,tutu,tata + +# Naming hint for class attribute names +class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ + +# Regular expression matching correct class attribute names +class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ + +# Naming hint for class names +# class-name-hint=[A-Z_][a-zA-Z0-9]+$ +class-name-hint=[A-Z_][a-zA-Z0-9_]+$ + +# Regular expression matching correct class names +# class-rgx=[A-Z_][a-zA-Z0-9]+$ +class-rgx=[A-Z_][a-zA-Z0-9_]+$ + +# Naming hint for constant names +const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ + +# Regular expression matching correct constant names +const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming hint for function names +function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Regular expression matching correct function names +function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Good variable names which should always be accepted, separated by a comma +# good-names=i,j,k,ex,Run,_ +good-names=r,g,b,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/.travis.yml b/.travis.yml new file mode 100644 index 0000000..8957cda --- /dev/null +++ b/.travis.yml @@ -0,0 +1,16 @@ +# MetroX-CircuitPython travis.yml + +dist: trusty +sudo: false +language: python +python: + - "3.6" + +cache: + pip: true + +install: + - pip install pylint circuitpython-build-tools + +script: + pylint --disable=missing-docstring,invalid-name examples/*.py diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..1617586 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* 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 in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at support@adafruit.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..40d1452 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 asher lieber, ladyada, 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 dcbe5a4..0000000 --- a/README.md +++ /dev/null @@ -1 +0,0 @@ -# METROX-CircuitPython \ No newline at end of file diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..830f398 --- /dev/null +++ b/README.rst @@ -0,0 +1,88 @@ +Introduction +============ + +.. image:: https://readthedocs.org/projects/circuitpython-metrox-circuitpython/badge/?version=latest + :target: https://circuitpython-metrox-circuitpython.readthedocs.io/ + :alt: Documentation Status + +.. image:: https://img.shields.io/discord/327254708534116352.svg + :target: https://discord.gg/nBQh6qu + :alt: Discord + +.. image:: https://travis-ci.org/adafruit/CircuitPython_METROX-CircuitPython.svg?branch=master + :target: https://travis-ci.org/adafruit/CircuitPython_METROX-CircuitPython + :alt: Build Status + +.. todo:: Describe what the library does. + +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 `_. + +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 circuitpython-metrox-circuitpython --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/examples/blinking_led.py b/examples/blinking_led.py new file mode 100755 index 0000000..3b93cf7 --- /dev/null +++ b/examples/blinking_led.py @@ -0,0 +1,23 @@ +""" +'blinking_led.py'. + +================================================= +blinks a led using digitalio +""" + +import time +import digitalio +import board + +led = digitalio.DigitalInOut(board.D13) +led.switch_to_output() + +while True: + # turn led ON + led.value = True + # wait 1 second + time.sleep(1.0) + # turn led off + led.value = False + # wait 1 second + time.sleep(1.0) diff --git a/examples/button_press.py b/examples/button_press.py new file mode 100755 index 0000000..25b658a --- /dev/null +++ b/examples/button_press.py @@ -0,0 +1,18 @@ +""" +'button_press.py'. + +================================================= +push the button and light up a led +""" +import digitalio +import board + +led = digitalio.DigitalInOut(board.D13) +led.switch_to_output() +button = digitalio.DigitalInOut(board.D2) +button.switch_to_input() + + +while True: + btn_state = button.value + led.value = not btn_state diff --git a/examples/char_lcd.py b/examples/char_lcd.py new file mode 100755 index 0000000..7b00617 --- /dev/null +++ b/examples/char_lcd.py @@ -0,0 +1,61 @@ +""" +'char_lcd.py' +================================================= +hello world using 16x2 character lcd +requires: +- CircuitPython_CharLCD Module +""" + +import time +import digitalio +import adafruit_character_lcd +from board import D7, D8, D9, D10, D11, D12, D13 + +# Character LCD Config: +# modify this if you have a different sized charlcd +lcd_columns = 16 +lcd_rows = 2 + +# Metro Express Pin Config: +lcd_rs = digitalio.DigitalInOut(D7) +lcd_en = digitalio.DigitalInOut(D8) +lcd_d7 = digitalio.DigitalInOut(D12) +lcd_d6 = digitalio.DigitalInOut(D11) +lcd_d5 = digitalio.DigitalInOut(D10) +lcd_d4 = digitalio.DigitalInOut(D9) +lcd_backlight = digitalio.DigitalInOut(D13) + +# Init the lcd class +lcd = adafruit_character_lcd.Character_LCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, + lcd_d7, lcd_columns, lcd_rows, lcd_backlight) + +# Print a 2x line message +lcd.message('hello\ncircuitpython') +# Wait 5s +time.sleep(5) +# Demo showing cursor +lcd.clear() +lcd.show_cursor(True) +lcd.message('showing cursor ') +# Wait 5s +time.sleep(5) +# Demo showing the blinking cursor +lcd.clear() +lcd.blink(True) +lcd.message('Blinky Cursor!') +# Wait 5s +time.sleep(5) +lcd.blink(False) +# Demo scrolling message LEFT +lcd.clear() +scroll_msg = 'Scroll' +lcd.message(scroll_msg) +# Scroll to the left +for i in range(lcd_columns - len(scroll_msg)): + time.sleep(0.5) + lcd.move_left() +# Demo turning backlight off +lcd.clear() +lcd.message("going to sleep\ncya later!") +lcd.set_backlight(False) +time.sleep(2) diff --git a/examples/colorful_light.py b/examples/colorful_light.py new file mode 100755 index 0000000..084c7ce --- /dev/null +++ b/examples/colorful_light.py @@ -0,0 +1,40 @@ +""" +'colorful_light.py'. + +================================================= +RGB LED control with circuitpython +""" + +import board +import digitalio + +RED = [True, False, False] +GREEN = [False, True, False] +BLUE = [False, False, True] +YELLOW = [True, True, False] +CYAN = [False, True, True] +MAGENTA = [True, False, True] +WHITE = [True, True, True] +BLACK = [False, False, False] +color_array = [RED, GREEN, BLUE, YELLOW, CYAN, MAGENTA, WHITE, BLACK] + +red_led = digitalio.DigitalInOut(board.D9) +green_led = digitalio.DigitalInOut(board.D10) +blue_led = digitalio.DigitalInOut(board.D11) + +rgb_led = [red_led, green_led, blue_led] + + +for led in rgb_led: + led.switch_to_output() + + +def set_color(color): + """sets the rgb led's cathode value.""" + rgb_led[0].value = not color[0] + rgb_led[1].value = not color[1] + rgb_led[2].value = not color[2] + + +while True: + set_color(GREEN) diff --git a/examples/eight_leds.py b/examples/eight_leds.py new file mode 100644 index 0000000..6ec2df5 --- /dev/null +++ b/examples/eight_leds.py @@ -0,0 +1,120 @@ +""" +'eight_leds.py'. + +================================================= +lights up 8 leds with different animations +""" +import time +import board +import digitalio + +led_pins = [digitalio.DigitalInOut(board.D2), + digitalio.DigitalInOut(board.D3), + digitalio.DigitalInOut(board.D4), + digitalio.DigitalInOut(board.D5), + digitalio.DigitalInOut(board.D6), + digitalio.DigitalInOut(board.D7), + digitalio.DigitalInOut(board.D8), + digitalio.DigitalInOut(board.D9)] + +for pin in led_pins: + pin.switch_to_output() + +def one_after_another_no_loop(): + """turns one LED on at a time, not looping at the end.""" + delay_time = 0.1 + led_pins[0].value = True + time.sleep(delay_time) + led_pins[1].value = True + time.sleep(delay_time) + led_pins[2].value = True + time.sleep(delay_time) + led_pins[3].value = True + time.sleep(delay_time) + led_pins[4].value = True + time.sleep(delay_time) + led_pins[5].value = True + time.sleep(delay_time) + led_pins[6].value = True + time.sleep(delay_time) + led_pins[7].value = True + time.sleep(delay_time) + + led_pins[7].value = False + time.sleep(delay_time) + led_pins[6].value = False + time.sleep(delay_time) + led_pins[5].value = False + time.sleep(delay_time) + led_pins[4].value = False + time.sleep(delay_time) + led_pins[3].value = False + time.sleep(delay_time) + led_pins[2].value = False + time.sleep(delay_time) + led_pins[1].value = False + time.sleep(delay_time) + led_pins[0].value = False + time.sleep(delay_time) + + +def one_after_another_loop(): + """turns one LED on at a time, looping at the end.""" + delay_time = 0.1 + for led in led_pins: + led.value = True + time.sleep(delay_time) + for led in led_pins[::-1]: + led.value = False + time.sleep(delay_time) + + +def one_on_at_a_time(): + """turns one LED on at a time, looping at the end.""" + delay_time = 0.1 + led_array_length = len(led_pins) + for i in range(10 * led_array_length): + j = i % led_array_length + led_pins[j].value = True + time.sleep(delay_time) + led_pins[j].value = False + + +def in_and_out(): + """fades the LEDs in and out.""" + delay_time = 0.1 + for i in range(3): + off_led = i - 1 + if i == 0: + off_led = 3 + on_led_1 = 3 - i + on_led_2 = 4 + i + off_led1 = 3 - off_led + off_led2 = 4 + off_led + delay_time = 0.1 + for pin_range in led_pins: + for _ in range(10): + pin_range.value = True + time.sleep(delay_time) + pin_range.value = False + for i in range(3): + i = 3 - i + off_led = i + 1 + if i == 3: + off_led = 0 + on_led_1 = 3 - i + on_led_2 = 4 + i + off_led1 = 3 - off_led + off_led2 = 4 + off_led + led_pins[on_led_1].value = True + led_pins[on_led_2].value = True + led_pins[off_led1].value = False + led_pins[off_led2].value = False + time.sleep(delay_time) + + +while True: + # one_after_another_no_loop() + # one_after_another_loop() + # one_on_at_a_time() + in_and_out() diff --git a/examples/eight_more_leds.py b/examples/eight_more_leds.py new file mode 100644 index 0000000..360de08 --- /dev/null +++ b/examples/eight_more_leds.py @@ -0,0 +1,73 @@ +""" +'8_more_leds.py'. + +================================================= +LED light show with a 74HC595 shift register +""" + +import time +import board +import digitalio + + +DATA = digitalio.DigitalInOut(board.d2) +DATA.switch_to_output() +CLK = digitalio.DigitalInOut(board.d3) +CLK.switch_to_output() +LATCH = digitalio.DigitalInOut(board.d4) +LATCH.switch_to_output() + +LED_STATE = 0 +BITS = [0b00000001, 0b00000010, 0b00000100, 0b00001000, + 0b00010000, 0b00100000, 0b01000000, 0b10000000] +MASKS = [0b11111110, 0b11111101, 0b11111011, 0b11110111, + 0b11101111, 0b11011111, 0b10111111, 0b01111111] + + +def update_leds(leds): + """updates the LED state.""" + LATCH.value = False + for bit in range(8): + if leds & (1 << bit): + DATA.value = True + else: + DATA.value = False + CLK.value = True + CLK.value = False + LATCH.value = True + + +def update_leds_long(value): + """uses bitmasking to update LEDs.""" + LATCH.value = False + val = value + # repeat once for each bit + for _ in range(8): + # use bitmask to select only the eighth bit in number + bit = val & 0b10000000 + val <<= 1 + if bit == 128: + DATA.value = True + else: + DATA.value = False + CLK.value = True + time.sleep(.01) + CLK.value = False + LATCH.value = True + + +def change_led(led, state): + """changes the LED's state.""" + global LED_STATE + LED_STATE = LED_STATE & MASKS[led] + if state: + LED_STATE = LED_STATE | BITS[led] + # print(LED_STATE) + update_leds(LED_STATE) + + +while True: + change_led(3, True) + for j in range(0, 256, 1): + update_leds(j) + time.sleep(0.4) diff --git a/examples/fading_led.py b/examples/fading_led.py new file mode 100644 index 0000000..099cdf3 --- /dev/null +++ b/examples/fading_led.py @@ -0,0 +1,18 @@ +""" +'fading_led.py'. + +================================================= +fades a LED using pulseio's PWM +""" + +import pulseio +import board + +led = pulseio.PWMOut(board.D13, frequency=500, duty_cycle=0) + +while True: + for i in range(100): + if i < 50: # fade up + led.duty_cycle = int(i * 2 * 65535 / 100) + else: # fade down + led.duty_cycle = 65535 - int((i-50) * 2 * 65535 / 100) diff --git a/examples/mib_button_press_on_off.py b/examples/mib_button_press_on_off.py new file mode 100755 index 0000000..3820af6 --- /dev/null +++ b/examples/mib_button_press_on_off.py @@ -0,0 +1,23 @@ +""" +'button_press_on_off.py'. + +================================================= +lightswitch-like operation with two buttons and a led +""" + +import board +import digitalio + +led = digitalio.DigitalInOut(board.D13) +led.switch_to_output() +btn1 = digitalio.DigitalInOut(board.D2) +btn1.switch_to_input() +btn2 = digitalio.DigitalInOut(board.D3) +btn2.switch_to_input() + + +while True: + if not btn1.value: + led.value = False + elif not btn2.value: + led.value = True diff --git a/examples/mib_button_press_pwm.py b/examples/mib_button_press_pwm.py new file mode 100755 index 0000000..a7c04eb --- /dev/null +++ b/examples/mib_button_press_pwm.py @@ -0,0 +1,30 @@ +""" +'mib_button_press_pwm.py'. + +================================================= +fade a led in and out using two buttons +""" +import time +import digitalio +import board +import pulseio + + +led = pulseio.PWMOut(board.D13) +btn1 = digitalio.DigitalInOut(board.D3) +btn2 = digitalio.DigitalInOut(board.D2) +btn1.switch_to_input() +btn2.switch_to_input() + + +while True: + BRIGHTNESS = led.duty_cycle + # If button + if not btn1.value: + BRIGHTNESS += 100 + if not btn2.value: + BRIGHTNESS -= 100 + BRIGHTNESS = max(0, BRIGHTNESS) + BRIGHTNESS = min(44000, BRIGHTNESS) + led.duty_cycle = BRIGHTNESS + time.sleep(0.001) diff --git a/examples/mib_char_lcd_light.py b/examples/mib_char_lcd_light.py new file mode 100755 index 0000000..11b0636 --- /dev/null +++ b/examples/mib_char_lcd_light.py @@ -0,0 +1,42 @@ +""" +'mib_char_lcd_light.py' +================================================= +light sensor circuit. displays output on charlcd +requires: +- CircuitPython_CharLCD Module +""" + +import time +import analogio +import digitalio +import adafruit_character_lcd +from board import D7, D8, D9, D10, D11, D12, D13, A0 + +# Character LCD Config: +# modify this if you have a different sized charlcd +lcd_columns = 16 +lcd_rows = 2 + +# Metro Express Pin Config: +lcd_rs = digitalio.DigitalInOut(D7) +lcd_en = digitalio.DigitalInOut(D8) +lcd_d7 = digitalio.DigitalInOut(D12) +lcd_d6 = digitalio.DigitalInOut(D11) +lcd_d5 = digitalio.DigitalInOut(D10) +lcd_d4 = digitalio.DigitalInOut(D9) +lcd_backlight = digitalio.DigitalInOut(D13) + +light = analogio.AnalogIn(A0) + +# Init the lcd class +lcd = adafruit_character_lcd.Character_LCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, + lcd_d7, lcd_columns, lcd_rows, lcd_backlight) + +while True: + lcd.clear() + percent = str(100-((light.value/65535)*100)) + nice = percent[:percent.find('.')] + lcd.message(nice + "% bright") + lcd.message(str(light.value)) + time.sleep(1) + # increment our elapsed_secs variable each time a second passes diff --git a/examples/mib_colorful_light.py b/examples/mib_colorful_light.py new file mode 100755 index 0000000..b88c0c3 --- /dev/null +++ b/examples/mib_colorful_light.py @@ -0,0 +1,46 @@ +""" +'mib_colorful_light.py'. + +================================================= +RGB LED control with circuitpython +requires: +-simpleio +""" +import random +import board +import pulseio +from simpleio import map_range + +RED = [100, 0, 0] +ORANGE = [50, 5, 0] +YELLOW = [100, 100, 0] +GREEN = [0, 100, 0] +TEAL = [0, 50, 5] +CYAN = [0, 100, 100] +BLUE = [0, 0, 100] +MAGENTA = [100, 0, 100] +WHITE = [100, 100, 100] +BLACK = [0, 0, 0] +color_array = [RED, ORANGE, YELLOW, GREEN, TEAL, BLUE, CYAN, MAGENTA, WHITE, BLACK] + +red_led = pulseio.PWMOut(board.D9) +green_led = pulseio.PWMOut(board.D10) +blue_led = pulseio.PWMOut(board.D11) + +rgb_led_array = [red_led, green_led, blue_led] + +def set_color(color): + """sets the rgb led's cathodes.""" + print("Setting (%0.2f, %0.2f, %0.2f)" % (color[0], color[1], color[2])) + rgb_led_array[0].duty_cycle = int(map_range(color[0], 0, 100, 65535, 0)) + rgb_led_array[1].duty_cycle = int(map_range(color[1], 0, 100, 65535, 0)) + rgb_led_array[2].duty_cycle = int(map_range(color[2], 0, 100, 65535, 0)) + + +def random_color(): + """generates a random color.""" + rnd_color = random.randrange(len(color_array)) + set_color(color_array[rnd_color]) + +while True: + set_color(GREEN) diff --git a/examples/mib_motor.py b/examples/mib_motor.py new file mode 100755 index 0000000..09ef360 --- /dev/null +++ b/examples/mib_motor.py @@ -0,0 +1,41 @@ +""" +'mib_motor.py'. + +================================================= +spins a DC motor using pulseio +""" + +import time +import board +import pulseio + +motor_pin = board.D9 +motor = pulseio.PWMOut(motor_pin, frequency=1000) + + +def motor_on_then_off_with_speed(): + """turns the motor on, then off, using PWM.""" + on_speed = 0.80 + on_time = 2.5 + off_speed = 0.10 + off_time = 1.0 + motor.duty_cycle = int(on_speed * 65535) + time.sleep(on_time) + motor.duty_cycle = int(off_speed * 65535) + time.sleep(off_time) + + +def motor_acceleration(): + """accelerates the motor forwards and backwards.""" + delay_time = 0.05 + for speed in range(0, 100, 1): + motor.duty_cycle = int(speed / 100 * 65535) + time.sleep(delay_time) + for speed in range(100, 0, -1): + motor.duty_cycle = int(speed / 100 * 65535) + time.sleep(delay_time) + + +while True: + motor_on_then_off_with_speed() + # motor_acceleration() diff --git a/examples/mib_photo_sensor_night_light.py b/examples/mib_photo_sensor_night_light.py new file mode 100755 index 0000000..83a234a --- /dev/null +++ b/examples/mib_photo_sensor_night_light.py @@ -0,0 +1,23 @@ +""" +'mib_photo_sensor_night_light_sensor.py'. + +================================================= +turns off and on a led using a photo sensor +""" + +import analogio +import board +import digitalio + +threshold_value = 60000 + +led = digitalio.DigitalInOut(board.D9) +led.switch_to_output() +light_sensor = analogio.AnalogIn(board.A0) + + +while True: + if light_sensor.value > threshold_value: + led.value = True + else: + led.value = False diff --git a/examples/mib_potentiometer_pwm.py b/examples/mib_potentiometer_pwm.py new file mode 100755 index 0000000..b8da9f2 --- /dev/null +++ b/examples/mib_potentiometer_pwm.py @@ -0,0 +1,16 @@ +""" +'mib_potentiometer_pwm.py'. + +================================================= +fades a led using a potentiometer +""" + +import analogio +import board +import pulseio + +led = pulseio.PWMOut(board.D9) +pot = analogio.AnalogIn(board.A0) + +while True: + led.duty_cycle = pot.value diff --git a/examples/mib_potentiometer_threshold.py b/examples/mib_potentiometer_threshold.py new file mode 100755 index 0000000..95f1da3 --- /dev/null +++ b/examples/mib_potentiometer_threshold.py @@ -0,0 +1,21 @@ +""" +'mib_potentiometer_THRESHOLD.py'. + +================================================= +turns on a LED when the potentiometer is above a half-turn +""" +import analogio +import board +import digitalio + +LED = digitalio.DigitalInOut(board.D13) +LED.switch_to_output() +POT = analogio.AnalogIn(board.A0) + +THRESHOLD = 10000 + +while True: + if POT.value > THRESHOLD: + LED.value = True + else: + LED.value = False diff --git a/examples/mib_servo.py b/examples/mib_servo.py new file mode 100755 index 0000000..d3ea887 --- /dev/null +++ b/examples/mib_servo.py @@ -0,0 +1,39 @@ +""" +'mib_servo.py'. + +================================================= +sweeping a servo with an analog potentiometer +requires: +- Adafruit_CircuitPython_Motor +""" +import time +import analogio +import board +import pulseio +from adafruit_motor import servo + + +SERVO = servo.Servo(pulseio.PWMOut(board.D9)) +POTE = analogio.AnalogIn(board.A0) + + +def servo_sweep(): + """sweeps the servo.""" + for angle_fwd in range(0, 180, 1): + SERVO.angle = angle_fwd + time.sleep(0.01) + for angle_bkwd in range(180, 0, -1): + SERVO.angle = angle_bkwd + time.sleep(0.01) + + +def pote_sweep(): + """assigns servo value to an analog potentiometer value.""" + val = POTE.value / 65536 + SERVO.angle = 180 * val + time.sleep(0.05) + + +while True: + servo_sweep() + # pote_sweep() diff --git a/examples/motor.py b/examples/motor.py new file mode 100755 index 0000000..6db2b59 --- /dev/null +++ b/examples/motor.py @@ -0,0 +1,28 @@ +""" +'MOTOR.py'. + +================================================= +spin a DC MOTOR using digitalio +""" + +import time +import board +import digitalio + +MOTOR_PIN = board.D9 +MOTOR = digitalio.DigitalInOut(MOTOR_PIN) +MOTOR.switch_to_output() + + +def motor_on_then_off(): + """toggles the motor.""" + on_time = 2.5 + off_time = 1.0 + MOTOR.value = True + time.sleep(on_time) + MOTOR.value = False + time.sleep(off_time) + + +while True: + motor_on_then_off() diff --git a/examples/neopixel_builtin.py b/examples/neopixel_builtin.py new file mode 100644 index 0000000..ecc8c03 --- /dev/null +++ b/examples/neopixel_builtin.py @@ -0,0 +1,39 @@ +""" +'neopixel_builtin.py'. + +================================================= +playing with the metro express builtin NeoPixel +""" + +import time +import board +import neopixel + +# we only have one neopixel on our metro express +NEO = neopixel.NeoPixel(board.NEOPIXEL, 1) +NEO.brightness = 0.5 + +# primary colors +RED = (255, 0, 0) +GREEN = (0, 255, 0) +BLUE = (0, 0, 255) + +COLORS = [RED, GREEN, BLUE] + +for i in COLORS: + NEO[0] = i + NEO.show() + time.sleep(.3) + +# shows all colors by trying all combinations of RGB levels +for red_level in range(0, 256, 100): + for green_level in range(0, 256, 100): + for blue_level in range(0, 256, 100): + print("red: ", red_level, "green: ", + green_level, "blue: ", blue_level) + NEO[0] = (red_level, green_level, blue_level) + NEO.show() + # wait 0.2 seconds to give us time to see the colors + time.sleep(1) +NEO[0] = (0, 0, 0) +NEO.show() diff --git a/examples/photo_sensor.py b/examples/photo_sensor.py new file mode 100755 index 0000000..68a156c --- /dev/null +++ b/examples/photo_sensor.py @@ -0,0 +1,18 @@ +""" +'photo_sensor.py'. + +================================================= +uses LIGHT to control a LED +""" +import analogio +import board +import pulseio +from simpleio import map_range + +LED = pulseio.PWMOut(board.D9) +LIGHT = analogio.AnalogIn(board.A0) + + +while True: + LIGHT_VAL = map_range(LIGHT.value, 20000, 32766, 0, 32766) + LED.duty_cycle = int(LIGHT_VAL) diff --git a/examples/piezo_music.py b/examples/piezo_music.py new file mode 100755 index 0000000..efe64f6 --- /dev/null +++ b/examples/piezo_music.py @@ -0,0 +1,35 @@ +""" +'piezo_music.py'. + +================================================= +Twinkle Twinkle with a piezo! +requires: +- simpleio library +""" +import time +import board +from simpleio import tone + +NOTES = 'ccdcfeccdcgf ' +BEATS = [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 4] +TONES = {'c': 263, + 'd': 293, + 'e': 329, + 'f': 349, + 'g': 391, + 'a': 440, + 'b': 493, + 'C': 523} +TEMPO = 300 + +# play the notes! +for i, item in enumerate(NOTES): + tempodelay = 60 / TEMPO + note = NOTES[i] + beat = BEATS[i] + print(note, end='') + if note == ' ': + time.sleep(beat * tempodelay) + else: + tone(board.D9, TONES[note], beat*tempodelay) + time.sleep(tempodelay/2) diff --git a/examples/potentiometer.py b/examples/potentiometer.py new file mode 100755 index 0000000..9a002c5 --- /dev/null +++ b/examples/potentiometer.py @@ -0,0 +1,25 @@ +""" +'potentiometer.py'. + +================================================= +control a LED's brightness using a potentiometer +""" +import time +import digitalio +import analogio +import board + +LED = digitalio.DigitalInOut(board.D13) +LED.switch_to_output() +POT = analogio.AnalogIn(board.A0) + +SENSOR_VAL = 0 + +while True: + # potentiometer value/max potentiometer value + SENSOR_VAL = POT.value / 65536 + print(SENSOR_VAL) + LED.value = True + time.sleep(SENSOR_VAL) + LED.value = False + time.sleep(SENSOR_VAL) diff --git a/examples/relay.py b/examples/relay.py new file mode 100755 index 0000000..928ad98 --- /dev/null +++ b/examples/relay.py @@ -0,0 +1,17 @@ +""" +'relay.py'. + +================================================= +drives a small relay +""" + +import time +import board +import digitalio + +RELAY = digitalio.DigitalInOut(board.D2) +RELAY.switch_to_output() + +while True: + RELAY.value = not RELAY.value + time.sleep(1) diff --git a/examples/servo.py b/examples/servo.py new file mode 100755 index 0000000..0534f61 --- /dev/null +++ b/examples/servo.py @@ -0,0 +1,20 @@ +""" +'servo.py'. + +================================================= +move a hobby servo (towerpro sg92r) w/ 3-wire interface +requires: +- Adafruit_CircuitPython_Motor +""" +import time +import board +import pulseio +from adafruit_motor import servo + +SERVO = servo.Servo(pulseio.PWMOut(board.D9)) + +while True: + SERVO.angle = 0 + time.sleep(2) + SERVO.angle = 90 + time.sleep(2) diff --git a/examples/squeeze.py b/examples/squeeze.py new file mode 100755 index 0000000..a5c1a88 --- /dev/null +++ b/examples/squeeze.py @@ -0,0 +1,16 @@ +""" +'squeeze.py'. + +================================================= +force sensitive resistor (fsr) with circuitpython +""" + +import analogio +import board +import pulseio + +FORCE_SENS_RESISTOR = analogio.AnalogIn(board.A2) +LED = pulseio.PWMOut(board.D10) + +while True: + LED.duty_cycle = FORCE_SENS_RESISTOR.value diff --git a/examples/temperature.py b/examples/temperature.py new file mode 100755 index 0000000..61f9c67 --- /dev/null +++ b/examples/temperature.py @@ -0,0 +1,28 @@ +""" +'temperature.py'. + +================================================= +Writes TMP36 data to the REPL +""" + +import time +import analogio +import board +from simpleio import map_range + +TEMP_SENSOR = analogio.AnalogIn(board.A0) + + +def get_voltage(_temp_sensor): + """gets the TMP36's voltage.""" + voltage_val = map_range(_temp_sensor.value, 0, 65535, 0, 3.3) + return voltage_val + + +while True: + TMP = get_voltage(TEMP_SENSOR) + print("Voltage =", TMP, end="") + # convert to celsius + TMP = (TMP - 0.5) * 100 + print(" Temperature =", TMP) + time.sleep(1) diff --git a/examples/temperature_alarm.py b/examples/temperature_alarm.py new file mode 100755 index 0000000..443722d --- /dev/null +++ b/examples/temperature_alarm.py @@ -0,0 +1,32 @@ +""" +'TEMP_alarm.py'. + +================================================= +sounds an alarm when the TEMP crosses a threshold +requires: +- simpleio +""" + +import time +import analogio +import pulseio +import board +from simpleio import map_range + +PIEZO = pulseio.PWMOut(board.D8, frequency=440, duty_cycle=0, variable_frequency=True) +TMP_36 = analogio.AnalogIn(board.A0) + +FREEZING_TEMP = 0 +BOIL_TEMP = 100 + +while True: + TEMP = map_range(TMP_36.value, 0, 65535, 0, 5) + # temp to degrees C + TEMP = (TEMP - .5) * 100 + print(TEMP) + + if TEMP < FREEZING_TEMP: + PIEZO.duty_cycle = 30000 + if TEMP > BOIL_TEMP: + PIEZO.duty_cycle = 10000 + time.sleep(.5)