Skip to content

Commit

Permalink
Add mip support
Browse files Browse the repository at this point in the history
  • Loading branch information
mcauser committed Feb 16, 2024
1 parent 75fe94e commit 3b217b4
Show file tree
Hide file tree
Showing 9 changed files with 222 additions and 88 deletions.
112 changes: 93 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,114 @@
# MicroPython AM2320 I2C

A MicroPython library for interfacing with an [Aosong AM2320](http://www.aosong.com/products-32.html) temperature and humidity sensor over I2C.
A MicroPython library for interfacing with an [Aosong AM2320](http://www.aosong.com/en/products-41.html) temperature and humidity sensor over I2C.

This library focuses on using the I2C interface. The sensor also supports a 1-wire interface, available when pin 4 is connected to GND.

![demo](docs/AM2320.jpg)
![demo](docs/demo.jpg)

#### Examples

Basic measurement
## Installation

Using mip via mpremote:

```bash
$ mpremote mip install github:mcauser/micropython-am2320
$ mpremote mip install github:mcauser/micropython-am2320/examples
```

Using mip directly on a WiFi capable board:

```python
>>> import mip
>>> mip.install("github:mcauser/micropython-am2320")
>>> mip.install("github:mcauser/micropython-am2320/examples")
```

Manual installation:

Copy `src/am2320.py` to the root directory of your device.


## Examples

**Basic usage**

```python
import am2320
from machine import I2C, Pin
i2c = I2C(scl=Pin(5), sda=Pin(4))
import am2320

i2c = I2C(0)
sensor = am2320.AM2320(i2c)

sensor.measure()
print(sensor.temperature())
print(sensor.humidity())
```

Continuous measurement

```python
import time
import am2320
from machine import I2C, Pin
i2c = I2C(scl=Pin(5), sda=Pin(4))
sensor = am2320.AM2320(i2c)
## Methods

while True:
sensor.measure()
print(sensor.temperature())
print(sensor.humidity())
time.sleep_ms(4000)
```
### __init__(i2c)

As with other modern Aosong sensors, this sensor supports an I2C interface and can be found at address 0x5C.

### check()

Scans the I2C bus looking for the sensor at it's fixed I2C address 0x5C. Raises a OSError if not found.

### measure()

Reads the temperature and humidity from the sensor over the I2C bus and persists for subsequent calls to `temperature()` and `humidity()`.
Received bytes contains a checksum to ensure the data is error free, otherwise an exception is raised.

### temperature()

Returns the temperature in degrees Celsius from the data collected from the last `measure()` call.

### humidity()

Get the relative humidity as a percentage from the data collected from the last `measure()` call.

### _wake()

The sensor goes into sleep mode when idle to help minimise influencing the readings and requires writing a byte to wake it back up.
The write will fail, however the sensor interprets it as a wake up call.

### _crc16(buf)

A 16-bit cyclic redundancy check for verifying the received data is error free.


## Parts

* [AM2320](https://s.click.aliexpress.com/e/_DCcOdjL)
* [AM2320](https://s.click.aliexpress.com/e/_DeLEjAD)
* [TinyPICO](https://www.tinypico.com/)
* [WeMos D1 Mini](https://www.aliexpress.com/item/32529101036.html)


## Connections

AM2320 | TinyPICO (ESP32)
------ | ----------------
VIN | 3V3
SDA | 22
GND | GND
SCL | 21

AM2320 | Wemos D1 Mini (ESP8266)
------ | -----------------------
VIN | 3V3
SDA | GPIO4
GND | GND
SCL | GPIO5


## Links

* [micropython.org](http://micropython.org)
* [AM2320 datasheet](docs/AM2320.pdf)
* [TinyPICO Getting Started](https://www.tinypico.com/gettingstarted)


## License
Expand Down
69 changes: 0 additions & 69 deletions am2320.py

This file was deleted.

Binary file added docs/AM2320.pdf
Binary file not shown.
Binary file added docs/demo.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 22 additions & 0 deletions examples/basic_measurement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# SPDX-FileCopyrightText: 2016 Mike Causer <https://github.com/mcauser>
# SPDX-License-Identifier: MIT

"""
MicroPython Aosong AM2320 I2C driver
https://github.com/mcauser/micropython-am2320
Prints the temperature and humidity
"""

from machine import I2C, Pin
import am2320

i2c = I2C(0)
sensor = am2320.AM2320(i2c)

if sensor.check():
print(f"AM2320 found at I2C address {am2320.I2C_ADDRESS:#x}")

sensor.measure()
print(f"Temperature: {sensor.temperature()} C")
print(f"Humidity: {sensor.humidity()} RH")
24 changes: 24 additions & 0 deletions examples/continuous_measurement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# SPDX-FileCopyrightText: 2016 Mike Causer <https://github.com/mcauser>
# SPDX-License-Identifier: MIT

"""
MicroPython Aosong AM2320 I2C driver
https://github.com/mcauser/micropython-am2320
Prints the temperature and humidity every 4 sec
"""

from time import sleep_ms
from machine import I2C, Pin
import am2320

i2c = I2C(0)
sensor = am2320.AM2320(i2c)

if sensor.check():
print(f"AM2320 found at I2C address {am2320.I2C_ADDRESS:#x}")

while True:
sensor.measure()
print(f"Temperature: {sensor.temperature()} C, Humidity: {sensor.humidity()} RH")
sleep_ms(4000)
8 changes: 8 additions & 0 deletions examples/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"urls": [
["am2320/examples/basic_measurement.py", "github:mcauser/micropython-am2320/examples/basic_measurement.py"],
["am2320/examples/continuous_measurement.py", "github:mcauser/micropython-am2320/examples/continuous_measurement.py"]
],
"deps": [],
"version": "1.1.0"
}
7 changes: 7 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"urls": [
["am2320/__init__.py", "github:mcauser/micropython-am2320/src/am2320.py"]
],
"deps": [],
"version": "1.1.0"
}
68 changes: 68 additions & 0 deletions src/am2320.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# SPDX-FileCopyrightText: 2016 Mike Causer <https://github.com/mcauser>
# SPDX-License-Identifier: MIT

"""
MicroPython Aosong AM2320 I2C driver
https://github.com/mcauser/micropython-am2320
"""

from time import sleep_ms
from micropython import const

__version__ = "1.1.0"

I2C_ADDRESS = const(0x5C) # fixed I2C address


class AM2320:
def __init__(self, i2c):
self._i2c = i2c
self._buf = bytearray(8)

def check(self):
self._wake()
if self._i2c.scan().count(I2C_ADDRESS) == 0:
raise OSError(f"AM2320 not found at I2C address {I2C_ADDRESS:#x}")
return True

def measure(self):
buf = self._buf
# wake sensor
self._wake()
# read 4 registers starting at offset 0x00
self._i2c.writeto(I2C_ADDRESS, b"\x03\x00\x04")
# wait at least 1.5ms
sleep_ms(2)
# read data
self._i2c.readfrom_mem_into(I2C_ADDRESS, 0, buf)
crc = buf[6] | (buf[7] << 8)
if crc != self._crc16(buf[:-2]):
raise ValueError("Checksum error")

def temperature(self):
t = ((self._buf[4] & 0x7F) << 8 | self._buf[5]) * 0.1
if self._buf[4] & 0x80:
t = -t
return t

def humidity(self):
return (self._buf[2] << 8 | self._buf[3]) * 0.1

def _wake(self):
try:
self._i2c.writeto(I2C_ADDRESS, b"")
except OSError:
pass
sleep_ms(10)

def _crc16(self, buf):
crc = 0xFFFF
for c in buf:
crc ^= c
for _ in range(8):
if crc & 0x01:
crc >>= 1
crc ^= 0xA001
else:
crc >>= 1
return crc

0 comments on commit 3b217b4

Please sign in to comment.