81 lines
2.0 KiB
Python
81 lines
2.0 KiB
Python
class uPySensor:
|
|
def __init__(self):
|
|
dummy=''
|
|
|
|
def sleep_ms(self, delay):
|
|
from time import sleep_ms
|
|
sleep_ms(delay)
|
|
|
|
|
|
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()
|