Browse Source

first commit

master
manfraid 1 year ago
commit
a054784cd1

+ 1
- 0
.gitignore View File

@@ -0,0 +1 @@
1
+composant.txt

+ 19
- 0
__list.py View File

@@ -0,0 +1,19 @@
1
+import os
2
+import sys
3
+
4
+
5
+def _list_fs(path=""):
6
+    try:
7
+        l = os.listdir(path)
8
+        if path:
9
+            sys.stdout.write(path + "/\n")
10
+        else:
11
+            sys.stdout.write("###\n")
12
+        for x in l:
13
+            _list_fs(x)
14
+        sys.stdout.write("/\n")
15
+    except OSError:
16
+        # Is file
17
+        sys.stdout.write(path + "\n")
18
+
19
+_list_fs()

+ 41
- 0
function.py View File

@@ -0,0 +1,41 @@
1
+import esp
2
+
3
+def dsleeps(s):
4
+    print("Sleep for {}s".format(s))
5
+    esp.deepsleep(1000000 * s)
6
+
7
+def dsleepm(m):
8
+    if m > 71:
9
+        print("Limite de temps a 71m")
10
+        dur = 71*60
11
+    else:
12
+        dur = m * 60
13
+    esp.deepsleep(1000000 * dur)
14
+
15
+
16
+def connect():
17
+    import network
18
+
19
+    ssid      = "nomReseauWiFi"
20
+    password  =  "motDePasseWiFi"
21
+
22
+    station = network.WLAN(network.STA_IF)
23
+
24
+    if station.isconnected() == True:
25
+        print("Already connected")
26
+        return
27
+
28
+    station.active(True)
29
+    station.connect()
30
+
31
+    while station.isconnected() == False:
32
+        pass
33
+
34
+    print("Connection successful")
35
+    print(station.ifconfig())
36
+
37
+def disconnect():
38
+    import network
39
+    station = network.WLAN(network.STA_IF)
40
+    station.disconnect()
41
+    station.active(False)

+ 8
- 0
list_ssid.py View File

@@ -0,0 +1,8 @@
1
+#List_ssid
2
+import network
3
+
4
+sta_if = network.WLAN(network.STA_IF)
5
+
6
+sta_if.active(True)
7
+
8
+print(sta_if.scan())

+ 56
- 0
test.py View File

@@ -0,0 +1,56 @@
1
+import network
2
+
3
+D0 = 16
4
+D1 = 5
5
+D2 = 4
6
+D3 = 0
7
+D4 = 2
8
+D5 = 14
9
+D6 = 12
10
+D7 = 13
11
+D8 = 15
12
+
13
+
14
+sta_if = network.WLAN(network.STA_IF)
15
+ap_if = network.WLAN(network.AP_IF)
16
+
17
+sta_if.active(True)
18
+sta_if.active()
19
+
20
+
21
+ap_if.active()
22
+
23
+ap_if.ifconfig()
24
+
25
+sta_if.connect('SSID','MDP')
26
+sta_if.isconnected()
27
+sta_if.ifconfig()
28
+ap_if.active(False)
29
+
30
+sta_if.scan()
31
+
32
+
33
+from machine import Pin
34
+
35
+p0 = Pin(0, Pin.IN)
36
+
37
+
38
+import webrepl_setup
39
+
40
+import webrepl
41
+webrepl.start()
42
+import machine
43
+pin = machine.Pin(2, machine.Pin.OUT)
44
+pin.value(1)
45
+import esp
46
+pwm12 = machine.PWM(pin)
47
+pwm12
48
+import time, math
49
+def pulse(l, t):
50
+     for i in range(200):
51
+         l.duty(int(math.sin(i / 200 * math.pi) * 500 + 500))
52
+         time.sleep_ms(t)
53
+pulse(pwm12, 1)
54
+for i in range(100):
55
+     pulse(pwm12, 2)
56
+pwm12.deinit()

+ 22
- 0
test_D4.py View File

@@ -0,0 +1,22 @@
1
+
2
+from machine import Pin,PWM
3
+import time, math
4
+import esp
5
+pin = Pin(2, Pin.OUT)
6
+pin.value(1)
7
+
8
+pwm2 = PWM(pin)
9
+
10
+
11
+def pulse(l, t):
12
+     for i in range(25):
13
+         l.duty(int(math.sin(i / 25 * math.pi) * 1023))
14
+         time.sleep_ms(t)
15
+pulse(pwm2, 100)
16
+for i in range(30):
17
+    print("Pulse n°: {}".format(i))
18
+    pulse(pwm2, 10)
19
+time.sleep_ms(50)
20
+pwm2.deinit()
21
+time.sleep_ms(50)
22
+pin.value(1)

+ 24
- 0
test_DS18B20.py View File

@@ -0,0 +1,24 @@
1
+import time
2
+import machine
3
+import onewire, ds18x20
4
+
5
+
6
+D5 = 14
7
+# the device is on GPIO12
8
+dat = machine.Pin(D5)
9
+
10
+# create the onewire object
11
+ds = ds18x20.DS18X20(onewire.OneWire(dat))
12
+
13
+# scan for devices on the bus
14
+roms = ds.scan()
15
+print('found devices:', roms)
16
+
17
+# loop 10 times and print all temperatures
18
+for i in range(10):
19
+    print('temperatures:', end=' ')
20
+    ds.convert_temp()
21
+    time.sleep_ms(750)
22
+    for rom in roms:
23
+        print(ds.read_temp(rom), end=' ')
24
+    print()

+ 20
- 0
test_bmp280.py View File

@@ -0,0 +1,20 @@
1
+from machine import Pin,I2C
2
+from bme280 import BME280
3
+D0 = 16
4
+D1 = 5
5
+D2 = 4
6
+D3 = 0
7
+D4 = 2
8
+D5 = 14
9
+D6 = 12
10
+D7 = 13
11
+D8 = 15
12
+
13
+# Rouge SCL D1, marron SDA D2
14
+
15
+i2c = I2C(scl=Pin(D1),sda=Pin(D2))
16
+print(i2c.scan())
17
+
18
+bmp = BME280(i2c=i2c)
19
+print(bmp.values)
20
+print(bmp.values2)

+ 1262
- 0
user_lib/apds9960.py
File diff suppressed because it is too large
View File


+ 3
- 0
user_lib/apds9960/__init__.py View File

@@ -0,0 +1,3 @@
1
+from apds9960.device import APDS9960, uAPDS9960
2
+
3
+__all__ = [ 'APDS9960', 'uAPDS9960', ]

+ 169
- 0
user_lib/apds9960/const.py View File

