From e058003472d63175298a2f9fa7f17f49acd52db2 Mon Sep 17 00:00:00 2001 From: caternuson Date: Tue, 23 Jan 2018 11:41:19 -0800 Subject: [PATCH] add code --- CODE_OF_CONDUCT.md | 74 +++++++++++++++++++ LICENSE | 21 ++++++ README.md | 2 - README.rst | 89 ++++++++++++++++++++++ adafruit_ds2413.py | 151 ++++++++++++++++++++++++++++++++++++++ api.rst | 5 ++ conf.py | 147 +++++++++++++++++++++++++++++++++++++ examples/direct_access.py | 27 +++++++ examples/simple.py | 32 ++++++++ readthedocs.yml | 3 + requirements.txt | 1 + 11 files changed, 550 insertions(+), 2 deletions(-) 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_ds2413.py create mode 100644 api.rst create mode 100644 conf.py create mode 100644 examples/direct_access.py create mode 100644 examples/simple.py create mode 100644 readthedocs.yml create mode 100644 requirements.txt 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..8c82590 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Carter Nelson for adafruit + +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 1265480..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# Adafruit_CircuitPython_DS2413 -CircuitPython driver for the DS2413 one wire GPIO breakout diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..b31b4eb --- /dev/null +++ b/README.rst @@ -0,0 +1,89 @@ + +Introduction +============ + +.. image:: https://readthedocs.org/projects/adafruit-circuitpython-ds2413/badge/?version=latest + + :target: https://circuitpython.readthedocs.io/projects/ds2413/en/latest/ + + :alt: Documentation Status + +.. image :: https://img.shields.io/discord/327254708534116352.svg + :target: https://discord.gg/nBQh6qu + :alt: Discord + +CircuitPython driver for the DS2413 one wire 2 channel GPIO breakout. + +Dependencies +============= +This driver depends on: + +* `Adafruit CircuitPython `_ +* `Adafruit OneWire `_ + +Please ensure all dependencies are available on the CircuitPython filesystem. +This is easily achieved by downloading +`the Adafruit library and driver bundle `_. + +Usage Example +============= + +.. code-block:: python + + import time + import board + from adafruit_onewire.bus import OneWireBus + import adafruit_ds2413 + + ow_bus = OneWireBus(board.D2) + ds = adafruit_ds2413.DS2413(ow_bus, ow_bus.scan()[0]) + + led = ds.IOA + button = ds.IOB + button.direction = adafruit_ds2413.INPUT + + while not button.value: + led.value = True + time.sleep(0.5) + led.value = False + time.sleep(0.5) + + +API Reference +============= + +.. toctree:: + :maxdepth: 2 + + api + +Contributing +============ + +Contributions are welcome! Please read our `Code of Conduct +`_ +before contributing to help this project stay welcoming. + +Building locally +================ + +To build this library locally you'll need to install the +`circuitpython-build-tools `_ package. + +.. code-block:: shell + + python3 -m venv .env + source .env/bin/activate + pip install circuitpython-build-tools + +Once installed, make sure you are in the virtual environment: + +.. code-block:: shell + + source .env/bin/activate + +Then run the build: + +.. code-block:: shell + + circuitpython-build-bundles --filename_prefix adafruit-circuitpython-ds2413 --library_location . diff --git a/adafruit_ds2413.py b/adafruit_ds2413.py new file mode 100644 index 0000000..8c0cfee --- /dev/null +++ b/adafruit_ds2413.py @@ -0,0 +1,151 @@ +# The MIT License (MIT) +# +# Copyright (c) 2017 Carter Nelson for adafruit +# +# 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. +# pylint: disable=C0103 +""" +`adafruit_DS2413` +==================================================== + + CircuitPython driver for the DS2413 one wire 2 channel GPIO breakout. + +* Author(s): Carter Nelson +""" + +__version__ = "0.0.0-auto.0" +__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_DS2413.git" + +from adafruit_onewire.device import OneWireDevice +from micropython import const + +_DS2413_ACCESS_READ = b'\xF5' +_DS2413_ACCESS_WRITE = b'\x5A' +_DS2413_ACK_SUCCESS = b'\xAA' +_DS2413_ACK_ERROR = b'\xFF' +INPUT = const(0) +OUTPUT = const(1) + +class DS2413Pin(): + """Class which provides interface to single DS2413 GPIO pin.""" + + def __init__(self, number, host, direction=OUTPUT): + if number not in (0, 1): + raise ValueError("Incorrect pin number.") + self._number = number + self._host = host + self._mask = 1 << (number * 2) + self._direction = None # create it, and then... + self.direction = direction # set it through setter + + @property + def direction(self): + """The direction of the pin, either INPUT or OUTPUT.""" + return self._direction + + @direction.setter + def direction(self, direction): + if direction not in (INPUT, OUTPUT): + raise ValueError("Incorrect direction setting.") + self._direction = OUTPUT + self.value = False + self._direction = direction + + @property + def value(self): + """The pin state if configured as INPUT. The output latch state + if configured as OUTPUT. True is HIGH/ON, False is LOW/OFF.""" + # return Pin State if configured for INPUT + # return Latch State if configured for OUTPUT + # NOTE: logic is re-inverted to make it more normally + return not self._host.pio_state & (self._mask << self._direction) + + @value.setter + def value(self, state): + # This only makes sense if the pin is configured for OUTPUT. + if self._direction == INPUT: + raise RuntimeError("Can't set value when pin is set to input.") + # We jump through some hoops in order to only set/clear the bit + # for the channel associated with this pin object. + current = self._host.pio_state + # PIOB Output Latch PIOA Output Latch + new = (current >> 2 & 0x02) | (current >> 1 & 0x01) + # To switch the output transistor on, the corresponding bit value is 0. + # To switch the output transistor off (non-conducting) the bit must be 1. + if state: + # clear it (transistor = ON) + new &= ~(1 << self._number) + else: + # set it (transistor = OFF) + new |= 1 << self._number + self._host.pio_state = new + +class DS2413(): + """Class which provides interface to DS2413 GPIO breakout.""" + + def __init__(self, bus, address): + if address.family_code == 0x3A: + self._address = address + self._device = OneWireDevice(bus, address) + self._buf = bytearray(3) + self._IOA = None + self._IOB = None + else: + raise RuntimeError('Incorrect family code in device address.') + + @property + def IOA(self): + """The pin object for channel A.""" + if self._IOA is None: + self._IOA = DS2413Pin(0, self) + return self._IOA + + @property + def IOB(self): + """The pin object for channel B.""" + if self._IOB is None: + self._IOB = DS2413Pin(1, self) + return self._IOB + + @property + def pio_state(self): + """The state of both PIO channels.""" + return self._read_status() + + @pio_state.setter + def pio_state(self, value): + return self._write_latches(value) + + def _read_status(self): + with self._device as dev: + dev.write(_DS2413_ACCESS_READ) + dev.readinto(self._buf, end=1) + return self._buf[0] + + def _write_latches(self, value): + # top six bits must be 1 + value |= 0xFC + self._buf[0] = value + self._buf[1] = ~value & 0xFF + with self._device as dev: + dev.write(_DS2413_ACCESS_WRITE) + dev.write(self._buf, end=2) + dev.readinto(self._buf, end=1) + if not self._buf[0] == ord(_DS2413_ACK_SUCCESS): + raise RuntimeError('ACK failure.') diff --git a/api.rst b/api.rst new file mode 100644 index 0000000..f3e3f0a --- /dev/null +++ b/api.rst @@ -0,0 +1,5 @@ + +.. If you created a package, create one automodule per module in the package. + +.. automodule:: adafruit_ds2413 + :members: diff --git a/conf.py b/conf.py new file mode 100644 index 0000000..1c83f33 --- /dev/null +++ b/conf.py @@ -0,0 +1,147 @@ +# -*- coding: utf-8 -*- + +import os +import sys +sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ------------------------------------------------ + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.intersphinx', + 'sphinx.ext.viewcode', +] + +# 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"] + +intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'README' + +# General information about the project. +project = u'Adafruit DS2413 Library' +copyright = u'2017 Carter Nelson' +author = u'Carter Nelson' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = u'1.0' +# The full version, including alpha/beta/rc tags. +release = u'1.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# +default_role = "any" + +# If true, '()' will be appended to :func: etc. cross-reference text. +# +add_function_parentheses = True + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +on_rtd = os.environ.get('READTHEDOCS', None) == 'True' + +if not on_rtd: # only import and set the theme if we're building docs locally + try: + import sphinx_rtd_theme + html_theme = 'sphinx_rtd_theme' + html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.'] + except: + html_theme = 'default' + html_theme_path = ['.'] +else: + html_theme_path = ['.'] + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Output file base name for HTML help builder. +htmlhelp_basename = 'AdafruitDs2413Librarydoc' + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'AdafruitDS2413Library.tex', u'AdafruitDS2413 Library Documentation', + author, 'manual'), +] + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'AdafruitDS2413library', u'Adafruit DS2413 Library Documentation', + [author], 1) +] + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'AdafruitDS2413Library', u'Adafruit DS2413 Library Documentation', + author, 'AdafruitDS2413Library', 'One line description of project.', + 'Miscellaneous'), +] diff --git a/examples/direct_access.py b/examples/direct_access.py new file mode 100644 index 0000000..81d1113 --- /dev/null +++ b/examples/direct_access.py @@ -0,0 +1,27 @@ +# This example shows how to directly access the DS2413. See the datasheet +# for details. This approach is only recommended for advanced use. For typical +# use, it is suggested to access the pins via the DS2413Pin objects. See the +# simple.py example. +import board +from adafruit_onewire.bus import OneWireBus +import adafruit_ds2413 + +# Create OneWire bus +ow_bus = OneWireBus(board.D2) + +# Create the DS2413 object from the first one found on the bus +ds = adafruit_ds2413.DS2413(ow_bus, ow_bus.scan()[0]) + +# Get the PIO logical status and report it together with the state of the +# PIO Output Latch +print("0b{:08b}".format(ds.pio_state)) + +# Control the output transistors. (ON = 0, OFF = 1) +# Turn off both transisotrs +ds.pio_state = 0x03 +# Turn on both transisotrs +ds.pio_state = 0x00 +# PIOA = on, PIOB = off +ds.pio_state = 0x02 +# PIOA = off, PIOB = on +ds.pio_state = 0x01 diff --git a/examples/simple.py b/examples/simple.py new file mode 100644 index 0000000..7afa733 --- /dev/null +++ b/examples/simple.py @@ -0,0 +1,32 @@ +# This example shows how to access the DS2413 pins and use them for both input +# and output. In this example, it is assumed an LED is attached to IOA and a +# button is attached to IOB. See the datasheet for details about how to +# interface the external hardware (it is different than most Arduino examples). +import time +import board +from adafruit_onewire.bus import OneWireBus +import adafruit_ds2413 + +# Create OneWire bus +ow_bus = OneWireBus(board.D2) + +# Create the DS2413 object from the first one found on the bus +ds = adafruit_ds2413.DS2413(ow_bus, ow_bus.scan()[0]) + +# LED on IOA +led = ds.IOA + +# button on IOB +button = ds.IOB +button.direction = adafruit_ds2413.INPUT + +# Loop forever +while True: + # Check for button press + if button.value: + # Print a message. + print("Button pressed!") + # Toggle LED + led.value = not led.value + # A little debounce + time.sleep(0.25) 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/requirements.txt b/requirements.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +