Skip to content

Adds in code from working repo #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 9, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -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 [email protected]. 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/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 Carter Nelson 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.
1 change: 0 additions & 1 deletion README.md

This file was deleted.

74 changes: 74 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@

Introduction
============

.. image:: https://readthedocs.org/projects/adafruit-circuitpython-CircuitPython_ADS1x15/badge/?version=latest
:target: https://circuitpython.readthedocs.io/projects/CircuitPython_ADS1x15/en/latest/
:alt: Documentation Status

.. image :: https://badges.gitter.im/adafruit/circuitpython.svg
:target: https://gitter.im/adafruit/circuitpython?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge
:alt: Gitter

Support for the ADS1x15 series of analog-to-digital converters. Available in 12-bit (ADS1015)
and 16-bit (ADS1115) versions.

Dependencies
=============
This driver depends on:

* `Adafruit CircuitPython <https://github.com/adafruit/circuitpython>`_
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is missing a link to Bus Device.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. Fixed.

* `Bus Device <https://github.com/adafruit/Adafruit_CircuitPython_BusDevice>`_

Please ensure all dependencies are available on the CircuitPython filesystem.
This is easily achieved by downloading
`the Adafruit library and driver bundle <https://github.com/adafruit/Adafruit_CircuitPython_Bundle>`_.

Usage Example
=============

Single Ended
------------

.. code-block:: python

import board
import busio
from adafruit_ads1x15.single_ended import ADS1015

i2c = busio.I2C(board.SCL, board.SDA)
adc = ADS1015(i2c)
while True:
# channel 0
print(adc[0].value, adc[0].volts)

Differential
------------

.. code-block:: python

import board
import busio
from adafruit_ads1x15.differential import ADS1015

i2c = busio.I2C(board.SCL, board.SDA)
adc = ADS1015(i2c)
while True:
# channel 0 - channel 1
print(adc[(0,1)].value, adc[(0,1)].volts)


Contributing
============

Contributions are welcome! Please read our `Code of Conduct
<https://github.com/adafruit/Adafruit_CircuitPython_CircuitPython_ADS1x15/blob/master/CODE_OF_CONDUCT.md>`_
before contributing to help this project stay welcoming.

API Reference
=============

.. toctree::
:maxdepth: 2

api
219 changes: 219 additions & 0 deletions adafruit_ads1x15/adafruit_ads1x15.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
# The MIT License (MIT)
#
# Copyright (c) 2017 Carter Nelson 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__ads1x15`
====================================================

CircuitPython driver for ADS1015/1115 ADCs.