@@ -0,0 +1,169 @@
1
+# APDS9960 i2c address
2
+APDS9960_I2C_ADDR = 0x39
3
+
4
+# APDS9960 gesture parameters
5
+APDS9960_GESTURE_THRESHOLD_OUT = 10
6
+APDS9960_GESTURE_SENSITIVITY_1 = 50
7
+APDS9960_GESTURE_SENSITIVITY_2 = 20
8
+
9
+# APDS9960 device IDs
10
+APDS9960_DEV_ID = [0xab, 0x9c, 0xa8]
11
+
12
+# APDS9960 times
13
+APDS9960_TIME_FIFO_PAUSE = 0.03
14
+
15
+# APDS9960 register addresses
16
+APDS9960_REG_ENABLE = 0x80
17
+APDS9960_REG_ATIME = 0x81
18
+APDS9960_REG_WTIME = 0x83
19
+APDS9960_REG_AILTL = 0x84
20
+APDS9960_REG_AILTH = 0x85
21
+APDS9960_REG_AIHTL = 0x86
22
+APDS9960_REG_AIHTH = 0x87
23
+APDS9960_REG_PILT = 0x89
24
+APDS9960_REG_PIHT = 0x8b
25
+APDS9960_REG_PERS = 0x8c
26
+APDS9960_REG_CONFIG1 = 0x8d
27
+APDS9960_REG_PPULSE = 0x8e
28
+APDS9960_REG_CONTROL = 0x8f
29
+APDS9960_REG_CONFIG2 = 0x90
30
+APDS9960_REG_ID = 0x92
31
+APDS9960_REG_STATUS = 0x93
32
+APDS9960_REG_CDATAL = 0x94
33
+APDS9960_REG_CDATAH = 0x95
34
+APDS9960_REG_RDATAL = 0x96
35
+APDS9960_REG_RDATAH = 0x97
36
+APDS9960_REG_GDATAL = 0x98
37
+APDS9960_REG_GDATAH = 0x99
38
+APDS9960_REG_BDATAL = 0x9a
39
+APDS9960_REG_BDATAH = 0x9b
40
+APDS9960_REG_PDATA = 0x9c
41
+APDS9960_REG_POFFSET_UR = 0x9d
42
+APDS9960_REG_POFFSET_DL = 0x9e
43
+APDS9960_REG_CONFIG3 = 0x9f
44
+APDS9960_REG_GPENTH = 0xa0
45
+APDS9960_REG_GEXTH = 0xa1
46
+APDS9960_REG_GCONF1 = 0xa2
47
+APDS9960_REG_GCONF2 = 0xa3
48
+APDS9960_REG_GOFFSET_U = 0xa4
49
+APDS9960_REG_GOFFSET_D = 0xa5
50
+APDS9960_REG_GOFFSET_L = 0xa7
51
+APDS9960_REG_GOFFSET_R = 0xa9
52
+APDS9960_REG_GPULSE = 0xa6
53
+APDS9960_REG_GCONF3 = 0xaA
54
+APDS9960_REG_GCONF4 = 0xaB
55
+APDS9960_REG_GFLVL = 0xae
56
+APDS9960_REG_GSTATUS = 0xaf
57
+APDS9960_REG_IFORCE = 0xe4
58
+APDS9960_REG_PICLEAR = 0xe5
59
+APDS9960_REG_CICLEAR = 0xe6
60
+APDS9960_REG_AICLEAR = 0xe7
61
+APDS9960_REG_GFIFO_U = 0xfc
62
+APDS9960_REG_GFIFO_D = 0xfd
63
+APDS9960_REG_GFIFO_L = 0xfe
64
+APDS9960_REG_GFIFO_R = 0xff
65
+
66
+# APDS9960 bit fields
67
+APDS9960_BIT_PON = 0b00000001
68
+APDS9960_BIT_AEN = 0b00000010
69
+APDS9960_BIT_PEN = 0b00000100
70
+APDS9960_BIT_WEN = 0b00001000
71
+APSD9960_BIT_AIEN =0b00010000
72
+APDS9960_BIT_PIEN = 0b00100000
73
+APDS9960_BIT_GEN = 0b01000000
74
+APDS9960_BIT_GVALID = 0b00000001
75
+
76
+# APDS9960 modes
77
+APDS9960_MODE_POWER = 0
78
+APDS9960_MODE_AMBIENT_LIGHT = 1
79
+APDS9960_MODE_PROXIMITY = 2
80
+APDS9960_MODE_WAIT = 3
81
+APDS9960_MODE_AMBIENT_LIGHT_INT = 4
82
+APDS9960_MODE_PROXIMITY_INT = 5
83
+APDS9960_MODE_GESTURE = 6
84
+APDS9960_MODE_ALL = 7
85
+
86
+# LED Drive values
87
+APDS9960_LED_DRIVE_100MA = 0
88
+APDS9960_LED_DRIVE_50MA = 1
89
+APDS9960_LED_DRIVE_25MA = 2
90
+APDS9960_LED_DRIVE_12_5MA = 3
91
+
92
+# Proximity Gain (PGAIN) values
93
+APDS9960_PGAIN_1X = 0
94
+APDS9960_PGAIN_2X = 1
95
+APDS9960_PGAIN_4X = 2
96
+APDS9960_PGAIN_8X = 3
97
+
98
+# ALS Gain (AGAIN) values
99
+APDS9960_AGAIN_1X = 0
100
+APDS9960_AGAIN_4X = 1
101
+APDS9960_AGAIN_16X = 2
102
+APDS9960_AGAIN_64X = 3
103
+
104
+# Gesture Gain (GGAIN) values
105
+APDS9960_GGAIN_1X = 0
106
+APDS9960_GGAIN_2X = 1
107
+APDS9960_GGAIN_4X = 2
108
+APDS9960_GGAIN_8X = 3
109
+
110
+# LED Boost values
111
+APDS9960_LED_BOOST_100 = 0
112
+APDS9960_LED_BOOST_150 = 1
113
+APDS9960_LED_BOOST_200 = 2
114
+APDS9960_LED_BOOST_300 = 3    
115
+
116
+# Gesture wait time values
117
+APDS9960_GWTIME_0MS = 0
118
+APDS9960_GWTIME_2_8MS = 1
119
+APDS9960_GWTIME_5_6MS = 2
120
+APDS9960_GWTIME_8_4MS = 3
121
+APDS9960_GWTIME_14_0MS = 4
122
+APDS9960_GWTIME_22_4MS = 5
123
+APDS9960_GWTIME_30_8MS = 6
124
+APDS9960_GWTIME_39_2MS = 7
125
+
126
+# Default values
127
+APDS9960_DEFAULT_ATIME = 219                            # 103ms
128
+APDS9960_DEFAULT_WTIME = 246                            # 27ms
129
+APDS9960_DEFAULT_PROX_PPULSE = 0x87                     # 16us, 8 pulses
130
+APDS9960_DEFAULT_GESTURE_PPULSE = 0x89                  # 16us, 10 pulses
131
+APDS9960_DEFAULT_POFFSET_UR = 0                         # 0 offset
132
+APDS9960_DEFAULT_POFFSET_DL = 0                         # 0 offset
133
+APDS9960_DEFAULT_CONFIG1 = 0x60                         # No 12x wait (WTIME) factor
134
+APDS9960_DEFAULT_LDRIVE = APDS9960_LED_DRIVE_100MA
135
+APDS9960_DEFAULT_PGAIN = APDS9960_PGAIN_4X
136
+APDS9960_DEFAULT_AGAIN = APDS9960_AGAIN_4X
137
+APDS9960_DEFAULT_PILT = 0                               # Low proximity threshold
138
+APDS9960_DEFAULT_PIHT = 50                              # High proximity threshold
139
+APDS9960_DEFAULT_AILT = 0xffff                          # Force interrupt for calibration
140
+APDS9960_DEFAULT_AIHT = 0
141
+APDS9960_DEFAULT_PERS = 0x11                            # 2 consecutive prox or ALS for int.
142
+APDS9960_DEFAULT_CONFIG2 = 0x01                         # No saturation interrupts or LED boost  
143
+APDS9960_DEFAULT_CONFIG3 = 0                            # Enable all photodiodes, no SAI
144
+APDS9960_DEFAULT_GPENTH = 40                            # Threshold for entering gesture mode
145
+APDS9960_DEFAULT_GEXTH = 30                             # Threshold for exiting gesture mode    
146
+APDS9960_DEFAULT_GCONF1 = 0x40                          # 4 gesture events for int., 1 for exit
147
+APDS9960_DEFAULT_GGAIN = APDS9960_GGAIN_4X
148
+APDS9960_DEFAULT_GLDRIVE = APDS9960_LED_DRIVE_100MA
149
+APDS9960_DEFAULT_GWTIME = APDS9960_GWTIME_2_8MS
150
+APDS9960_DEFAULT_GOFFSET = 0                            # No offset scaling for gesture mode
151
+APDS9960_DEFAULT_GPULSE = 0xc9                          # 32us, 10 pulses
152
+APDS9960_DEFAULT_GCONF3 = 0                             # All photodiodes active during gesture
153
+APDS9960_DEFAULT_GIEN = 0                               # Disable gesture interrupts
154
+
155
+# gesture directions
156
+APDS9960_DIR_NONE = 0
157
+APDS9960_DIR_LEFT = 1
158
+APDS9960_DIR_RIGHT = 2
159
+APDS9960_DIR_UP = 3
160
+APDS9960_DIR_DOWN = 4
161
+APDS9960_DIR_NEAR = 5
162
+APDS9960_DIR_FAR = 6
163
+APDS9960_DIR_ALL = 7
164
+
165
+# state definitions
166
+APDS9960_STATE_NA = 0
167
+APDS9960_STATE_NEAR = 1
168
+APDS9960_STATE_FAR = 2
169
+APDS9960_STATE_ALL = 3

+ 1103
- 0
user_lib/apds9960/device.py
File diff suppressed because it is too large
View File


+ 7
- 0
user_lib/apds9960/exceptions.py View File

@@ -0,0 +1,7 @@
1
+class ADPS9960InvalidDevId(ValueError):
2
+    def __init__(self, id, valid_ids):
3
+        Exception.__init__(self, "Device id 0x{} is not a valied one (valid: {})!".format(format(id, '02x'), ', '.join(["0x{}".format(format(i, '02x')) for i in valid_ids])))
4
+
5
+class ADPS9960InvalidMode(ValueError):
6
+    def __init__(self, mode):
7
+        Exception.__init__(self, "Feature mode {} is invalid!".format(mode))

+ 955
- 0
user_lib/apds9960_prox.py View File

