Giter Site home page Giter Site logo

adafruit / adafruit_circuitpython_apds9960 Goto Github PK

View Code? Open in Web Editor NEW

This project forked from mrmcwethy/adafruit_circuitpython_apds9960

10.0 18.0 17.0 192 KB

Adafruit Bundle driver for APSD9960 Gesture breakout board

License: MIT License

Python 100.00%
circuitpython hacktoberfest

adafruit_circuitpython_apds9960's Introduction

Introduction

Documentation Status Discord Build Status Code Style: Black

The APDS-9960 is a specialized chip that detects hand gestures, proximity and ambient light color over I2C. Its available from Adafruit as a breakout and as a built-in sensor on several Adafruit development boards.

This driver provides easy access to proximity, gesture and color data from the APDS-9960 sensor with a minimal footprint to allow it to work on all CircuitPython platforms.

Installation and Dependencies

This driver depends on:

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

On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally from PyPI.

To install for current user:

pip3 install adafruit-circuitpython-apds9960

To install system-wide (this may be required in some cases):

sudo pip3 install adafruit-circuitpython-apds9960

To install in a virtual environment in your current project:

mkdir project-name && cd project-name
python3 -m venv .venv
source .venv/bin/activate
pip3 install adafruit-circuitpython-apds9960

Usage Example

import board
import digitalio
from adafruit_apds9960.apds9960 import APDS9960

i2c = board.I2C()
int_pin = digitalio.DigitalInOut(board.D5)
int_pin.switch_to_input(pull=digitalio.Pull.UP)
apds = APDS9960(i2c)

apds.enable_proximity_interrupt = True
apds.proximity_interrupt_threshold = (0, 175)
apds.enable_proximity = True

while True:
    if not int_pin.value:
        print(apds.proximity)
        apds.clear_interrupt()

Hardware Set-up

If you're using a board with a built-in APDS-9960, no hardware setup will be required.

If you're using a breakout board via the pin header, connect Vin to a 3.3 V or 5 V power source, connect GND to ground, then connect SCL and SDA to the appropriate pins.

Optionally, if you'd like to use the sensor's interrupt pin connect INT to any available digital I/O pin.

Basics

To get started, import board and, and this library:

import board
from adafruit_apds9960.apds9960 import APDS9960

To set up the sensor to gather data, initialize the I2C bus via board.I2C() then initialize the APDS-9960 library.

i2c = board.I2C()
apds = APDS9960(i2c)

Proximity

To get a proximity result, enable the proximity engine then read the proximity value.

This will return a value between 0 and 255, with higher values indicating that something is close to the sensor.

apds.enable_proximity = True

while True:
  print(apds.proximity)

Gestures

First, enable both the proximity and gesture engines. The gesture engine relies on the proximity engine to determine when to start itself up and, as a result, proximity readings won't be reliable while the gesture engine is enabled.

To get a gesture, use the gesture() function to see if a gesture has been detected. If a value greater than 0 is returned, a gesture has been detected.

# Uncomment and set the rotation if depending on how your sensor is mounted.
# apds.rotation = 270 # 270 for CLUE

apds.enable_proximity = True
apds.enable_gesture = True

while True:
  gesture = apds.gesture()
  if gesture == 1:
    print("up")
  if gesture == 2:
    print("down")
  if gesture == 3:
    print("left")
  if gesture == 4:
    print("right")

Color/Light Measurement

To get a color measurement, first enable the color/light engine, wait for color data to arrive, then read the color_data values.

apds.enable_color = True

while True:
    while not apds.color_data_ready:
        time.sleep(0.005)

    r, g, b, c = apds.color_data
    print("r: {}, g: {}, b: {}, c: {}".format(r, g, b, c))

Interrupt Pin

This sensor has an interrupt pin can be asserted (pulled low) if proximity is detected outside of a specified window of values.

For boards with a built-in APDS-9960 this interupt pin will already be defined. For example, on the Clue and Feather nRF52840 Sense boards this pin is mapped to board.PROXIMITY_LIGHT_INTERRUPT and on the Proximity Trinkey it is mapped to board.INTERRUPT.

int_pin = digitalio.DigitalInOut(board.D5)
int_pin.switch_to_input(pull=digitalio.Pull.UP)

Proximity Detection

