GithubHelp home page GithubHelp logo

adafruit / adafruit_circuitpython_tlv493d Goto Github PK

View Code? Open in Web Editor NEW
2.0 20.0 4.0 106 KB

CircuitPython helper library for the TLV493D 3-axis magnetometer

License: MIT License

Python 100.00%
hacktoberfest

adafruit_circuitpython_tlv493d's Introduction

Introduction

Documentation Status Discord Build Status Code Style: Black

CircuitPython helper library for the TLV493D 3-axis magnetometer

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-tlv493d

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

sudo pip3 install adafruit-circuitpython-tlv493d

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-tlv493d

Usage Example

import time
import board
import adafruit_tlv493d

i2c = board.I2C()  # uses board.SCL and board.SDA
tlv = adafruit_tlv493d.TLV493D(i2c)

while True:
    print("X: %s, Y:%s, Z:%s uT"%tlv.magnetic)
    time.sleep(1)

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.

adafruit_circuitpython_tlv493d's People

Contributors

blepblorp avatar brianpugh avatar evaherrada avatar foamyguy avatar jposada202020 avatar kattni avatar ladyada avatar lubarb avatar markus-k avatar siddacious avatar sommersoft avatar tcfranks avatar tekktrik avatar

Stargazers

 avatar  avatar

Watchers

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

adafruit_circuitpython_tlv493d's Issues

Using 3 sensors

Hi there,

Thank you for this library and all the work which has gone into it! I am new to this and I am trying to get 3 TLV sensors to work. I have connected them all to the same bus, they are connected as per the data sheet. Decoupling caps etc all provided, all running at 3.3v connected to a raspberry pi pico.
I can get 2 sensors to work well and react sensibly to a magnet but not 3. The attached code produces 3 readouts but TLV 2 readout is just noise. The magnet moving over sensor 2 provides a readout for TLV reading 3. I am pretty sure this is not a hardware issue in terms of hookup, but an addressing issue. I however cannot make it work.

Any help would be greatly appreciated,

Thank you

`
import time
import board
import busio
import digitalio
import adafruit_tlv493d

Define i2c bus

i2c = busio.I2C(scl=board.GP1, sda=board.GP0)

Sensor 1 VCC

en_pin = digitalio.DigitalInOut(board.GP2)
en_pin.switch_to_output()

Sensor 2 VCC

en2_pin = digitalio.DigitalInOut(board.GP3)
en2_pin.switch_to_output()

Sensor 3 VCC

en3_pin = digitalio.DigitalInOut(board.GP4)
en3_pin.switch_to_output()

Power down sensors to start addressing sequence

en_pin.value = False
en2_pin.value = False
en3_pin.value = False
time.sleep(0.2)

Enable and configure sensor 1

en_pin.value = True
tlv = adafruit_tlv493d.TLV493D(i2c, addr_reg=1)
tlv = adafruit_tlv493d.TLV493D(i2c, address=0x5a, addr_reg=1)

Enable and configure sensor 2

en2_pin.value = True
tlv2 = adafruit_tlv493d.TLV493D(i2c, addr_reg=3)
tlv2 = adafruit_tlv493d.TLV493D(i2c, address=0x4a, addr_reg=3)

Enable and configure sensor 3

en3_pin.value = True
tlv3 = adafruit_tlv493d.TLV493D(i2c, addr_reg=0)
tlv3 = adafruit_tlv493d.TLV493D(i2c, address=0x5e, addr_reg=0)

while True:
print("Values")
print("X1: %s, Y1: %s, Z1: %s mT" % tlv.magnetic)
print("X2: %s, Y2: %s, Z2: %s mT" % tlv2.magnetic)
print("X3: %s, Y3: %s, Z3: %s mT" % tlv2.magnetic)
time.sleep(1)
`

Error connecting to board

From a Magtag, using:

import board
import busio
import adafruit_tlv493d

print("starting up")