@@ -0,0 +1,955 @@
1
+from micropython import const
2
+from time import sleep
3
+
4
+# APDS9960 i2c address
5
+APDS9960_I2C_ADDR = const(0x39)
6
+
7
+# APDS9960 gesture parameters
8
+APDS9960_GESTURE_THRESHOLD_OUT = const(10)
9
+APDS9960_GESTURE_SENSITIVITY_1 = const(50)
10
+APDS9960_GESTURE_SENSITIVITY_2 = const(20)
11
+
12
+# APDS9960 device IDs
13
+APDS9960_DEV_ID = [0xab, 0x9c, 0xa8]
14
+
15
+# APDS9960 times
16
+APDS9960_TIME_FIFO_PAUSE = 0.03
17
+
18
+# APDS9960 register addresses
19
+APDS9960_REG_ENABLE = const(0x80)
20
+APDS9960_REG_ATIME = const(0x81)
21
+APDS9960_REG_WTIME = const(0x83)
22
+APDS9960_REG_AILTL = const(0x84)
23
+APDS9960_REG_AILTH = const(0x85)
24
+APDS9960_REG_AIHTL = const(0x86)
25
+APDS9960_REG_AIHTH = const(0x87)
26
+APDS9960_REG_PILT = const(0x89)
27
+APDS9960_REG_PIHT = const(0x8b)
28
+APDS9960_REG_PERS = const(0x8c)
29
+APDS9960_REG_CONFIG1 = const(0x8d)
30
+APDS9960_REG_PPULSE = const(0x8e)
31
+APDS9960_REG_CONTROL = const(0x8f)
32
+APDS9960_REG_CONFIG2 = const(0x90)
33
+APDS9960_REG_ID = const(0x92)
34
+APDS9960_REG_STATUS = const(0x93)
35
+APDS9960_REG_CDATAL = const(0x94)
36
+APDS9960_REG_CDATAH = const(0x95)
37
+APDS9960_REG_RDATAL = const(0x96)
38
+APDS9960_REG_RDATAH = const(0x97)
39
+APDS9960_REG_GDATAL = const(0x98)
40
+APDS9960_REG_GDATAH = const(0x99)
41
+APDS9960_REG_BDATAL = const(0x9a)
42
+APDS9960_REG_BDATAH = const(0x9b)
43
+APDS9960_REG_PDATA = const(0x9c)
44
+APDS9960_REG_POFFSET_UR = const(0x9d)
45
+APDS9960_REG_POFFSET_DL = const(0x9e)
46
+APDS9960_REG_CONFIG3 = const(0x9f)
47
+APDS9960_REG_GPENTH = const(0xa0)
48
+APDS9960_REG_GEXTH = const(0xa1)
49
+APDS9960_REG_GCONF1 = const(0xa2)
50
+APDS9960_REG_GCONF2 = const(0xa3)
51
+APDS9960_REG_GOFFSET_U = const(0xa4)
52
+APDS9960_REG_GOFFSET_D = const(0xa5)
53
+APDS9960_REG_GOFFSET_L = const(0xa7)
54
+APDS9960_REG_GOFFSET_R = const(0xa9)
55
+APDS9960_REG_GPULSE = const(0xa6)
56
+APDS9960_REG_GCONF3 = const(0xaA)
57
+APDS9960_REG_GCONF4 = const(0xaB)
58
+APDS9960_REG_GFLVL = const(0xae)
59
+APDS9960_REG_GSTATUS = const(0xaf)
60
+APDS9960_REG_IFORCE = const(0xe4)
61
+APDS9960_REG_PICLEAR = const(0xe5)
62
+APDS9960_REG_CICLEAR = const(0xe6)
63
+APDS9960_REG_AICLEAR = const(0xe7)
64
+APDS9960_REG_GFIFO_U = const(0xfc)
65
+APDS9960_REG_GFIFO_D = const(0xfd)
66
+APDS9960_REG_GFIFO_L = const(0xfe)
67
+APDS9960_REG_GFIFO_R = const(0xff)
68
+
69
+# APDS9960 bit fields
70
+APDS9960_BIT_PON = const(0b00000001)
71
+APDS9960_BIT_AEN = const(0b00000010)
72
+APDS9960_BIT_PEN = const(0b00000100)
73
+APDS9960_BIT_WEN = const(0b00001000)
74
+APSD9960_BIT_AIEN = const(0b00010000)
75
+APDS9960_BIT_PIEN = const(0b00100000)
76
+APDS9960_BIT_GEN = const(0b01000000)
77
+APDS9960_BIT_GVALID = const(0b00000001)
78
+
79
+# APDS9960 modes
80
+APDS9960_MODE_POWER = const(0)
81
+APDS9960_MODE_AMBIENT_LIGHT = const(1)
82
+APDS9960_MODE_PROXIMITY = const(2)
83
+APDS9960_MODE_WAIT = const(3)
84
+APDS9960_MODE_AMBIENT_LIGHT_INT = const(4)
85
+APDS9960_MODE_PROXIMITY_INT = const(5)
86
+APDS9960_MODE_GESTURE = const(6)
87
+APDS9960_MODE_ALL = const(7)
88
+
89
+# LED Drive values
90
+APDS9960_LED_DRIVE_100MA = const(0)
91
+APDS9960_LED_DRIVE_50MA = const(1)
92
+APDS9960_LED_DRIVE_25MA = const(2)
93
+APDS9960_LED_DRIVE_12_5MA = const(3)
94
+
95
+# Proximity Gain (PGAIN) values
96
+APDS9960_PGAIN_1X = const(0)
97
+APDS9960_PGAIN_2X = const(1)
98
+APDS9960_PGAIN_4X = const(2)
99
+APDS9960_PGAIN_8X = const(3)
100
+
101
+# ALS Gain (AGAIN) values
102
+APDS9960_AGAIN_1X = const(0)
103
+APDS9960_AGAIN_4X = const(1)
104
+APDS9960_AGAIN_16X = const(2)
105
+APDS9960_AGAIN_64X = const(3)
106
+
107
+# Gesture Gain (GGAIN) values
108
+APDS9960_GGAIN_1X = const(0)
109
+APDS9960_GGAIN_2X = const(1)
110
+APDS9960_GGAIN_4X = const(2)
111
+APDS9960_GGAIN_8X = const(3)
112
+
113
+# LED Boost values
114
+APDS9960_LED_BOOST_100 = const(0)
115
+APDS9960_LED_BOOST_150 = const(1)
116
+APDS9960_LED_BOOST_200 = const(2)
117
+APDS9960_LED_BOOST_300 = const(3)
118
+
119
+# Gesture wait time values
120
+APDS9960_GWTIME_0MS = const(0)
121
+APDS9960_GWTIME_2_8MS = const(1)
122
+APDS9960_GWTIME_5_6MS = const(2)
123
+APDS9960_GWTIME_8_4MS = const(3)
124
+APDS9960_GWTIME_14_0MS = const(4)
125
+APDS9960_GWTIME_22_4MS = const(5)
126
+APDS9960_GWTIME_30_8MS = const(6)
127
+APDS9960_GWTIME_39_2MS = const(7)
128
+
129
+# Default values
130
+APDS9960_DEFAULT_ATIME = const(219)                            # 103ms
131
+APDS9960_DEFAULT_WTIME = const(246)                            # 27ms
132
+APDS9960_DEFAULT_PROX_PPULSE = const(0x87)                     # 16us, 8 pulses
133
+APDS9960_DEFAULT_GESTURE_PPULSE = const(0x89)                  # 16us, 10 pulses
134
+APDS9960_DEFAULT_POFFSET_UR = const(0)                         # 0 offset
135
+APDS9960_DEFAULT_POFFSET_DL = const(0)                         # 0 offset
136
+APDS9960_DEFAULT_CONFIG1 = const(0x60)                         # No 12x wait (WTIME) factor
137
+APDS9960_DEFAULT_LDRIVE = APDS9960_LED_DRIVE_100MA
138
+APDS9960_DEFAULT_PGAIN = APDS9960_PGAIN_4X
139
+APDS9960_DEFAULT_AGAIN = APDS9960_AGAIN_4X
140
+APDS9960_DEFAULT_PILT = const(0)                               # Low proximity threshold
141
+APDS9960_DEFAULT_PIHT = const(50)                              # High proximity threshold
142
+APDS9960_DEFAULT_AILT = const(0xffff)                          # Force interrupt for calibration
143
+APDS9960_DEFAULT_AIHT = const(0)
144
+APDS9960_DEFAULT_PERS = const(0x11)                            # 2 consecutive prox or ALS for int.
145
+APDS9960_DEFAULT_CONFIG2 = const(0x01)                         # No saturation interrupts or LED boost
146
+APDS9960_DEFAULT_CONFIG3 = const(0)                            # Enable all photodiodes, no SAI
147
+APDS9960_DEFAULT_GPENTH = const(40)                            # Threshold for entering gesture mode
148
+APDS9960_DEFAULT_GEXTH = const(30)                             # Threshold for exiting gesture mode
149
+APDS9960_DEFAULT_GCONF1 = const(0x40)                          # 4 gesture events for int., 1 for exit
150
+APDS9960_DEFAULT_GGAIN = APDS9960_GGAIN_4X
151
+APDS9960_DEFAULT_GLDRIVE = APDS9960_LED_DRIVE_100MA
152
+APDS9960_DEFAULT_GWTIME = APDS9960_GWTIME_2_8MS
153
+APDS9960_DEFAULT_GOFFSET = const(0)                            # No offset scaling for gesture mode
154
+APDS9960_DEFAULT_GPULSE = const(0xc9)                          # 32us, 10 pulses
155
+APDS9960_DEFAULT_GCONF3 = const(0)                             # All photodiodes active during gesture
156
+APDS9960_DEFAULT_GIEN = const(0)                               # Disable gesture interrupts
157
+
158
+# gesture directions
159
+APDS9960_DIR_NONE = const(0)
160
+APDS9960_DIR_LEFT = const(1)
161
+APDS9960_DIR_RIGHT = const(2)
162
+APDS9960_DIR_UP = const(3)
163
+APDS9960_DIR_DOWN = const(4)
164
+APDS9960_DIR_NEAR = const(5)
165
+APDS9960_DIR_FAR = const(6)
166
+APDS9960_DIR_ALL = const(7)
167
+
168
+# state definitions
169
+APDS9960_STATE_NA = const(0)
170
+APDS9960_STATE_NEAR = const(1)
171
+APDS9960_STATE_FAR = const(2)
172
+APDS9960_STATE_ALL = const(3)
173
+
174
+class ADPS9960InvalidDevId(ValueError):
175
+    def __init__(self, id, valid_ids):
176
+        Exception.__init__(self, "Device id 0x{} is not a valied one (valid: {})!".format(format(id, '02x'), ', '.join(["0x{}".format(format(i, '02x')) for i in valid_ids])))
177
+
178
+class ADPS9960InvalidMode(ValueError):
179
+    def __init__(self, mode):
180
+        Exception.__init__(self, "Feature mode {} is invalid!".format(mode))
181
+
182
+
183
+
184
+
185
+class APDS9960:
186
+    class GestureData:
187
+        def __init__(self):
188
+            self.u_data = [0] * 32
189
+            self.d_data = [0] * 32
190
+            self.l_data = [0] * 32
191
+            self.r_data = [0] * 32
192
+            self.index = 0
193
+            self.total_gestures = 0
194
+            self.in_threshold = 0
195
+            self.out_threshold = 0
196
+
197
+    def __init__(self, bus, address=APDS9960_I2C_ADDR, valid_id=APDS9960_DEV_ID):
198
+        # I2C stuff
199
+        self.address = address
200
+        self.bus = bus
201
+
202
+        # instance variables for gesture detection
203
+        self.gesture_ud_delta_ = 0
204
+        self.gesture_lr_delta_ = 0
205
+
206
+        self.gesture_ud_count_ = 0
207
+        self.gesture_lr_count_ = 0
208
+
209
+        self.gesture_near_count_ = 0
210
+        self.gesture_far_count_ = 0
211
+
212
+        self.gesture_state_ = 0
213
+        self.gesture_motion_ = APDS9960_DIR_NONE
214
+
215
+        self.gesture_data_ = APDS9960.GestureData()
216
+
217
+        # check device id
218
+        self.dev_id = self._read_byte_data(APDS9960_REG_ID)
219
+        if not self.dev_id in valid_id:
220
+            raise ADPS9960InvalidDevId(self.dev_id, valid_id)
221
+
222
+        # disable all features
223
+        self.setMode(APDS9960_MODE_ALL, False)
224
+
225
+        # set default values for ambient light and proximity registers
226
+        self._write_byte_data(APDS9960_REG_ATIME, APDS9960_DEFAULT_ATIME)
227
+        self._write_byte_data(APDS9960_REG_WTIME, APDS9960_DEFAULT_WTIME)
228
+        self._write_byte_data(APDS9960_REG_PPULSE, APDS9960_DEFAULT_PROX_PPULSE)
229
+        self._write_byte_data(APDS9960_REG_POFFSET_UR, APDS9960_DEFAULT_POFFSET_UR)
230
+        self._write_byte_data(APDS9960_REG_POFFSET_DL, APDS9960_DEFAULT_POFFSET_DL)
231
+        self._write_byte_data(APDS9960_REG_CONFIG1, APDS9960_DEFAULT_CONFIG1)
232
+        self.setLEDDrive(APDS9960_DEFAULT_LDRIVE)
233
+        self.setProximityGain(APDS9960_DEFAULT_PGAIN)
234
+        self.setAmbientLightGain(APDS9960_DEFAULT_AGAIN)
235
+        self.setProxIntLowThresh(APDS9960_DEFAULT_PILT)
236
+        self.setProxIntHighThresh(APDS9960_DEFAULT_PIHT)
237
+        self.setLightIntLowThreshold(APDS9960_DEFAULT_AILT)
238
+        self.setLightIntHighThreshold(APDS9960_DEFAULT_AIHT)
239
+
240
+        self._write_byte_data(APDS9960_REG_PERS, APDS9960_DEFAULT_PERS)
241
+        self._write_byte_data(APDS9960_REG_CONFIG2, APDS9960_DEFAULT_CONFIG2)
242
+        self._write_byte_data(APDS9960_REG_CONFIG3, APDS9960_DEFAULT_CONFIG3)
243
+
244
+    def getMode(self):
245
+        return self._read_byte_data(APDS9960_REG_ENABLE)
246
+
247
+    def setMode(self, mode, enable=True):
248
+        # read ENABLE register
249
+        reg_val = self.getMode()
250
+
251
+        if mode < 0 or mode > APDS9960_MODE_ALL:
252
+            raise ADPS9960InvalidMode(mode)
253
+
254
+        # change bit(s) in ENABLE register */
255
+        if mode == APDS9960_MODE_ALL:
256
+            if enable:
257
+                reg_val = 0x7f
258
+            else:
259
+                reg_val = 0x00
260
+        else:
261
+            if enable:
262
+                reg_val |= (1 << mode);
263
+            else:
264
+                reg_val &= ~(1 << mode);
265
+
266
+        # write value to ENABLE register
267
+        self._write_byte_data(APDS9960_REG_ENABLE, reg_val)
268
+
269
+
270
+    # start the light (R/G/B/Ambient) sensor
271
+    def enableLightSensor(self, interrupts=True):
272
+        self.setAmbientLightGain(APDS9960_DEFAULT_AGAIN)
273
+        self.setAmbientLightIntEnable(interrupts)
274
+        self.enablePower()
275
+        self.setMode(APDS9960_MODE_AMBIENT_LIGHT, True)
276
+
277
+    # stop the light sensor
278
+    def disableLightSensor(self):
279
+        self.setAmbientLightIntEnable(False)
280
+        self.setMode(APDS9960_MODE_AMBIENT_LIGHT, False)
281
+
282
+
283
+    # start the proximity sensor
284
+    def enableProximitySensor(self, interrupts=True):
285
+        self.setProximityGain(APDS9960_DEFAULT_PGAIN)
286
+        self.setLEDDrive(APDS9960_DEFAULT_LDRIVE)
287
+        self.setProximityIntEnable(interrupts)
288
+        self.enablePower()
289
+        self.setMode(APDS9960_MODE_PROXIMITY, True)
290
+
291
+    # stop the proximity sensor
292
+    def disableProximitySensor(self):
293
+        self.setProximityIntEnable(False)
294
+        self.setMode(APDS9960_MODE_PROXIMITY, False)
295
+
296
+
297
+    # turn the APDS-9960 on
298
+    def enablePower(self):
299
+        self.setMode(APDS9960_MODE_POWER, True)
300
+
301
+
302
+    def disablePower(self):
303
+        # turn the APDS-9960 off
304
+        self.setMode(APDS9960_MODE_POWER, False)
305
+
306
+
307
+
308
+    # *******************************************************************************
309
+    # ambient light and color sensor controls
310
+    # *******************************************************************************
311
+
312
+    # reads the ambient (clear) light level as a 16-bit value
313
+    def readAmbientLight(self):
314
+        # read value from clear channel, low byte register
315
+        l = self._read_byte_data(APDS9960_REG_CDATAL)
316
+
317
+        # read value from clear channel, high byte register
318
+        h = self._read_byte_data(APDS9960_REG_CDATAH)
319
+
320
+        return l + (h << 8)
321
+
322
+    # reads the red light level as a 16-bit value
323
+    def readRedLight(self):
324
+        # read value from red channel, low byte register
325
+        l = self._read_byte_data(APDS9960_REG_RDATAL)
326
+
327
+        # read value from red channel, high byte register
328
+        h = self._read_byte_data(APDS9960_REG_RDATAH)
329
+
330
+        return l + (h << 8)
331
+
332
+    # reads the green light level as a 16-bit value
333
+    def readGreenLight(self):
334
+        # read value from green channel, low byte register
335
+        l = self._read_byte_data(APDS9960_REG_GDATAL)
336
+
337
+        # read value from green channel, high byte register
338
+        h = self._read_byte_data(APDS9960_REG_GDATAH)
339
+
340
+        return l + (h << 8)
341
+
342
+    # reads the blue light level as a 16-bit value
343
+    def readBlueLight(self):
344
+        # read value from blue channel, low byte register
345
+        l = self._read_byte_data(APDS9960_REG_BDATAL)
346
+
347
+        # read value from blue channel, high byte register
348
+        h = self._read_byte_data(APDS9960_REG_BDATAH)
349
+
350
+        return l + (h << 8)
351
+
352
+
353
+    # *******************************************************************************
354
+    # Proximity sensor controls
355
+    # *******************************************************************************
356
+
357
+    # reads the proximity level as an 8-bit value
358
+    def readProximity(self):
359
+        return self._read_byte_data(APDS9960_REG_PDATA)
360
+
361
+
362
+    # *******************************************************************************
363
+    # Getters and setters for register values
364
+    # *******************************************************************************
365
+
366
+    def getProxIntLowThresh(self):
367
+        """Returns the lower threshold for proximity detection
368
+        """
369
+        return self._read_byte_data(APDS9960_REG_PILT)
370
+
371
+    def setProxIntLowThresh(self, threshold):
372
+        """Sets the lower threshold for proximity detection.
373
+        """
374
+        self._write_byte_data(APDS9960_REG_PILT, threshold)
375
+
376
+
377
+    def getProxIntHighThresh(self):
378
+        """Returns the high threshold for proximity detection.
379
+        """
380
+        return self._read_byte_data(APDS9960_REG_PIHT)
381
+
382
+    def setProxIntHighThresh(self, threshold):
383
+        """Sets the high threshold for proximity detection.
384
+        """
385
+        self._write_byte_data(APDS9960_REG_PIHT, threshold)
386
+
387
+
388
+    def getLEDDrive(self):
389
+        """Returns LED drive strength for proximity and ALS.
390
+
391
+            Value    LED Current
392
+              0        100 mA
393
+              1         50 mA
394
+              2         25 mA
395
+              3         12.5 mA
396
+
397
+            Returns:
398
+                int: the value of the LED drive strength
399
+        """
400
+        val = self._read_byte_data(APDS9960_REG_CONTROL)
401
+
402
+        # shift and mask out LED drive bits
403
+        return (val >> 6) & 0b00000011
404
+
405
+    def setLEDDrive(self, drive):
406
+        """Sets LED drive strength for proximity and ALS.
407
+
408
+            Value    LED Current
409
+              0        100 mA
410
+              1         50 mA
411
+              2         25 mA
412
+              3         12.5 mA
413
+
414
+            Args:
415
+                drive (int): value for the LED drive strength
416
+        """
417
+        val = self._read_byte_data(APDS9960_REG_CONTROL)
418
+
419
+        # set bits in register to given value
420
+        drive &= 0b00000011
421
+        drive = drive << 6
422
+        val &= 0b00111111
423
+        val |= drive
424
+
425
+        self._write_byte_data(APDS9960_REG_CONTROL, val)
426
+
427
+
428
+    def getProximityGain(self):
429
+        """Returns receiver gain for proximity detection.
430
+
431
+            Value    Gain
432
+              0       1x
433
+              1       2x
434
+              2       4x
435
+              3       8x
436
+
437
+            Returns:
438
+                int: the value of the proximity gain
439
+        """
440
+        val = self._read_byte_data(APDS9960_REG_CONTROL)
441
+
442
+        # shift and mask out PDRIVE bits
443
+        return (val >> 2) & 0b00000011
444
+
445
+    def setProximityGain(self, drive):
446
+        """Returns receiver gain for proximity detection.
447
+
448
+            Value    Gain
449
+              0       1x
450
+              1       2x
451
+              2       4x
452
+              3       8x
453
+
454
+            Args:
455
+                drive (int): value for the proximity gain
456
+        """
457
+        val = self._read_byte_data(APDS9960_REG_CONTROL)
458
+
459
+        # set bits in register to given value
460
+        drive &= 0b00000011
461
+        drive = drive << 2
462
+        val &= 0b11110011
463
+        val |= drive
464
+
465
+        self._write_byte_data(APDS9960_REG_CONTROL, val)
466
+
467
+
468
+    def getAmbientLightGain(self):
469
+        """Returns receiver gain for the ambient light sensor (ALS).
470
+
471
+            Value    Gain
472
+              0       1x
473
+              1       4x
474
+              2       16x
475
+              3       64x
476
+
477
+            Returns:
478
+                int: the value of the ALS gain
479
+        """
480
+        val = self._read_byte_data(APDS9960_REG_CONTROL)
481
+
482
+        # shift and mask out ADRIVE bits
483
+        return (val & 0b00000011)
484
+
485
+    def setAmbientLightGain(self, drive):
486
+        """Sets the receiver gain for the ambient light sensor (ALS).
487
+
488
+            Value    Gain
489
+              0       1x
490
+              1       4x
491
+              2       16x
492
+              3       64x
493
+
494
+            Args:
495
+                drive (int): value for the ALS gain
496
+        """
497
+        val = self._read_byte_data(APDS9960_REG_CONTROL)
498
+
499
+        # set bits in register to given value
500
+        drive &= 0b00000011
501
+        val &= 0b11111100
502
+        val |= drive
503
+
504
+        self._write_byte_data(APDS9960_REG_CONTROL, val)
505
+
506
+
507
+    def getLEDBoost(self):
508
+        """Get the current LED boost value.
509
+
510
+            Value    Gain
511
+              0        100%
512
+              1        150%
513
+              2        200%
514
+              3        300%
515
+
516
+            Returns:
517
+                int: the LED boost value
518
+        """
519
+        val = self._read_byte_data(APDS9960_REG_CONFIG2)
520
+
521
+        # shift and mask out LED_BOOST bits
522
+        return (val >> 4) & 0b00000011
523
+
524
+    def setLEDBoost(self, boost):
525
+        """Sets the LED current boost value.
526
+
527
+            Value    Gain
528
+              0        100%
529
+              1        150%
530
+              2        200%
531
+              3        300%
532
+
533
+            Args:
534
+                boost (int): value for the LED boost
535
+        """
536
+        val = self._read_byte_data(APDS9960_REG_CONFIG2)
537
+
538
+        # set bits in register to given value
539
+        boost &= 0b00000011
540
+        boost = boost << 4
541
+        val &= 0b11001111
542
+        val |= boost
543
+
544
+        self._write_byte_data(APDS9960_REG_CONFIG2, val)
545
+
546
+
547
+    def getProxGainCompEnable(self):
548
+        """Gets proximity gain compensation enable.
549
+
550
+            Returns:
551
+                bool: True if compensation is enabled, False if not
552
+        """
553
+        val = self._read_byte_data(APDS9960_REG_CONFIG3)
554
+
555
+        # Shift and mask out PCMP bits
556
+        val = (val >> 5) & 0b00000001
557
+        return val == 1
558
+
559
+    def setProxGainCompEnable(self, enable):
560
+        """Sets the proximity gain compensation enable.
561
+
562
+            Args:
563
+                enable (bool): True to enable compensation, False to disable
564
+        """
565
+        val = self._read_byte_data(APDS9960_REG_CONFIG3)
566
+
567
+        # set bits in register to given value
568
+        val &= 0b11011111
569
+        if enable:
570
+            val |= 0b00100000
571
+
572
+        self._write_byte_data(APDS9960_REG_CONFIG3, val)
573
+
574
+
575
+    def getProxPhotoMask(self):
576
+        """Gets the current mask for enabled/disabled proximity photodiodes.
577
+
578
+            Bit    Photodiode
579
+             3       UP
580
+             2       DOWN
581
+             1       LEFT
582
+             0       RIGHT
583
+
584
+            1 = disabled, 0 = enabled
585
+
586
+            Returns:
587
+                int: Current proximity mask for photodiodes.
588
+        """
589
+        val = self._read_byte_data(APDS9960_REG_CONFIG3)
590
+
591
+        # mask out photodiode enable mask bits
592
+        return val & 0b00001111
593
+
594
+    def setProxPhotoMask(self, mask):
595
+        """Sets the mask for enabling/disabling proximity photodiodes.
596
+
597
+            Bit    Photodiode
598
+             3       UP
599
+             2       DOWN
600
+             1       LEFT
601
+             0       RIGHT
602
+
603
+            1 = disabled, 0 = enabled
604
+
605
+            Args:
606
+                mask (int): 4-bit mask value
607
+        """
608
+        val = self._read_byte_data(APDS9960_REG_CONFIG3)
609
+
610
+        # set bits in register to given value
611
+        mask &= 0b00001111
612
+        val &= 0b11110000
613
+        val |= mask
614
+
615
+        self._write_byte_data(APDS9960_REG_CONFIG3, val)
616
+
617
+
618
+    def getGestureEnterThresh(self):
619
+        """Gets the entry proximity threshold for gesture sensing.
620
+
621
+            Returns:
622
+                int: current entry proximity threshold
623
+        """
624
+        return self._read_byte_data(APDS9960_REG_GPENTH)
625
+
626
+    def setGestureEnterThresh(self, threshold):
627
+        """Sets the entry proximity threshold for gesture sensing.
628
+
629
+            Args:
630
+                threshold (int): threshold proximity value needed to start gesture mode
631
+        """
632
+        self._write_byte_data(APDS9960_REG_GPENTH, threshold)
633
+
634
+
635
+    def getGestureExitThresh(self):
636
+        """Gets the exit proximity threshold for gesture sensing.
637
+
638
+            Returns:
639
+                int: current exit proximity threshold
640
+        """
641
+        return self._read_byte_data(APDS9960_REG_GEXTH)
642
+
643
+    def setGestureExitThresh(self, threshold):
644
+        """Sets the exit proximity threshold for gesture sensing.
645
+
646
+            Args:
647
+                threshold (int): threshold proximity value needed to end gesture mode
648
+        """
649
+        self._write_byte_data(APDS9960_REG_GEXTH, threshold)
650
+
651
+
652
+    def getGestureGain(self):
653
+        """Gets the gain of the photodiode during gesture mode.
654
+
655
+            Value    Gain
656
+              0       1x
657
+              1       2x
658
+              2       4x
659
+              3       8x
660
+
661
+            Returns:
662
+                int: the current photodiode gain
663
+        """
664
+        val = self._read_byte_data(APDS9960_REG_GCONF2)
665
+
666
+        # shift and mask out PDRIVE bits
667
+        return (val >> 5) & 0b00000011
668
+
669
+    def setGestureGain(self, gain):
670
+        """Sets the gain of the photodiode during gesture mode.
671
+
672
+            Value    Gain
673
+              0       1x
674
+              1       2x
675
+              2       4x
676
+              3       8x
677
+
678
+            Args:
679
+                gain (int): the value for the photodiode gain
680
+        """
681
+        val = self._read_byte_data(APDS9960_REG_GCONF2)
682
+
683
+        # set bits in register to given value
684
+        gain &= 0b00000011
685
+        gain = gain << 5
686
+        val &= 0b10011111
687
+        val |= gain
688
+
689
+        self._write_byte_data(APDS9960_REG_GCONF2, val)
690
+
691
+
692
+    def getGestureLEDDrive(self):
693
+        """Gets the drive current of the LED during gesture mode.
694
+
695
+            Value    LED Current
696
+              0        100 mA
697
+              1         50 mA
698
+              2         25 mA
699
+              3         12.5 mA
700
+
701
+            Returns:
702
+                int: the LED drive current value
703
+        """
704
+        val = self._read_byte_data(APDS9960_REG_GCONF2)
705
+
706
+        # shift and mask out LED drive bits
707
+        return (val >> 3) & 0b00000011
708
+
709
+    def setGestureLEDDrive(self, drive):
710
+        """Sets LED drive strength for proximity and ALS.
711
+
712
+            Value    LED Current
713
+              0        100 mA
714
+              1         50 mA
715
+              2         25 mA
716
+              3         12.5 mA
717
+
718
+            Args:
719
+                drive (int): value for the LED drive current
720
+        """
721
+        val = self._read_byte_data(APDS9960_REG_GCONF2)
722
+
723
+        # set bits in register to given value
724
+        drive &= 0b00000011;
725
+        drive = drive << 3;
726
+        val &= 0b11100111;
727
+        val |= drive;
728
+
729
+        self._write_byte_data(APDS9960_REG_GCONF2, val)
730
+
731
+
732
+    def getGestureWaitTime(self):
733
+        """Gets the time in low power mode between gesture detections.
734
+
735
+            Value    Wait time
736
+              0          0 ms
737
+              1          2.8 ms
738
+              2          5.6 ms
739
+              3          8.4 ms
740
+              4         14.0 ms
741
+              5         22.4 ms
742
+              6         30.8 ms
743
+              7         39.2 ms
744
+
745
+            Returns:
746
+                int: the current wait time between gestures
747
+        """
748
+        val = self._read_byte_data(APDS9960_REG_GCONF2)
749
+
750
+        # shift and mask out LED drive bits
751
+        return val & 0b00000111
752
+
753
+    def setGestureWaitTime(self, time):
754
+        """Sets the time in low power mode between gesture detections.
755
+
756
+            Value    Wait time
757
+              0          0 ms
758
+              1          2.8 ms
759
+              2          5.6 ms
760
+              3          8.4 ms
761
+              4         14.0 ms
762
+              5         22.4 ms
763
+              6         30.8 ms
764
+              7         39.2 ms
765
+
766
+            Args:
767
+                time (int): value for the wait time
768
+        """
769
+        val = self._read_byte_data(APDS9960_REG_GCONF2)
770
+
771
+        # set bits in register to given value
772
+        time &= 0b00000111
773
+        val &= 0b11111000
774
+        val |= time
775
+
776
+        self._write_byte_data(APDS9960_REG_GCONF2, val)
777
+
778
+
779
+    def getLightIntLowThreshold(self):
780
+        """Gets the low threshold for ambient light interrupts.
781
+
782
+            Returns:
783
+                int: threshold current low threshold stored on the APDS9960
784
+        """
785
+        return self._read_byte_data(APDS9960_REG_AILTL) | (self._read_byte_data(APDS9960_REG_AILTH) << 8)
786
+
787
+    def setLightIntLowThreshold(self, threshold):
788
+        """Sets the low threshold for ambient light interrupts.
789
+
790
+            Args:
791
+                threshold (int): low threshold value for interrupt to trigger
792
+        """
793
+        # break 16-bit threshold into 2 8-bit values
794
+        self._write_byte_data(APDS9960_REG_AILTL, threshold & 0x00ff)
795
+        self._write_byte_data(APDS9960_REG_AILTH, (threshold & 0xff00) >> 8)
796
+
797
+
798
+    def getLightIntHighThreshold(self):
799
+        """Gets the high threshold for ambient light interrupts.
800
+
801
+            Returns:
802
+                int: threshold current low threshold stored on the APDS9960
803
+        """
804
+        return self._read_byte_data(APDS9960_REG_AIHTL) | (self._read_byte_data(APDS9960_REG_AIHTH) << 8)
805
+
806
+    def setLightIntHighThreshold(self, threshold):
807
+        """Sets the high threshold for ambient light interrupts.
808
+
809
+            Args:
810
+                threshold (int): high threshold value for interrupt to trigger
811
+        """
812
+        # break 16-bit threshold into 2 8-bit values
813
+        self._write_byte_data(APDS9960_REG_AIHTL, threshold & 0x00ff)
814
+        self._write_byte_data(APDS9960_REG_AIHTH, (threshold & 0xff00) >> 8)
815
+
816
+
817
+    def getProximityIntLowThreshold(self):
818
+        """Gets the low threshold for proximity interrupts.
819
+
820
+            Returns:
821
+                int: threshold current low threshold stored on the APDS9960
822
+        """
823
+        return self._read_byte_data(APDS9960_REG_PILT)
824
+
825
+    def setProximityIntLowThreshold(self, threshold):
826
+        """Sets the low threshold for proximity interrupts.
827
+
828
+            Args:
829
+                threshold (int): low threshold value for interrupt to trigger
830
+        """
831
+        self._write_byte_data(APDS9960_REG_PILT, threshold)
832
+
833
+
834
+    def getProximityIntHighThreshold(self):
835
+        """Gets the high threshold for proximity interrupts.
836
+
837
+            Returns:
838
+                int: threshold current high threshold stored on the APDS9960
839
+        """
840
+        return self._read_byte_data(APDS9960_REG_PIHT)
841
+
842
+    def setProximityIntHighThreshold(self, threshold):
843
+        """Sets the high threshold for proximity interrupts.
844
+
845
+            Args:
846
+                threshold (int): high threshold value for interrupt to trigger
847
+        """
848
+        self._write_byte_data(APDS9960_REG_PIHT, threshold)
849
+
850
+
851
+    def getAmbientLightIntEnable(self):
852
+        """Gets if ambient light interrupts are enabled or not.
853
+
854
+            Returns:
855
+                bool: True if interrupts are enabled, False if not
856
+        """
857
+        val = self._read_byte_data(APDS9960_REG_ENABLE)
858
+        return (val >> 4) & 0b00000001 == 1
859
+
860
+    def setAmbientLightIntEnable(self, enable):
861
+        """Turns ambient light interrupts on or off.
862
+
863
+            Args:
864
+                enable (bool): True to enable interrupts, False to turn them off
865
+        """
866
+        val = self._read_byte_data(APDS9960_REG_ENABLE)
867
+
868
+        # set bits in register to given value
869
+        val &= 0b11101111;
870
+        if enable:
871
+            val |= 0b00010000
872
+
873
+        self._write_byte_data(APDS9960_REG_ENABLE, val)
874
+
875
+
876
+    def getProximityIntEnable(self):
877
+        """Gets if proximity interrupts are enabled or not.
878
+
879
+            Returns:
880
+                bool: True if interrupts are enabled, False if not
881
+        """
882
+        val = self._read_byte_data(APDS9960_REG_ENABLE)
883
+        return (val >> 5) & 0b00000001 == 1
884
+
885
+    def setProximityIntEnable(self, enable):
886
+        """Turns proximity interrupts on or off.
887
+
888
+            Args:
889
+                enable (bool): True to enable interrupts, False to turn them off
890
+        """
891
+        val = self._read_byte_data(APDS9960_REG_ENABLE)
892
+
893
+        # set bits in register to given value
894
+        val &= 0b11011111;
895
+        if enable:
896
+            val |= 0b00100000
897
+
898
+        self._write_byte_data(APDS9960_REG_ENABLE, val)
899
+
900
+
901
+    def getGestureIntEnable(self):
902
+        """Gets if gesture interrupts are enabled or not.
903
+
904
+            Returns:
905
+                bool: True if interrupts are enabled, False if not
906
+        """
907
+        val = self._read_byte_data(APDS9960_REG_GCONF4)
908
+        return (val >> 1) & 0b00000001 == 1
909
+
910
+    def setGestureIntEnable(self, enable):
911
+        """Turns gesture-related interrupts on or off.
912
+
913
+            Args:
914
+                enable (bool): True to enable interrupts, False to turn them off
915
+        """
916
+        val = self._read_byte_data(APDS9960_REG_GCONF4)
917
+
918
+        # set bits in register to given value
919
+        val &= 0b11111101
920
+        if enable:
921
+            val |= 0b00000010
922
+
923
+        self._write_byte_data(APDS9960_REG_GCONF4, val)
924
+
925
+
926
+    def clearAmbientLightInt(self):
927
+        """Clears the ambient light interrupt.
928
+        """
929
+        self._read_byte_data(APDS9960_REG_AICLEAR)
930
+
931
+
932
+    def clearProximityInt(self):
933
+        """Clears the proximity interrupt.
934
+        """
935
+        self._read_byte_data(APDS9960_REG_PICLEAR)
936
+
937
+
938
+    # *******************************************************************************
939
+    # Raw I2C Reads and Writes
940
+    # *******************************************************************************
941
+
942
+    def _read_byte_data(self, cmd):
943
+        return self.bus.readfrom_mem(self.address, cmd, 1)[0]
944
+
945
+    def _write_byte_data(self, cmd, val):
946
+        self.bus.writeto_mem(self.address, cmd, bytes([val]))
947
+
948
+    def _read_i2c_block_data(self, cmd, num):
949
+        return self.bus.readfrom_mem(self.address, cmd, num)
950
+
951
+    # *******************************************************************************
952
+    # High-level gesture controls
953
+    # *******************************************************************************
954
+
955
+    # resets all the parameters in the gesture data member

