Code Monkey home page Code Monkey logo

adafruit_circuitpython_ahtx0's Introduction

Introduction

Documentation Status

Discord

Build Status

Code Style: Black

CircuitPython driver for the Adafruit AHT10 or AHT20 Humidity and Temperature Sensor

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

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

sudo pip3 install adafruit-circuitpython-ahtx0

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

Usage Example

import time
import board
import adafruit_ahtx0

# Create sensor object, communicating over the board's default I2C bus
i2c = board.I2C()  # uses board.SCL and board.SDA
sensor = adafruit_ahtx0.AHTx0(i2c)

while True:
    print("\nTemperature: %0.1f C" % sensor.temperature)
    print("Humidity: %0.1f %%" % sensor.relative_humidity)
    time.sleep(2)

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_ahtx0's People

Contributors

blitzcitydiy avatar caternuson avatar demivis avatar evaherrada avatar foamyguy avatar jposada202020 avatar kattni avatar ladyada avatar tammymakesthings avatar tannewt avatar tekktrik avatar

Stargazers

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

adafruit_circuitpython_ahtx0's Issues

Calibrate Command not valid for newer ATH20

Relevant line:
https://github.com/adafruit/Adafruit_CircuitPython_AHTx0/blame/e7b71a57a769c57ce4efb95491dffc32e5940132/adafruit_ahtx0.py#L48

While trying to initialize a new AHT20 device ( shop link ) using a QT Py ESP32-S2 WiFi Dev Board with STEMMA QT ( shop link ) connected using a breadboard and wires (not STEMMA) between labelled QT Py SCL/SDA and AHT20 SCL/SDA, labeled GND pins connected, and AHT20 VIN tied to QT Py 3V I was getting an error using the above code library on intial call with the following traceback:

Traceback (most recent call last):
  File "code.py", line 46, in <module>
  File "adafruit_ahtx0.py", line 96, in __init__
  File "adafruit_ahtx0.py", line 114, in calibrate
OSError: [Errno 19] No such device

Upon further investigation using an analog discovery, I found the AHT20 was NACK-ing the first word of calibrate command (defined in this library as AHTX0_CMD_CALIBRATE).
Initial soft reboot:
Initial soft reboot
followed by NACK of Calibrate command first word:
NACK of Calibrate command

I tried various other things, including manually emulating the library step by step to find the issue, and continually got NACK on that first word. Digging into the AHT20 documentation, I found this document that shows a different calibrate word in section 5.4

  1. Wait 40ms after power-on. Before reading the temperature and humidity values, first check whether the calibration enable bit Bit [3] of the status word is 1 (you can get a byte of status word by sending 0x71). If not 1, need to send 0xbe command (for initialization), this command parameter has two bytes, the first byte is 0x08, the second byte is 0x00, and then wait for 10ms

I modified my manual recreation of this library to use 0xBE as the first word instead and it worked. So I downloaded this file directly, modified only line 48 (above) to read

AHTX0_CMD_CALIBRATE: int = const(0xBE)  # Calibration command

and the library works exactly as intended. Further calls to the returned object as shown in the guide work as expected for as long as I tested it.

I didn't want to submit a pull request as I'm not sure this update would be valid for all uses of the library, but wanted to report the issue I saw and subsequent solution.

Different initialization commands for AHT10 and AHT20

While porting the library to MicroPython I maybe found an issue with initialization commands. Your library uses 0xE1, which is right for the AHT10 according to the datasheet. The AHT20 expects 0xBE, see datasheet.
I found 0xE1 working well with the AHT10 and didn't have the chance to test with a AHT20, yet. Since Adafruit is also vendor of a AHT20 module, I am sure you have tested your library and maybe there is only some confusion in datasheets or simply both commands are working. Anyway it would be great, if you can have a look at that and share your thoughts with me.

Accuracy on FunHouse? (or temp compensation of RH via dew point?)

I've ported my air-quality code from Clue to FunHouse, and in the process looked at what the on-board AHT humidity sensor says compared to what the SCD30 says.

  • The AHT onboard says 18.2%RH at 40C
  • The SCD30 says 40.5%RH at 26.3C

