Software source reference
"""
Contains some helper functions to initialize and communicate with SHT45 sensor,
which measures the heat and the humidity.
Authos:
Min Tai Yap
"""
import board
import adafruit_sht4x
import busio
import time
import asyncio
from adafruit_blinka.microcontroller.bcm283x.pin import Pin
# Initialize the sensor once and reuse it across multiple reads
[docs]
async def init_sht45(i2c):
"""
Initializes the SHT45 sensor with heating disabled and high precision enabled.
:param i2c: A busio.I2C object for the communication on the I2C bus
:returns: An adafruit_sht4x.SHT4x driver object for the SHT45 sensor upon successful initialization, otherwise None
"""
try:
sht = adafruit_sht4x.SHT4x(i2c)
sht.mode = adafruit_sht4x.Mode.NOHEAT_HIGHPRECISION
print("SHT45 sensor initialized.")
return sht
except Exception as e:
print(f"Failed to initialize SHT45: {e}")
return None
[docs]
async def sht45_read(sht):
"""
Reads temperature and humidity from the SHT45 sensor. For more consistent data collection,
a waiting time of 0.1 seconds is incurred before reading.
:param sht: An adafruit_sht4x.SHT4x driver object
:returns: The temperature reading in °C and the humidity in % upon successful reading, otherwise -1 repeated twice
"""
# Ensure a 0.1-second delay before reading SHT45
await asyncio.sleep(0.1)
if sht is None:
print("Sensor not initialized.")
return -1, -1
try:
sht_temp = sht.temperature
sht_rh = sht.relative_humidity
print(f'SHT45 Temperature: {sht_temp:.2f} °C, Humidity: {sht_rh:.2f} %')
return sht_temp, sht_rh
except Exception as e:
print(f"Error reading from SHT45: {e}")
return -1, -1