+ 33
- 0
user_lib/apds9960_test_ambient.py View File

@@ -0,0 +1,33 @@
1
+from time import sleep
2
+
3
+from machine import Pin, I2C
4
+
5
+D0 = 16
6
+D1 = 5
7
+D2 = 4
8
+D3 = 0
9
+D4 = 2
10
+D5 = 14
11
+D6 = 12
12
+D7 = 13
13
+D8 = 15
14
+
15
+
16
+
17
+from apds9960 import APDS9960
18
+
19
+bus = I2C(sda=Pin(D2), scl=Pin(D1))
20
+
21
+apds = APDS9960(bus)
22
+
23
+print("Light Sensor Test")
24
+print("=================")
25
+apds.enableLightSensor()
26
+
27
+oval = -1
28
+while True:
29
+    sleep(0.25)
30
+    val = apds.readAmbientLight()
31
+    if val != oval:
32
+        print("AmbientLight={}".format(val))
33
+        oval = val

+ 40
- 0
user_lib/apds9960_test_gesture.py View File

@@ -0,0 +1,40 @@
1
+from time import sleep
2
+
3
+from machine import Pin, I2C
4
+
5
+
6
+from apds9960 import APDS9960
7
+D0 = 16
8
+D1 = 5
9
+D2 = 4
10
+D3 = 0
11
+D4 = 2
12
+D5 = 14
13
+D6 = 12
14
+D7 = 13
15
+D8 = 15
16
+bus = I2C(sda=Pin(D2), scl=Pin(D1))
17
+
18
+apds = APDS9960(bus)
19
+
20
+dirs = {
21
+    APDS9960_DIR_NONE: "none",
22
+    APDS9960_DIR_LEFT: "left",
23
+    APDS9960_DIR_RIGHT: "right",
24
+    APDS9960_DIR_UP: "up",
25
+    APDS9960_DIR_DOWN: "down",
26
+    APDS9960_DIR_NEAR: "near",
27
+    APDS9960_DIR_FAR: "far",
28
+}
29
+
30
+apds.setProximityIntLowThreshold(50)
31
+
32
+print("Gesture Test")
33
+print("============")
34
+apds.enableGestureSensor()
35
+
36
+while True:
37
+    sleep(0.5)
38
+    if apds.isGestureAvailable():
39
+        motion = apds.readGesture()
40
+        print("Gesture={}".format(dirs.get(motion, "unknown")))

