-
Notifications
You must be signed in to change notification settings - Fork 3
/
chirp.py
94 lines (77 loc) · 2.36 KB
/
chirp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from machine import Pin, I2C
from time import sleep
class Chirp:
def __init__(self, bus, address=0x20, min_moist=250, max_moist=800):
self.i2c = bus
self.address = address
self.min_moist = min_moist
self.max_moist = max_moist
def _bytes_to_int(self, bytes):
result = 0
for b in bytes:
result = result * 256 + int(b)
return result
def _int_to_bytes(self, value, length):
result = []
for i in range(0, length):
result.append(value >> (i * 8) & 0xff)
result.reverse()
return result
def get_reg(self, reg, lenght=2):
val = self.i2c.readfrom_mem(self.address, reg, lenght)
return self._bytes_to_int(val)
@property
def sensor_address(self):
return self.get_reg(0x02, 1)
def reset(self):
print("Resetting")
val = self._int_to_bytes(0, 1)
self.i2c.writeto_mem(self.address, 0x06, bytearray(val))
sleep(5)
print("Resetted")
def set_address(self, new_addr):
addr = self._int_to_bytes(new_addr, 1)
self.i2c.writeto_mem(self.address, 0x01, bytearray(addr))
self.i2c.writeto_mem(self.address, 0x01, bytearray(addr))
self.reset()
self.address = new_addr
# Not tested
def sleep(self):
self.i2c.writeto(self.address, bytearray(self._int_to_bytes(0x08, 1)))
def wake_up(self, wake_time=1):
try:
self.version()
except:
pass
sleep(wake_time)
@property
def version(self):
return self.get_reg(7, 1)
@property
def busy(self):
busy = self.get_reg(9, 1)
if busy == 1:
return True
else:
return False
@property
def moisture(self):
return self.get_reg(0, 2)
@property
def temperature(self):
return self.get_reg(5, 2)/10
def light(self):
self.i2c.writeto_mem(self.address, 0x03,
bytearray(self._int_to_bytes(0, 1)))
sleep(1.5)
return self.get_reg(4, 2)
@property
def moist_percent(self):
moisture = self.moisture
hum = round((((moisture - self.min_moist)*100) /
(self.max_moist-self.min_moist)), 1)
if hum > 100:
return 100
if hum < 0:
return 0
return hum