I'm not sure if this is just the difference due to local heating of the sensor (relative humidity drops as temp rises, even if absolute humidity stays the same), or if there's an issue in the driver or something.

Hmm, according to https://bmcnoldy.rsmas.miami.edu/Humidity.html, the AHT's measurement is a dewpoint of 11.52, vs the scd30 of 11.82, which is pretty close - so probably the FunHouse (and other) guides that apply a temperature correction should also re-compute relative humidity. Might actually want to put the dew point calculations into a library of its own.

For reference, here's my setup - they're all basically right next to each other. The SCD data matches what I would expect from my other sensors around the house, which are a mix of HTU21D and SHT30D
image

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_ahtx0.py:81

AttributeError: 'module' object has no attribute 'AHTx0'

RaspberryPi Pico W, CircuitPython 8.1.0-beta.2, DHT20

Installing library:

$ circup install adafruit_ahtx0
Found device at /Volumes/CIRCUITPY, running CircuitPython 8.1.0-beta.2.
Searching for dependencies for: ['adafruit_ahtx0']
WARNING:
	typing-extensions is not a known CircuitPython library.
Ready to install: ['adafruit_ahtx0', 'adafruit_bus_device', 'adafruit_register']

'adafruit_ahtx0' is already installed.
'adafruit_bus_device' is already installed.
'adafruit_register' is already installed.

Example code:

>>> import board
>>> import busio
>>> import adafruit_ahtx0
>>> i2c = busio.I2C(scl=board.GP19, sda=board.GP18)
>>> sensor = adafruit_ahtx0.AHTx0(i2c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'AHTx0'

Recent AHT20 shipment Errno 19 (ENODEV) retrieving device status fails in ahtx0_simpletest.py

Ordered some new AHT20 breakout boards on 26 Nov 2023. The first two of these devices (others remain sealed) fail in status with CircuitPython 8.2.9 and Adafruit CircuitPython Bundle 20231205:

Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
code.py output:
Traceback (most recent call last):
  File "code.py", line 17, in <module>
  File "adafruit_ahtx0.py", line 96, in __init__
  File "adafruit_ahtx0.py", line 120, in calibrate
  File "adafruit_ahtx0.py", line 129, in status
OSError: [Errno 19] No such device

Code done running.

Expected output is:

Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
code.py output:

Temperature: 26.5 C
Humidity: 32.9 %

Temperature: 26.4 C
Humidity: 33.0 %

Temperature: 26.2 C
Humidity: 33.1 %

This is the line 129 in the library that is failing:

def status(self) -> int:
        """The status byte initially returned from the sensor, see datasheet for details"""
        with self.i2c_device as i2c:
            i2c.readinto(self._buf, start=0, end=1)  ### line 129
        # print("status: "+hex(self._buf[0]))
        return self._buf[0]

There are several revisions of the data sheet floating around on the internet. The one linked on the Adafruit Product site says the minimum wait time after power on is 100ms. Other documentation that I have found e.g., from Sparkfun indicate 20ms and a sample C program that I found on the manufacturer's product page waits 500ms after power-on.

I increased wait time to 110ms in a copy of adafruit_ahtx0.py, without any improvement in status reading. I also tried commenting out the self.reset() invocation in init() because the literature seems to indicate it might be unnecessary. Here is the snippet with my change:

    def __init__(
        self, i2c_bus: busio.I2C, address: int = AHTX0_I2CADDR_DEFAULT
    ) -> None:
        time.sleep(0.110)  # 20ms delay to wake up
        self.i2c_device = I2CDevice(i2c_bus, address)
        self._buf = bytearray(6)
#        self.reset()
        if not self.calibrate():
            raise RuntimeError("Could not calibrate")
        self._temp = None
        self._humidity = None

    def reset(self) -> None:
        """Perform a soft-reset of the AHT"""
        self._buf[0] = AHTX0_CMD_SOFTRESET
        with self.i2c_device as i2c:
            i2c.write(self._buf, start=0, end=1)
        time.sleep(0.110)  # 20ms delay to wake up

Let me know how I can help? More context in a forum thread here

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.