# Hardware I2C setup:
i2c = busio.I2C(board.SCL, board.SDA)
tlv = adafruit_tlv493d.TLV493D(i2c)

I get an error when repeatedly connecting to the board (4366).

If instead I change the i2c setup to use
i2c = busio.I2C(board.SCL, board.SDA, frequency = 400000)
I can reconnect without trouble.

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_tlv493d.py:105
  • adafruit_tlv493d.py:137
  • adafruit_tlv493d.py:143
  • adafruit_tlv493d.py:169

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

Spikes in values read from the tlv493d magnetometer

Reading values from the tlv493d with no magnet near, most of the values returned are in the range of roughly +- .3 units, consistent with bit and noise levels from the spec sheet. However about 1-2% of the readings are roughly +- 1.5 units.

Screenshot 2021-03-16 095848

Logged with the following code:

import board
import math
import time
import wifi
import socketpool
import ssl
import json
import busio
import adafruit_tlv493d
import adafruit_minimqtt.adafruit_minimqtt as MQTT

DOOR_MQTT_TOPIC = "dryertest/door"

# Hardware I2C setup:

i2c = busio.I2C(board.SCL, board.SDA)
tlv = adafruit_tlv493d.TLV493D(i2c)

print("starting up")

# Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and
# "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other
# source control.
# pylint: disable=no-name-in-module,wrong-import-order
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!" % secrets["ssid"])

# Create a socket pool
pool = socketpool.SocketPool(wifi.radio)

# Set up a MiniMQTT Client
mqtt_client = MQTT.MQTT(
    broker=secrets["mqtt_broker"],
    port=secrets["mqtt_port"],
    username=secrets["mqtt_username"],
    password=secrets["mqtt_password"],
    socket_pool=pool,
    ssl_context=ssl.create_default_context(),
)

print("Attempting to connect to %s" % mqtt_client.broker)
mqtt_client.connect()

readcount = 0
badvalue = False

while True:
    door = tlv.magnetic
    door_output = {
    "x" : door[0],
    "y" : door[1],
    "z" : door[2],
    }

    readcount += 1

    if (abs(door[0]) > 1.0) :
        print("Outlier value (X) seen after ", readcount, " reads")
        badvalue = True
    if (abs(door[1]) > 1.0) :
        print("Outlier value (Y) seen after ", readcount, " reads")
        badvalue = True
    if (abs(door[2]) > 1.0) :
        print("Outlier value (Z) seen after ", readcount, " reads")
        badvalue = True
    if badvalue :
        badvalue = False
        readcount = 0

    print('.', end='')
    
    mqtt_client.publish(DOOR_MQTT_TOPIC, json.dumps(door_output))

    time.sleep(1)

This seems to be consistent across multiple sensor boards connected to a Magtag and to several Metro ESP32-S2 boards with several Stemma cables.

My most recent test is with a Magtag using Adafruit CircuitPython 6.2.0-beta.3 on 2021-03-04; Adafruit MagTag with ESP32S2 and libraries from 3/15/21 with the exception of a slightly edited adafruit_minimqtt.py (the library version crashes in the absence of logging, a pull request hadn't made it into the library release). I've also seen the behavior with the 6.1.0 release of CircuitPython and earlier libraries.

Also, in looking at the adafruit_tlv493d.py library, the init function sets up values to be written for control into a buffer before actually writing the values out over i2c.

        # setup MASTERCONTROLLEDMODE which takes a measurement for every read
        self._set_write_key("PARITY", 1)
        self._set_write_key("PARITY", 1)
        self._set_write_key("LOWPOWER", 1)
        self._set_write_key("LP_PERIOD", 1)
        self._write_i2c()

Looking at the code for _set_write_key, entering the PARITY value into the buffer twice is redundant. I can't figure out from the chip documentation whether this was just an inadvertent duplication or whether perhaps setting another different control bit was intended.

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.