+ 32
- 0
user_lib/apds9960_test_prox.py View File

@@ -0,0 +1,32 @@
1
+from time import sleep
2
+
3
+from machine import Pin, I2C
4
+D0 = 16
5
+D1 = 5
6
+D2 = 4
7
+D3 = 0
8
+D4 = 2
9
+D5 = 14
10
+D6 = 12
11
+D7 = 13
12
+D8 = 15
13
+
14
+from apds9960_prox import APDS9960
15
+
16
+bus = I2C(sda=Pin(D2), scl=Pin(D1))
17
+
18
+apds = APDS9960(bus)
19
+
20
+apds.setProximityIntLowThreshold(50)
21
+
22
+print("Proximity Sensor Test")
23
+print("=====================")
24
+apds.enableProximitySensor()
25
+
26
+oval = -1
27
+while True:
28
+    sleep(0.25)
29
+    val = apds.readProximity()
30
+    if val != oval:
31
+        print("proximity={}".format(val))
32
+        oval = val

+ 216
- 0
user_lib/bme280.py View File

@@ -0,0 +1,216 @@
1
+# Authors: Paul Cunnane 2016, Peter Dahlebrg 2016
2
+#
3
+# This module borrows from the Adafruit BME280 Python library. Original
4
+# Copyright notices are reproduced below.
5
+#
6
+# Those libraries were written for the Raspberry Pi. This modification is
7
+# intended for the MicroPython and esp8266 boards.
8
+#
9
+# Copyright (c) 2014 Adafruit Industries
10
+# Author: Tony DiCola
11
+#
12
+# Based on the BMP280 driver with BME280 changes provided by
13
+# David J Taylor, Edinburgh (www.satsignal.eu)
14
+#
15
+# Based on Adafruit_I2C.py created by Kevin Townsend.
16
+#
17
+# Permission is hereby granted, free of charge, to any person obtaining a copy
18
+# of this software and associated documentation files (the "Software"), to deal
19
+# in the Software without restriction, including without limitation the rights
20
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
21
+# copies of the Software, and to permit persons to whom the Software is
22
+# furnished to do so, subject to the following conditions:
23
+#
24
+# The above copyright notice and this permission notice shall be included in
25
+# all copies or substantial portions of the Software.
26
+#
27
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
33
+# THE SOFTWARE.
34
+
35
+import time
36
+from ustruct import unpack, unpack_from
37
+from array import array
38
+
39
+# BME280 default address.
40
+BME280_I2CADDR = 0x76
41
+
42
+# Operating Modes
43
+BME280_OSAMPLE_1 = 1
44
+BME280_OSAMPLE_2 = 2
45
+BME280_OSAMPLE_4 = 3
46
+BME280_OSAMPLE_8 = 4
47
+BME280_OSAMPLE_16 = 5
48
+
49
+BME280_REGISTER_CONTROL_HUM = 0xF2
50
+BME280_REGISTER_CONTROL = 0xF4
51
+
52
+
53
+class BME280:
54
+
55
+    def __init__(self,
56
+                 mode=BME280_OSAMPLE_1,
57
+                 address=BME280_I2CADDR,
58
+                 i2c=None,
59
+                 **kwargs):
60
+        # Check that mode is valid.
61
+        if mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
62
+                        BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
63
+            raise ValueError(
64
+                'Unexpected mode value {0}. Set mode to one of '
65
+                'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or '
66
+                'BME280_ULTRAHIGHRES'.format(mode))
67
+        self._mode = mode
68
+        self.address = address
69
+        if i2c is None:
70
+            raise ValueError('An I2C object is required.')
71
+        self.i2c = i2c
72
+
73
+        # load calibration data
74
+        dig_88_a1 = self.i2c.readfrom_mem(self.address, 0x88, 26)
75
+        dig_e1_e7 = self.i2c.readfrom_mem(self.address, 0xE1, 7)
76
+        self.dig_T1, self.dig_T2, self.dig_T3, self.dig_P1, \
77
+            self.dig_P2, self.dig_P3, self.dig_P4, self.dig_P5, \
78
+            self.dig_P6, self.dig_P7, self.dig_P8, self.dig_P9, \
79
+            _, self.dig_H1 = unpack("<HhhHhhhhhhhhBB", dig_88_a1)
80
+
81
+        self.dig_H2, self.dig_H3 = unpack("<hB", dig_e1_e7)
82
+        e4_sign = unpack_from("<b", dig_e1_e7, 3)[0]
83
+        self.dig_H4 = (e4_sign << 4) | (dig_e1_e7[4] & 0xF)
84
+
85
+        e6_sign = unpack_from("<b", dig_e1_e7, 5)[0]
86
+        self.dig_H5 = (e6_sign << 4) | (dig_e1_e7[4] >> 4)
87
+
88
+        self.dig_H6 = unpack_from("<b", dig_e1_e7, 6)[0]
89
+
90
+        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
91
+                             bytearray([0x3F]))
92
+        self.t_fine = 0
93
+
94
+        # temporary data holders which stay allocated
95
+        self._l1_barray = bytearray(1)
96
+        self._l8_barray = bytearray(8)
97
+        self._l3_resultarray = array("i", [0, 0, 0])
98
+
99
+    def read_raw_data(self, result):
100
+        """ Reads the raw (uncompensated) data from the sensor.
101
+            Args:
102
+                result: array of length 3 or alike where the result will be
103
+                stored, in temperature, pressure, humidity order
104
+            Returns:
105
+                None
106
+        """
107
+
108
+        self._l1_barray[0] = self._mode
109
+        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL_HUM,
110
+                             self._l1_barray)
111
+        self._l1_barray[0] = self._mode << 5 | self._mode << 2 | 1
112
+        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
113
+                             self._l1_barray)
114
+
115
+        sleep_time = 1250 + 2300 * (1 << self._mode)
116
+        sleep_time = sleep_time + 2300 * (1 << self._mode) + 575
117
+        sleep_time = sleep_time + 2300 * (1 << self._mode) + 575
118
+        time.sleep_us(sleep_time)  # Wait the required time
119
+
120
+        # burst readout from 0xF7 to 0xFE, recommended by datasheet
121
+        self.i2c.readfrom_mem_into(self.address, 0xF7, self._l8_barray)
122
+        readout = self._l8_barray
123
+        # pressure(0xF7): ((msb << 16) | (lsb << 8) | xlsb) >> 4
124
+        raw_press = ((readout[0] << 16) | (readout[1] << 8) | readout[2]) >> 4
125
+        # temperature(0xFA): ((msb << 16) | (lsb << 8) | xlsb) >> 4
126
+        raw_temp = ((readout[3] << 16) | (readout[4] << 8) | readout[5]) >> 4
127
+        # humidity(0xFD): (msb << 8) | lsb
128
+        raw_hum = (readout[6] << 8) | readout[7]
129
+
130
+        result[0] = raw_temp
131
+        result[1] = raw_press
132
+        result[2] = raw_hum
133
+
134
+    def read_compensated_data(self, result=None):
135
+        """ Reads the data from the sensor and returns the compensated data.
136
+            Args:
137
+                result: array of length 3 or alike where the result will be
138
+                stored, in temperature, pressure, humidity order. You may use
139
+                this to read out the sensor without allocating heap memory
140
+            Returns:
141
+                array with temperature, pressure, humidity. Will be the one from
142
+                the result parameter if not None
143
+        """
144
+        self.read_raw_data(self._l3_resultarray)
145
+        raw_temp, raw_press, raw_hum = self._l3_resultarray
146
+        # temperature
147
+        var1 = ((raw_temp >> 3) - (self.dig_T1 << 1)) * (self.dig_T2 >> 11)
148
+        var2 = (((((raw_temp >> 4) - self.dig_T1) *
149
+                  ((raw_temp >> 4) - self.dig_T1)) >> 12) * self.dig_T3) >> 14
150
+        self.t_fine = var1 + var2
151
+        temp = (self.t_fine * 5 + 128) >> 8
152
+
153
+        # pressure
154
+        var1 = self.t_fine - 128000
155
+        var2 = var1 * var1 * self.dig_P6
156
+        var2 = var2 + ((var1 * self.dig_P5) << 17)
157
+        var2 = var2 + (self.dig_P4 << 35)
158
+        var1 = (((var1 * var1 * self.dig_P3) >> 8) +
159
+                ((var1 * self.dig_P2) << 12))
160
+        var1 = (((1 << 47) + var1) * self.dig_P1) >> 33
161
+        if var1 == 0:
162
+            pressure = 0
163
+        else:
164
+            p = 1048576 - raw_press
165
+            p = (((p << 31) - var2) * 3125) // var1
166
+            var1 = (self.dig_P9 * (p >> 13) * (p >> 13)) >> 25
167
+            var2 = (self.dig_P8 * p) >> 19
168
+            pressure = ((p + var1 + var2) >> 8) + (self.dig_P7 << 4)
169
+
170
+        # humidity
171
+        h = self.t_fine - 76800
172
+        h = (((((raw_hum << 14) - (self.dig_H4 << 20) -
173
+                (self.dig_H5 * h)) + 16384)
174
+              >> 15) * (((((((h * self.dig_H6) >> 10) *
175
+                            (((h * self.dig_H3) >> 11) + 32768)) >> 10) +
176
+                          2097152) * self.dig_H2 + 8192) >> 14))
177
+        h = h - (((((h >> 15) * (h >> 15)) >> 7) * self.dig_H1) >> 4)
178
+        h = 0 if h < 0 else h
179
+        h = 419430400 if h > 419430400 else h
180
+        humidity = h >> 12
181
+
182
+        if result:
183
+            result[0] = temp
184
+            result[1] = pressure
185
+            result[2] = humidity
186
+            return result
187
+
188
+        return array("i", (temp, pressure, humidity))
189
+
190
+    @property
191
+    def values(self):
192
+        """ human readable values """
193
+
194
+        t, p, h = self.read_compensated_data()
195
+
196
+        p = p // 256
197
+        pi = p // 100
198
+        pd = p - pi * 100
199
+
200
+        hi = h // 1024
201
+        hd = h * 100 // 1024 - hi * 100
202
+        return ("{}C".format(t / 100), "{}.{:02d}hPa".format(pi, pd),
203
+                "{}.{:02d}%".format(hi, hd))
204
+
205
+    @property
206
+    def values2(self):
207
+        """ human readable values without string """
208
+        t, p, h = self.read_compensated_data()
209
+        p = p // 256
210
+        pi = p // 100
211
+        pd = p - pi * 100
212
+
213
+        hi = h // 1024
214
+        hd = h * 100 // 1024 - hi * 100
215
+
216
+        return (t/100,pi+pd/100,hi+hd/100)