With the interrupt pin set up we can define a threshold and enable the assertion of the sensor's interrupt pin by the proximity engine before enabling the proximity engine itself.

In this configuration, the sensor's interrupt pin will be asserted when an object is close to the sensor. After checking on the interrupt it can be cleared using clear_interrupt()

apds.enable_proximity = True

# set the interrupt threshold to fire when proximity reading goes above 175
apds.proximity_interrupt_threshold = (0, 175)

# assert interrupt pin on internal proximity interrupt
apds.enable_proximity_interrupt = True

# enable the sensor's proximity engine
apds.enable_proximity = True

while True:
  if not interrupt_pin.value:
    print(apds.proximity)

    # clear the interrupt
    apds.clear_interrupt()

Initiaization Options

By default, when the driver is initialized, the APDS-9960 sensor's internal settings are reset and sensible defaults are applied to several low-level settings that should work well for most use cases.

If either the "reset" or "set defaults" behaviors (or both) aren't desired, they can be individually disabled via init kwargs.

apds = APDS9960(i2c, reset=False, set_defaults=False)

Documentation

API documentation for this library can be found on Read the Docs.

For information on building library documentation, please check out this guide.

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-travis-build-tools package.

Once installed, make sure you are in the virtual environment:

Then run the build:

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):

python3 -m venv .venv
source .venv/bin/activate
pip install Sphinx sphinx-rtd-theme

Now, once you have the virtual environment activated:

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.

adafruit_circuitpython_apds9960's People

Contributors

askpatrickw avatar bablokb avatar brennen avatar caternuson avatar dertobias avatar dhalbert avatar evaherrada avatar fivesixzero avatar foamyguy avatar jepler avatar jerryneedell avatar jposada202020 avatar kattni avatar ladyada avatar makermelissa avatar mrmcwethy avatar s-light avatar sommersoft avatar tannewt avatar tekktrik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adafruit_circuitpython_apds9960's Issues

integration_time property uses raw sensor values and differs to C/Arduino library

The C/Arduino library has a method called setADCIntegrationTime which takes a uint16_t iTimeMS and converts it into values that the APDS9660 uses, full code can be seen here https://github.com/adafruit/Adafruit_APDS9960/blob/master/Adafruit_APDS9960.cpp#L130-L149 (NB that code does not do a particularly explicit conversion from FP to (8 bit) integer).

The CircuitPython library currently just sends the raw value but the property is a bit misleading and called integration_time. The library defaults this to 0x01 which translates to (256 - 1) * 2.78ms = 708.9ms.

I'm not sure if this should be corrected to match the Arduino library with its more intuitive and user-friendly values? Changing this value now would disrupt existing users as there's no (clean!) way to code this with the existing property name. Is there a way to code this to happen in CP 5+ libraries only? Is that a good approach?

Add gesture rotation

The APDS9960 is rotated 90 degrees on the CLUE, therefore the gestures are off by 90 degrees.

Add the ability to compensate for sensor rotation by including gesture rotation.

The other capabilities of the sensor are not affected by rotation.

gesture_proximity_threshold default causes prox value to lock at 51

From @dastels in #16:
Related: gestures being triggered (prox > gesture_proximity_threshold) freeze the returned proximity value. E.g. if the threshold is at the default 50, the returned proximity value to 'lock in' when it reaches 51. Setting the threshold to 255 allows proximity to work property throughout it's full 0-255 range.

integration_time equation possibly incorrect

From @kevinjwalters in #16:
FYI, If the RGBC values are of interest, the current defauls set the ADC Integration Time Register (0x81) register to 0x01 which equates to 708.9ms integration time giving updates only ~ 1.4Hz. Page 20 of the datasheet has a slight error on how this value is treated, it says 256 - TIME / 2.78 ms. I'm pretty sure it means (256 - TIME) * 2.78. There's an integration_time property which can be used to adjust this.

I've also noticed clue.color() values getting "stuck" on REPL on the CLUE but I've only seen this once. foamyguy on discord has also seen this.

What is a 'clear' color value?

From the Adafruit documentation:

read the color_data property to retrieve the red, green, blue, and clear color values as a 4-tuple of 16-bit values โ€ฆ

I can't, for the life of me, figure out what a "clear" color value or "clear light" refers to! Deep googling yields information about Tibetan Bhuddism and a psychedelic rock band from the 1960s.