* Author(s): Carter Nelson
"""
import time
from micropython import const
from adafruit_bus_device.i2c_device import I2CDevice

# Register and other configuration values:
ADS1x15_DEFAULT_ADDRESS = const(0x48)
ADS1x15_POINTER_CONVERSION = const(0x00)
ADS1x15_POINTER_CONFIG = const(0x01)
ADS1x15_POINTER_LOW_THRESHOLD = const(0x02)
ADS1x15_POINTER_HIGH_THRESHOLD = const(0x03)
ADS1x15_CONFIG_OS_SINGLE = const(0x8000)
ADS1x15_CONFIG_MUX_OFFSET = const(12)
# Maping of gain values to config register values.
ADS1x15_CONFIG_GAIN = {
2/3: 0x0000,
1: 0x0200,
2: 0x0400,
4: 0x0600,
8: 0x0800,
16: 0x0A00
}
ADS1x15_PGA_RANGE = {
2/3: 6.144,
1: 4.096,
2: 2.048,
4: 1.024,
8: 0.512,
16: 0.256
}
ADS1x15_CONFIG_MODE_CONTINUOUS = const(0x0000)
ADS1x15_CONFIG_MODE_SINGLE = const(0x0100)
# Mapping of data/sample rate to config register values for ADS1015 (faster).
ADS1015_CONFIG_DR = {
128: 0x0000,
250: 0x0020,
490: 0x0040,
920: 0x0060,
1600: 0x0080,
2400: 0x00A0,
3300: 0x00C0
}
# Mapping of data/sample rate to config register values for ADS1115 (slower).
ADS1115_CONFIG_DR = {
8: 0x0000,
16: 0x0020,
32: 0x0040,
64: 0x0060,
128: 0x0080,
250: 0x00A0,
475: 0x00C0,
860: 0x00E0
}
ADS1x15_CONFIG_COMP_WINDOW = const(0x0010)
ADS1x15_CONFIG_COMP_ACTIVE_HIGH = const(0x0008)
ADS1x15_CONFIG_COMP_LATCHING = const(0x0004)
ADS1x15_CONFIG_COMP_QUE = {
1: 0x0000,
2: 0x0001,
4: 0x0002
}
ADS1x15_CONFIG_COMP_QUE_DISABLE = const(0x0003)
ADS1x15_DIFF_CHANNELS = {
(0,1): 0,
(0,3): 1,
(1,3): 2,
(2,3): 3
}

class ADC_Channel(object):
"""Provides per channel access to ADC readings."""

def __init__(self, adc, channel):
self._adc = adc
self._channel = channel

@property
def value(self, ):
"""ADC reading in raw counts."""
return self._adc._read_channel(self._channel)

@property
def volts(self, ):
"""ADC reading in volts."""
return self._adc._read_channel_volts(self._channel)


class ADS1x15(object):
"""Base functionality for ADS1x15 analog to digital converters."""

def __init__(self, i2c, address=ADS1x15_DEFAULT_ADDRESS, **kwargs):
self.buf = bytearray(3)
self.i2c_device = I2CDevice(i2c, address)
self.bits = None
self._channels = [ADC_Channel(self, 0),
ADC_Channel(self, 1),
ADC_Channel(self, 2),
ADC_Channel(self, 3)]

def _data_rate_default(self):
"""Retrieve the default data rate for this ADC (in samples per second).
Should be implemented by subclasses.
"""
raise NotImplementedError('Subclasses must implement _data_rate_default!')

def _data_rate_config(self, data_rate):
"""Subclasses should override this function and return a 16-bit value
that can be OR'ed with the config register to set the specified
data rate. If a value of None is specified then a default data_rate
setting should be returned. If an invalid or unsupported data_rate is
provided then an exception should be thrown.
"""
raise NotImplementedError('Subclass must implement _data_rate_config function!')

def _conversion_value(self, low, high):
"""Subclasses should override this function that takes the low and high
byte of a conversion result and returns a signed integer value.
"""
raise NotImplementedError('Subclass must implement _conversion_value function!')

def _read_channel(self, channel):
"""Subclasses should override this function to return a value for the
requested channels as a signed integer value.
"""
raise NotImplementedError('Subclass must implement _read_channel function!')

def _read_channel_volts(self, channel):
"""Subclasses should override this function to return a value for the
requested channels as a float value.
"""
raise NotImplementedError('Subclass must implement _read_channel_volts function!')

def _read(self, mux, gain, data_rate, mode):
"""Perform an ADC read with the provided mux, gain, data_rate, and mode
values. Returns the signed integer result of the read.
"""
config = ADS1x15_CONFIG_OS_SINGLE # Go out of power-down mode for conversion.
# Specify mux value.
config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET
# Validate the passed in gain and then set it in the config.
if gain not in ADS1x15_CONFIG_GAIN:
raise ValueError('Gain must be one of: 2/3, 1, 2, 4, 8, 16')
config |= ADS1x15_CONFIG_GAIN[gain]
# Set the mode (continuous or single shot).
config |= mode
# Get the default data rate if none is specified (default differs between
# ADS1015 and ADS1115).
if data_rate is None:
data_rate = self._data_rate_default()
# Set the data rate (this is controlled by the subclass as it differs
# between ADS1015 and ADS1115).
config |= self._data_rate_config(data_rate)
config |= ADS1x15_CONFIG_COMP_QUE_DISABLE # Disble comparator mode.
# Send the config value to start the ADC conversion.
# Explicitly break the 16-bit value down to a big endian pair of bytes.
self.buf[0] = ADS1x15_POINTER_CONFIG
self.buf[1] = (config >> 8) & 0xFF
self.buf[2] = config & 0xFF
with self.i2c_device as i2c:
i2c.write(self.buf)
# Wait for the ADC sample to finish based on the sample rate plus a
# small offset to be sure (0.1 millisecond).
time.sleep(1.0/data_rate+0.0001)
# Retrieve the result.
self.buf[0] = ADS1x15_POINTER_CONVERSION
i2c.write(self.buf, end=1, stop=False)
i2c.read_into(self.buf, start=1)
return self._conversion_value(self.buf[2], self.buf[1])

def stop_adc(self):
"""Stop all continuous ADC conversions (either normal or difference mode).
"""
# Set the config register to its default value of 0x8583 to stop
# continuous conversions.
self.buf[0] = ADS1x15_POINTER_CONFIG
self.buf[1] = 0x85
self.buf[2] = 0x83
with self.i2c_device as i2c:
i2c.write(self.buf)

def get_last_result(self):
"""Read the last conversion result when in continuous conversion mode.
Will return a signed integer value.
"""
# Retrieve the conversion register value, convert to a signed int, and
# return it.
self.buf[0] = ADS1x15_POINTER_CONVERSION
with self.i2c_device as i2c:
i2c.write(self.buf, end=1, stop=False)
i2c.read_into(self.buf, start=1)
return self._conversion_value(self.buf[2], self.buf[1])
Loading