+ 338
- 0
user_lib/vl53l0x.py View File

@@ -0,0 +1,338 @@
1
+from micropython import const
2
+import ustruct
3
+import utime
4
+
5
+
6
+_IO_TIMEOUT = 1000
7
+_SYSRANGE_START = const(0x00)
8
+_EXTSUP_HV = const(0x89)
9
+_MSRC_CONFIG = const(0x60)
10
+_FINAL_RATE_RTN_LIMIT = const(0x44)
11
+_SYSTEM_SEQUENCE = const(0x01)
12
+_SPAD_REF_START = const(0x4f)
13
+_SPAD_ENABLES = const(0xb0)
14
+_REF_EN_START_SELECT = const(0xb6)
15
+_SPAD_NUM_REQUESTED = const(0x4e)
16
+_INTERRUPT_GPIO = const(0x0a)
17
+_INTERRUPT_CLEAR = const(0x0b)
18
+_GPIO_MUX_ACTIVE_HIGH = const(0x84)
19
+_RESULT_INTERRUPT_STATUS = const(0x13)
20
+_RESULT_RANGE_STATUS = const(0x14)
21
+_OSC_CALIBRATE = const(0xf8)
22
+_MEASURE_PERIOD = const(0x04)
23
+
24
+
25
+class TimeoutError(RuntimeError):
26
+    pass
27
+
28
+
29
+class VL53L0X:
30
+    def __init__(self, i2c, address=0x29):
31
+        self.i2c = i2c
32
+        self.address = address
33
+        self.init()
34
+        self._started = False
35
+
36
+    def _registers(self, register, values=None, struct='B'):
37
+        if values is None:
38
+            size = ustruct.calcsize(struct)
39
+            data = self.i2c.readfrom_mem(self.address, register, size)
40
+            values = ustruct.unpack(struct, data)
41
+            return values
42
+        data = ustruct.pack(struct, *values)
43
+        self.i2c.writeto_mem(self.address, register, data)
44
+
45
+    def _register(self, register, value=None, struct='B'):
46
+        if value is None:
47
+            return self._registers(register, struct=struct)[0]
48
+        self._registers(register, (value,), struct=struct)
49
+
50
+    def _flag(self, register=0x00, bit=0, value=None):
51
+        data = self._register(register)
52
+        mask = 1 << bit
53
+        if value is None:
54
+            return bool(data & mask)
55
+        elif value:
56
+            data |= mask
57
+        else:
58
+            data &= ~mask
59
+        self._register(register, data)
60
+
61
+    def _config(self, *config):
62
+        for register, value in config:
63
+            self._register(register, value)
64
+
65
+    def init(self, power2v8=True):
66
+        self._flag(_EXTSUP_HV, 0, power2v8)
67
+
68
+        # I2C standard mode
69
+        self._config(
70
+            (0x88, 0x00),
71
+
72
+            (0x80, 0x01),
73
+            (0xff, 0x01),
74
+            (0x00, 0x00),
75
+        )
76
+        self._stop_variable = self._register(0x91)
77
+        self._config(
78
+            (0x00, 0x01),
79
+            (0xff, 0x00),
80
+            (0x80, 0x00),
81
+        )
82
+
83
+        # disable signal_rate_msrc and signal_rate_pre_range limit checks
84
+        self._flag(_MSRC_CONFIG, 1, True)
85
+        self._flag(_MSRC_CONFIG, 4, True)
86
+
87
+        # rate_limit = 0.25
88
+        self._register(_FINAL_RATE_RTN_LIMIT, int(0.25 * (1 << 7)),
89
+                       struct='>H')
90
+
91
+        self._register(_SYSTEM_SEQUENCE, 0xff)
92
+
93
+        spad_count, is_aperture = self._spad_info()
94
+        spad_map = bytearray(self._registers(_SPAD_ENABLES, struct='6B'))
95
+
96
+        # set reference spads
97
+        self._config(
98
+            (0xff, 0x01),
99
+            (_SPAD_REF_START, 0x00),
100
+            (_SPAD_NUM_REQUESTED, 0x2c),
101
+            (0xff, 0x00),
102
+            (_REF_EN_START_SELECT, 0xb4),
103
+        )
104
+
105
+        spads_enabled = 0
106
+        for i in range(48):
107
+            if i < 12 and is_aperture or spads_enabled >= spad_count:
108
+                spad_map[i // 8] &= ~(1 << (i >> 2))
109
+            elif spad_map[i // 8] & (1 << (i >> 2)):
110
+                spads_enabled += 1
111
+
112
+        self._registers(_SPAD_ENABLES, spad_map, struct='6B')
113
+
114
+        self._config(
115
+            (0xff, 0x01),
116
+            (0x00, 0x00),
117
+
118
+            (0xff, 0x00),
119
+            (0x09, 0x00),
120
+            (0x10, 0x00),
121
+            (0x11, 0x00),
122
+
123
+            (0x24, 0x01),
124
+            (0x25, 0xFF),
125
+            (0x75, 0x00),
126
+
127
+            (0xFF, 0x01),
128
+            (0x4E, 0x2C),
129
+            (0x48, 0x00),
130
+            (0x30, 0x20),
131
+
132
+            (0xFF, 0x00),
133
+            (0x30, 0x09),
134
+            (0x54, 0x00),
135
+            (0x31, 0x04),
136
+            (0x32, 0x03),
137
+            (0x40, 0x83),
138
+            (0x46, 0x25),
139
+            (0x60, 0x00),
140
+            (0x27, 0x00),
141
+            (0x50, 0x06),
142
+            (0x51, 0x00),
143
+            (0x52, 0x96),
144
+            (0x56, 0x08),
145
+            (0x57, 0x30),
146
+            (0x61, 0x00),
147
+            (0x62, 0x00),
148
+            (0x64, 0x00),
149
+            (0x65, 0x00),
150
+            (0x66, 0xA0),
151
+
152
+            (0xFF, 0x01),
153
+            (0x22, 0x32),
154
+            (0x47, 0x14),
155
+            (0x49, 0xFF),
156
+            (0x4A, 0x00),
157
+
158
+            (0xFF, 0x00),
159
+            (0x7A, 0x0A),
160
+            (0x7B, 0x00),
161
+            (0x78, 0x21),
162
+
163
+            (0xFF, 0x01),
164
+            (0x23, 0x34),
165
+            (0x42, 0x00),
166
+            (0x44, 0xFF),
167
+            (0x45, 0x26),
168
+            (0x46, 0x05),
169
+            (0x40, 0x40),
170
+            (0x0E, 0x06),
171
+            (0x20, 0x1A),
172
+            (0x43, 0x40),
173
+
174
+            (0xFF, 0x00),
175
+            (0x34, 0x03),
176
+            (0x35, 0x44),
177
+
178
+            (0xFF, 0x01),
179
+            (0x31, 0x04),
180
+            (0x4B, 0x09),
181
+            (0x4C, 0x05),
182
+            (0x4D, 0x04),
183
+
184
+            (0xFF, 0x00),
185
+            (0x44, 0x00),
186
+            (0x45, 0x20),
187
+            (0x47, 0x08),
188
+            (0x48, 0x28),
189
+            (0x67, 0x00),
190
+            (0x70, 0x04),
191
+            (0x71, 0x01),
192
+            (0x72, 0xFE),
193
+            (0x76, 0x00),
194
+            (0x77, 0x00),
195
+
196
+            (0xFF, 0x01),
197
+            (0x0D, 0x01),
198
+
199
+            (0xFF, 0x00),
200
+            (0x80, 0x01),
201
+            (0x01, 0xF8),
202
+
203
+            (0xFF, 0x01),
204
+            (0x8E, 0x01),
205
+            (0x00, 0x01),
206
+            (0xFF, 0x00),
207
+            (0x80, 0x00),
208
+        )
209
+
210
+        self._register(_INTERRUPT_GPIO, 0x04)
211
+        self._flag(_GPIO_MUX_ACTIVE_HIGH, 4, False)
212
+        self._register(_INTERRUPT_CLEAR, 0x01)
213
+
214
+        # XXX Need to implement this.
215
+        #budget = self._timing_budget()
216
+        #self._register(_SYSTEM_SEQUENCE, 0xe8)
217
+        #self._timing_budget(budget)
218
+
219
+        self._register(_SYSTEM_SEQUENCE, 0x01)
220
+        self._calibrate(0x40)
221
+        self._register(_SYSTEM_SEQUENCE, 0x02)
222
+        self._calibrate(0x00)
223
+
224
+        self._register(_SYSTEM_SEQUENCE, 0xe8)
225
+
226
+    def _spad_info(self):
227
+        self._config(
228
+            (0x80, 0x01),
229
+            (0xff, 0x01),
230
+            (0x00, 0x00),
231
+
232
+            (0xff, 0x06),
233
+        )
234
+        self._flag(0x83, 3, True)
235
+        self._config(
236
+            (0xff, 0x07),
237
+            (0x81, 0x01),
238
+
239
+            (0x80, 0x01),
240
+
241
+            (0x94, 0x6b),
242
+            (0x83, 0x00),
243
+        )
244
+        for timeout in range(_IO_TIMEOUT):
245
+            if self._register(0x83):
246
+                break
247
+            utime.sleep_ms(1)
248
+        else:
249
+            raise TimeoutError()
250
+        self._config(
251
+            (0x83, 0x01),
252
+        )
253
+        value = self._register(0x92)
254
+        self._config(
255
+            (0x81, 0x00),
256
+            (0xff, 0x06),
257
+        )
258
+        self._flag(0x83, 3, False)
259
+        self._config(
260
+            (0xff, 0x01),
261
+            (0x00, 0x01),
262
+
263
+            (0xff, 0x00),
264
+            (0x80, 0x00),
265
+        )
266
+        count = value & 0x7f
267
+        is_aperture = bool(value & 0b10000000)
268
+        return count, is_aperture
269
+
270
+    def _calibrate(self, vhv_init_byte):
271
+        self._register(_SYSRANGE_START, 0x01 | vhv_init_byte)
272
+        for timeout in range(_IO_TIMEOUT):
273
+            if self._register(_RESULT_INTERRUPT_STATUS) & 0x07:
274
+                break
275
+            utime.sleep_ms(1)
276
+        else:
277
+            raise TimeoutError()
278
+        self._register(_INTERRUPT_CLEAR, 0x01)
279
+        self._register(_SYSRANGE_START, 0x00)
280
+
281
+    def start(self, period=0):
282
+        self._config(
283
+          (0x80, 0x01),
284
+          (0xFF, 0x01),
285
+          (0x00, 0x00),
286
+          (0x91, self._stop_variable),
287
+          (0x00, 0x01),
288
+          (0xFF, 0x00),
289
+          (0x80, 0x00),
290
+        )
291
+        if period:
292
+            oscilator = self._register(_OSC_CALIBRATE, struct='>H')
293
+            if oscilator:
294
+                period *= oscilator
295
+            self._register(_MEASURE_PERIOD, period, struct='>H')
296
+            self._register(_SYSRANGE_START, 0x04)
297
+        else:
298
+            self._register(_SYSRANGE_START, 0x02)
299
+        self._started = True
300
+
301
+    def stop(self):
302
+        self._register(_SYSRANGE_START, 0x01)
303
+        self._config(
304
+          (0xFF, 0x01),
305
+          (0x00, 0x00),
306
+          (0x91, self._stop_variable),
307
+          (0x00, 0x01),
308
+          (0xFF, 0x00),
309
+        )
310
+        self._started = False
311
+
312
+    def read(self):
313
+        if not self._started:
314
+            self._config(
315
+              (0x80, 0x01),
316
+              (0xFF, 0x01),
317
+              (0x00, 0x00),
318
+              (0x91, self._stop_variable),
319
+              (0x00, 0x01),
320
+              (0xFF, 0x00),
321
+              (0x80, 0x00),
322
+              (_SYSRANGE_START, 0x01),
323
+            )
324
+            for timeout in range(_IO_TIMEOUT):
325
+                if not self._register(_SYSRANGE_START) & 0x01:
326
+                    break
327
+                utime.sleep_ms(1)
328
+            else:
329
+                raise TimeoutError()
330
+        for timeout in range(_IO_TIMEOUT):
331
+            if self._register(_RESULT_INTERRUPT_STATUS) & 0x07:
332
+                break
333
+            utime.sleep_ms(1)
334
+        else:
335
+            raise TimeoutError()
336
+        value = self._register(_RESULT_RANGE_STATUS + 10, struct='>H')
337
+        self._register(_INTERRUPT_CLEAR, 0x01)
338
+        return value

Loading…
Cancel
Save