Thanks in advance.

Proximity/Color enable

The CLUE module sets the sensor object's enable_color and enable_proximity to true before asking for the related data. It never sets them to false. More interestingly I don't see where in the sensor code those values get propagated to the sensor enable register, although they do get initialized from the register value.

no method for setting pgain/ggain

I know that the policy for this lib is to not expose all registers to keep the footprint small. But I think it really needs methods for setting the proximity-gain (PGAIN) and gesture-gain (GGAIN). The default is 1x and 4x respectively. With this setting, proximity detection kicks in at a distance below an inch (at least for my sensor), which makes the driver almost useless.

The lib already has a setter/getter for the color-gain (AGAIN), and I would provide a patch with similar methods for the PGAIN/GGAIN settings if you also think this is a useful addition.

DisplayIO Example Wanted

Add a Basic DisplayIO Based Example

We would like to have a basic displayio example for this library. The example should be written for microcontrollers with a built-in display. At a minimum it should show a Label on the display and update it with live readings from the sensor.

The example should not be overly complex, it's intended to be a good starting point for displayio based projects that utilize this sensor library. Try to keep all visual content as near to the top left corner as possible in order to best fascilitate devices with small built-in display resolutions.

The new example should follow the naming convention examples/libraryname_displayio_simpletest.py with "libraryname" being replaced by the actual name of this library.

You can find an example of a Pull Request that adds this kind of example here: adafruit/Adafruit_CircuitPython_BME680#72

We have a guide that covers the process of contributing with git and github: https://learn.adafruit.com/contribute-to-circuitpython-with-git-and-github

If you're interested in contributing but need additional help, or just want to say hi, feel free to join the Discord server to ask questions: https://adafru.it/discord

"interrupt_pin" constructor arg causes error, internal "_interrupt_pin" var is never used

The class doc states that it expects a Pin but, when given a Pin object, the library throws this error:

>>> light = APDS9960(i2c, interrupt_pin=board.PROXIMITY_LIGHT_INTERRUPT)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "adafruit_apds9960/apds9960.py", line 155, in __init__
AttributeError: 'Pin' object has no attribute 'switch_to_input'

Since this internal variable is never used it may be best to just remove it.

Missing Type Annotations

There are missing type annotations for some functions in this library.

The typing module does not exist on CircuitPython devices so the import needs to be wrapped in try/except to catch the error for missing import. There is an example of how that is done here:

try:
    from typing import List, Tuple
except ImportError:
    pass

Once imported the typing annotations for the argument type(s), and return type(s) can be added to the function signature. Here is an example of a function that has had this done already:

def wrap_text_to_pixels(
    string: str, max_width: int, font=None, indent0: str = "", indent1: str = ""
) -> List[str]:

If you are new to Git or Github we have a guide about contributing to our projects here: https://learn.adafruit.com/contribute-to-circuitpython-with-git-and-github

There is also a guide that covers our CI utilities and how to run them locally to ensure they will pass in Github Actions here: https://learn.adafruit.com/creating-and-sharing-a-circuitpython-library/check-your-code In particular the pages: Sharing docs on ReadTheDocs and Check your code with pre-commit contain the tools to install and commands to run locally to run the checks.

If you are attempting to resolve this issue and need help, you can post a comment on this issue and tag both @FoamyGuy and @kattni or reach out to us on Discord: https://adafru.it/discord in the #circuitpython-dev channel.

The following locations are reported by mypy to be missing type annotations:

  • adafruit_apds9960/colorutility.py:18
  • adafruit_apds9960/colorutility.py:43
  • adafruit_apds9960/apds9960.py:138
  • adafruit_apds9960/apds9960.py:215
  • adafruit_apds9960/apds9960.py:229
  • adafruit_apds9960/apds9960.py:234
  • adafruit_apds9960/apds9960.py:332
  • adafruit_apds9960/apds9960.py:365
  • adafruit_apds9960/apds9960.py:381
  • adafruit_apds9960/apds9960.py:399
  • adafruit_apds9960/apds9960.py:403
  • adafruit_apds9960/apds9960.py:411
  • adafruit_apds9960/apds9960.py:418
  • adafruit_apds9960/apds9960.py:426

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.