uPyLibs/uPySensor.py

120 lines
3.1 KiB
Python
Raw Normal View History

2018-05-31 15:04:58 +01:00
class uPySensor:
def __init__(self):
dummy=''
def sleep_ms(self, delay):
from time import sleep_ms
sleep_ms(delay)
2018-05-31 20:46:29 +01:00
class BME280(uPySensor):
import bme280
BME280_ADDRESS = 0x76
def __init__(self, i2c):
self.i2c = i2c
self.handle = self.bme280.BME280(i2c=self.i2c)
def update_sensor(self):
t, p, h = self.handle.values
self.temperature = float(t[:-1])
self.pressure = float(p[:-3])
self.humidity = float(h[:-1])
def read_tempC(self):
self.update_sensor()
return self.temperature
def read_hum(self):
self.update_sensor()
return self.humidity
def read_pressure(self):
self.update_sensor()
return self.pressure
2018-05-31 20:46:29 +01:00
class DS18B20(uPySensor):
def __init__(self, onewire):
from ds18x20 import DS18X20
self.bus=onewire
self.bus_filter=DS18X20(self.bus)
if len(self.bus_filter.scan()) == 0: raise IOError("No DS18B20 sensors found on OneWire bus")
self.sensor=self.bus_filter.scan()[0]
def read_tempC(self):
self.bus_filter.convert_temp()
self.sleep_ms(300)
return self.bus_filter.read_temp(self.sensor)
2018-05-31 15:04:58 +01:00
class LM75A(uPySensor):
LM75A_ADDRESS = 0x48
def __init__(self, i2c):
self.i2c = i2c
def readbyte(self):
return self.i2c.readfrom(self.LM75A_ADDRESS, 1)
def readbytes(self, num):
return self.i2c.readfrom(self.LM75A_ADDRESS, num)
def read_tempC(self):
import math
data = self.readbytes(2)
return float("%d.%d" % (int(data[0]), math.floor(int(data[1])/23)))
class SHT21(uPySensor):
SOFT_RESET = 0xfe
SHT21_ADDRESS = 0x40
TRIG_TEMP_NO_HOLD = 0xf3
TRIG_HUM_NO_HOLD = 0xf5
def writebyte(self, byte):
self.i2c.writeto(self.SHT21_ADDRESS, bytearray([byte]))
def readbyte(self):
return self.i2c.readfrom(self.SHT21_ADDRESS, 1)
def readbytes(self, num):
return self.i2c.readfrom(self.SHT21_ADDRESS, num)
def __init__(self, i2c):
self.i2c = i2c
self.writebyte(self.SOFT_RESET)
self.sleep_ms(15)
def read_tempC(self):
self.writebyte(self.TRIG_TEMP_NO_HOLD)
self.sleep_ms(250)
data = self.readbytes(2)
return self._buffer_to_tempC(data)
def read_hum(self):
self.writebyte(self.TRIG_HUM_NO_HOLD)
self.sleep_ms(250)
data = self.readbytes(2)
return self._buffer_to_hum(data)
def _buffer_to_tempC(self, buf):
unadj = (buf[0] << 8) + buf[1]
unadj *= 175.72
unadj /= 1 << 16
unadj -= 46.85
return unadj
def _buffer_to_hum(self, buf):
unadj = (buf[0] << 8) + buf[1]
unadj *= 125
unadj /= 1 << 16
unadj -= 6
return unadj
def close(self):
self.i2c.close()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()