Skip to content
This repository was archived by the owner on Sep 30, 2019. It is now read-only.

Commit b239f83

Browse files
committed
Simple ctypes wrapper for C library.
1 parent e20e41d commit b239f83

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Adafruit_DHT_Driver/DHT_Wrapper.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import ctypes
2+
from decimal import *
3+
4+
5+
class DHT(object):
6+
"""
7+
Wrapper for Adafruit DHT11/DHT22/AM2302 sensor Raspberry Pi driver.
8+
"""
9+
def __init__(self, sensor, pin):
10+
"""
11+
Initialize with sensor type as string and pin Raspberry Pi pin number as integer
12+
"""
13+
self.DHTlib = ctypes.CDLL("./libAdafruit_DHT.so")
14+
if not self.DHTlib.init():
15+
raise IOError("Could not initialise BCM2835 - may need to run as root")
16+
self.sensor = self.DHTlib.parseType(ctypes.c_char_p(sensor))
17+
self.pin = ctypes.c_int(pin)
18+
self.DHTlib.readDHT.restype = ctypes.POINTER(ctypes.c_float)
19+
def read(self):
20+
"""
21+
Returns a dict of decimals representing measured temperature and humidity
22+
"""
23+
r = self.DHTlib.readDHT(self.sensor, self.pin, ctypes.c_int(0))
24+
if r[1] > 0:
25+
q = Decimal("0.1")
26+
return {"temp": Decimal(r[0]).quantize(q), "hum":Decimal(r[1]).quantize(q)}
27+
else:
28+
return False
29+

0 commit comments

Comments
 (0)