Skip to content

Instantly share code, notes, and snippets.

@TayIorRobinson
Created October 22, 2023 00:53
Show Gist options
  • Save TayIorRobinson/4aa463edd953ef7ad03ef0746d2fad36 to your computer and use it in GitHub Desktop.
Save TayIorRobinson/4aa463edd953ef7ad03ef0746d2fad36 to your computer and use it in GitHub Desktop.
MicroPython MPRLS library
# MicroPython library for the Adafruit MPRLS/Honeywell MPR LS module.
# 22/10/2023 - Taylor Robinson (https://robins.one)
# Example:
"""
from machine import I2C, Pin
from mprls import MPRLS
i2c = I2C(id=1,sda=Pin(26),scl=Pin(27))
mprls = MPRLS(i2c)
print(mprls.getPressure())
"""
MPRLS_STATUS_POWERED = 0x40
MPRLS_STATUS_BUSY = 0x20
MPRLS_STATUS_FAILED = 0x04
MPRLS_STATUS_MATHSAT = 0x02
PSI_TO_HPA = 68.947572932
class MPRLS:
def __init__(self, i2c, address=0x18):
self._i2c = i2c
self._address = address
self._buffer = bytearray(4)
if not self.readStatus() & MPRLS_STATUS_POWERED:
raise RuntimeError("MPRLS not found")
def read(self):
"""
Reads the sensor's registers into the _buffer.
"""
self._i2c.readfrom_into(self._address, self._buffer)
def readStatus(self):
"""
Reads the status of the sensor.
"""
self.read()
return self._buffer[0]
def requestPressure(self):
"""
Requests that the sensor take a pressure reading.
"""
self._buffer[0] = 0xAA
self._buffer[1] = 0x00
self._buffer[2] = 0x00
self._i2c.writeto(self._address, self._buffer[0:3])
def readPressure(self, multi=PSI_TO_HPA):
"""
Reads pressure from the sensor.
Arguments:
multi: Multiplier to convert PSI to desired unit. Default is 68.947572932 to convert to hPa. Set to 1 to get PSI.
Returns:
- False if the sensor is busy
- -1 if there was an error
- or the pressure in the desired unit.
"""
status = self.readStatus()
if status & MPRLS_STATUS_BUSY:
return False
if status & MPRLS_STATUS_FAILED or status & MPRLS_STATUS_MATHSAT:
return -1
rawPSI = self._buffer[1] << 16 | self._buffer[2] << 8 | self._buffer[3]
psi = (rawPSI - 0x19999A) * 25
psi /= 0xE66666 - 0x19999A
return psi * multi
def getPressure(self, multi=PSI_TO_HPA):
"""
Requests pressure and waits for it to be ready.
Arguments:
multi: Multiplier to convert PSI to desired unit. Default is 68.947572932 to convert to hPa. Set to 1 to get PSI.
Returns:
Pressure in desired unit, or -1 if there was an error.
"""
self.requestPressure()
pres = self.readPressure(multi)
while pres == False:
pres = self.readPressure(multi)
return pres
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment