dht22.py 1.15 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import sensor
import dhtreader
import time
class DHT22(sensor.Sensor):
	requiredData = ["measurement","pinNumber"]
	optionalData = ["unit"]
	def __init__(self,data):
		dhtreader.init()
		dhtreader.lastDataTime = 0
		dhtreader.lastData = (None,None)
		self.sensorName = "DHT22"
		self.pinNum = int(data["pinNumber"])
		if "temp" in data["measurement"].lower():
			self.valName = "Temperature"
			self.valUnit = "Celsius"
			self.valSymbol = "C"
			if "unit" in data:
				if data["unit"]=="F":
rjlanc's avatar
rjlanc committed
19
					self.valUnit = "Fahrenheit"
20 21 22 23 24 25 26 27 28 29 30 31
					self.valSymbol = "F"
		elif "h" in data["measurement"].lower():
			self.valName = "Relative_Humidity"
			self.valSymbol = "%"
			self.valUnit = "% Relative Humidity"
		return

	def getVal(self):
		tm = dhtreader.lastDataTime
		if (time.time()-tm)<2:
			t, h = dhtreader.lastData
		else:
32
			tim = time.time()
33 34 35 36 37
			try:
				t, h = dhtreader.read(22,self.pinNum)
			except Exception:
				t, h = dhtreader.lastData
			dhtreader.lastData = (t,h)
38
			dhtreader.lastDataTime=tim
39 40 41 42 43 44 45
		if self.valName == "Temperature":
			temp = t
			if self.valUnit == "Fahrenheit":
				temp = temp * 1.8 + 32
			return temp
		elif self.valName == "Relative_Humidity":
			return h