Browse Source

first commit

master
manfraid 1 year ago
commit
a054784cd1

+ 1
- 0
.gitignore View File

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

+ 19
- 0
__list.py View File

@@ -0,0 +1,19 @@
import os
import sys
def _list_fs(path=""):
try:
l = os.listdir(path)
if path:
sys.stdout.write(path + "/\n")
else:
sys.stdout.write("###\n")
for x in l:
_list_fs(x)
sys.stdout.write("/\n")
except OSError:
# Is file
sys.stdout.write(path + "\n")
_list_fs()

+ 41
- 0
function.py View File

@@ -0,0 +1,41 @@
import esp
def dsleeps(s):
print("Sleep for {}s".format(s))
esp.deepsleep(1000000 * s)
def dsleepm(m):
if m > 71:
print("Limite de temps a 71m")
dur = 71*60
else:
dur = m * 60
esp.deepsleep(1000000 * dur)
def connect():
import network
ssid = "nomReseauWiFi"
password = "motDePasseWiFi"
station = network.WLAN(network.STA_IF)
if station.isconnected() == True:
print("Already connected")
return
station.active(True)
station.connect()
while station.isconnected() == False:
pass
print("Connection successful")
print(station.ifconfig())
def disconnect():
import network
station = network.WLAN(network.STA_IF)
station.disconnect()
station.active(False)

+ 8
- 0
list_ssid.py View File

@@ -0,0 +1,8 @@
#List_ssid
import network
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
print(sta_if.scan())

+ 56
- 0
test.py View File

@@ -0,0 +1,56 @@
import network
D0 = 16
D1 = 5
D2 = 4
D3 = 0
D4 = 2
D5 = 14
D6 = 12
D7 = 13
D8 = 15
sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)
sta_if.active(True)
sta_if.active()
ap_if.active()
ap_if.ifconfig()
sta_if.connect('SSID','MDP')
sta_if.isconnected()
sta_if.ifconfig()
ap_if.active(False)
sta_if.scan()
from machine import Pin
p0 = Pin(0, Pin.IN)
import webrepl_setup
import webrepl
webrepl.start()
import machine
pin = machine.Pin(2, machine.Pin.OUT)
pin.value(1)
import esp
pwm12 = machine.PWM(pin)
pwm12
import time, math
def pulse(l, t):
for i in range(200):
l.duty(int(math.sin(i / 200 * math.pi) * 500 + 500))
time.sleep_ms(t)
pulse(pwm12, 1)
for i in range(100):
pulse(pwm12, 2)
pwm12.deinit()

+ 22
- 0
test_D4.py View File

@@ -0,0 +1,22 @@
from machine import Pin,PWM
import time, math
import esp
pin = Pin(2, Pin.OUT)
pin.value(1)
pwm2 = PWM(pin)
def pulse(l, t):
for i in range(25):
l.duty(int(math.sin(i / 25 * math.pi) * 1023))
time.sleep_ms(t)
pulse(pwm2, 100)
for i in range(30):
print("Pulse n°: {}".format(i))
pulse(pwm2, 10)
time.sleep_ms(50)
pwm2.deinit()
time.sleep_ms(50)
pin.value(1)

+ 24
- 0
test_DS18B20.py View File

@@ -0,0 +1,24 @@
import time
import machine
import onewire, ds18x20
D5 = 14
# the device is on GPIO12
dat = machine.Pin(D5)
# create the onewire object
ds = ds18x20.DS18X20(onewire.OneWire(dat))
# scan for devices on the bus
roms = ds.scan()
print('found devices:', roms)
# loop 10 times and print all temperatures
for i in range(10):
print('temperatures:', end=' ')
ds.convert_temp()
time.sleep_ms(750)
for rom in roms:
print(ds.read_temp(rom), end=' ')
print()

+ 20
- 0
test_bmp280.py View File

@@ -0,0 +1,20 @@
from machine import Pin,I2C
from bme280 import BME280
D0 = 16
D1 = 5
D2 = 4
D3 = 0
D4 = 2
D5 = 14
D6 = 12
D7 = 13
D8 = 15
# Rouge SCL D1, marron SDA D2
i2c = I2C(scl=Pin(D1),sda=Pin(D2))
print(i2c.scan())
bmp = BME280(i2c=i2c)
print(bmp.values)
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 @@
from apds9960.device import APDS9960, uAPDS9960

__all__ = [ 'APDS9960', 'uAPDS9960', ]

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

@@ -0,0 +1,169 @@
# APDS9960 i2c address
APDS9960_I2C_ADDR = 0x39

# APDS9960 gesture parameters
APDS9960_GESTURE_THRESHOLD_OUT = 10
APDS9960_GESTURE_SENSITIVITY_1 = 50
APDS9960_GESTURE_SENSITIVITY_2 = 20

# APDS9960 device IDs
APDS9960_DEV_ID = [0xab, 0x9c, 0xa8]

# APDS9960 times
APDS9960_TIME_FIFO_PAUSE = 0.03

# APDS9960 register addresses
APDS9960_REG_ENABLE = 0x80
APDS9960_REG_ATIME = 0x81
APDS9960_REG_WTIME = 0x83
APDS9960_REG_AILTL = 0x84
APDS9960_REG_AILTH = 0x85
APDS9960_REG_AIHTL = 0x86
APDS9960_REG_AIHTH = 0x87
APDS9960_REG_PILT = 0x89
APDS9960_REG_PIHT = 0x8b
APDS9960_REG_PERS = 0x8c
APDS9960_REG_CONFIG1 = 0x8d
APDS9960_REG_PPULSE = 0x8e
APDS9960_REG_CONTROL = 0x8f
APDS9960_REG_CONFIG2 = 0x90
APDS9960_REG_ID = 0x92
APDS9960_REG_STATUS = 0x93
APDS9960_REG_CDATAL = 0x94
APDS9960_REG_CDATAH = 0x95
APDS9960_REG_RDATAL = 0x96
APDS9960_REG_RDATAH = 0x97
APDS9960_REG_GDATAL = 0x98
APDS9960_REG_GDATAH = 0x99
APDS9960_REG_BDATAL = 0x9a
APDS9960_REG_BDATAH = 0x9b
APDS9960_REG_PDATA = 0x9c
APDS9960_REG_POFFSET_UR = 0x9d
APDS9960_REG_POFFSET_DL = 0x9e
APDS9960_REG_CONFIG3 = 0x9f
APDS9960_REG_GPENTH = 0xa0
APDS9960_REG_GEXTH = 0xa1
APDS9960_REG_GCONF1 = 0xa2
APDS9960_REG_GCONF2 = 0xa3
APDS9960_REG_GOFFSET_U = 0xa4
APDS9960_REG_GOFFSET_D = 0xa5
APDS9960_REG_GOFFSET_L = 0xa7
APDS9960_REG_GOFFSET_R = 0xa9
APDS9960_REG_GPULSE = 0xa6
APDS9960_REG_GCONF3 = 0xaA
APDS9960_REG_GCONF4 = 0xaB
APDS9960_REG_GFLVL = 0xae
APDS9960_REG_GSTATUS = 0xaf
APDS9960_REG_IFORCE = 0xe4
APDS9960_REG_PICLEAR = 0xe5
APDS9960_REG_CICLEAR = 0xe6
APDS9960_REG_AICLEAR = 0xe7
APDS9960_REG_GFIFO_U = 0xfc
APDS9960_REG_GFIFO_D = 0xfd
APDS9960_REG_GFIFO_L = 0xfe
APDS9960_REG_GFIFO_R = 0xff

# APDS9960 bit fields
APDS9960_BIT_PON = 0b00000001
APDS9960_BIT_AEN = 0b00000010
APDS9960_BIT_PEN = 0b00000100
APDS9960_BIT_WEN = 0b00001000
APSD9960_BIT_AIEN =0b00010000
APDS9960_BIT_PIEN = 0b00100000
APDS9960_BIT_GEN = 0b01000000
APDS9960_BIT_GVALID = 0b00000001

# APDS9960 modes
APDS9960_MODE_POWER = 0
APDS9960_MODE_AMBIENT_LIGHT = 1
APDS9960_MODE_PROXIMITY = 2
APDS9960_MODE_WAIT = 3
APDS9960_MODE_AMBIENT_LIGHT_INT = 4
APDS9960_MODE_PROXIMITY_INT = 5
APDS9960_MODE_GESTURE = 6
APDS9960_MODE_ALL = 7

# LED Drive values
APDS9960_LED_DRIVE_100MA = 0
APDS9960_LED_DRIVE_50MA = 1
APDS9960_LED_DRIVE_25MA = 2
APDS9960_LED_DRIVE_12_5MA = 3

# Proximity Gain (PGAIN) values
APDS9960_PGAIN_1X = 0
APDS9960_PGAIN_2X = 1
APDS9960_PGAIN_4X = 2
APDS9960_PGAIN_8X = 3

# ALS Gain (AGAIN) values
APDS9960_AGAIN_1X = 0
APDS9960_AGAIN_4X = 1
APDS9960_AGAIN_16X = 2
APDS9960_AGAIN_64X = 3

# Gesture Gain (GGAIN) values
APDS9960_GGAIN_1X = 0
APDS9960_GGAIN_2X = 1
APDS9960_GGAIN_4X = 2
APDS9960_GGAIN_8X = 3

# LED Boost values
APDS9960_LED_BOOST_100 = 0
APDS9960_LED_BOOST_150 = 1
APDS9960_LED_BOOST_200 = 2
APDS9960_LED_BOOST_300 = 3

# Gesture wait time values
APDS9960_GWTIME_0MS = 0
APDS9960_GWTIME_2_8MS = 1
APDS9960_GWTIME_5_6MS = 2
APDS9960_GWTIME_8_4MS = 3
APDS9960_GWTIME_14_0MS = 4
APDS9960_GWTIME_22_4MS = 5
APDS9960_GWTIME_30_8MS = 6
APDS9960_GWTIME_39_2MS = 7

# Default values
APDS9960_DEFAULT_ATIME = 219 # 103ms
APDS9960_DEFAULT_WTIME = 246 # 27ms
APDS9960_DEFAULT_PROX_PPULSE = 0x87 # 16us, 8 pulses
APDS9960_DEFAULT_GESTURE_PPULSE = 0x89 # 16us, 10 pulses
APDS9960_DEFAULT_POFFSET_UR = 0 # 0 offset
APDS9960_DEFAULT_POFFSET_DL = 0 # 0 offset
APDS9960_DEFAULT_CONFIG1 = 0x60 # No 12x wait (WTIME) factor
APDS9960_DEFAULT_LDRIVE = APDS9960_LED_DRIVE_100MA
APDS9960_DEFAULT_PGAIN = APDS9960_PGAIN_4X
APDS9960_DEFAULT_AGAIN = APDS9960_AGAIN_4X
APDS9960_DEFAULT_PILT = 0 # Low proximity threshold
APDS9960_DEFAULT_PIHT = 50 # High proximity threshold
APDS9960_DEFAULT_AILT = 0xffff # Force interrupt for calibration
APDS9960_DEFAULT_AIHT = 0
APDS9960_DEFAULT_PERS = 0x11 # 2 consecutive prox or ALS for int.
APDS9960_DEFAULT_CONFIG2 = 0x01 # No saturation interrupts or LED boost
APDS9960_DEFAULT_CONFIG3 = 0 # Enable all photodiodes, no SAI
APDS9960_DEFAULT_GPENTH = 40 # Threshold for entering gesture mode
APDS9960_DEFAULT_GEXTH = 30 # Threshold for exiting gesture mode
APDS9960_DEFAULT_GCONF1 = 0x40 # 4 gesture events for int., 1 for exit
APDS9960_DEFAULT_GGAIN = APDS9960_GGAIN_4X
APDS9960_DEFAULT_GLDRIVE = APDS9960_LED_DRIVE_100MA
APDS9960_DEFAULT_GWTIME = APDS9960_GWTIME_2_8MS
APDS9960_DEFAULT_GOFFSET = 0 # No offset scaling for gesture mode
APDS9960_DEFAULT_GPULSE = 0xc9 # 32us, 10 pulses
APDS9960_DEFAULT_GCONF3 = 0 # All photodiodes active during gesture
APDS9960_DEFAULT_GIEN = 0 # Disable gesture interrupts

# gesture directions
APDS9960_DIR_NONE = 0
APDS9960_DIR_LEFT = 1
APDS9960_DIR_RIGHT = 2
APDS9960_DIR_UP = 3
APDS9960_DIR_DOWN = 4
APDS9960_DIR_NEAR = 5
APDS9960_DIR_FAR = 6
APDS9960_DIR_ALL = 7

# state definitions
APDS9960_STATE_NA = 0
APDS9960_STATE_NEAR = 1
APDS9960_STATE_FAR = 2
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 @@
class ADPS9960InvalidDevId(ValueError):
def __init__(self, id, valid_ids):
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])))

class ADPS9960InvalidMode(ValueError):
def __init__(self, mode):
Exception.__init__(self, "Feature mode {} is invalid!".format(mode))

+ 955
- 0
user_lib/apds9960_prox.py View File

@@ -0,0 +1,955 @@
from micropython import const
from time import sleep
# APDS9960 i2c address
APDS9960_I2C_ADDR = const(0x39)
# APDS9960 gesture parameters
APDS9960_GESTURE_THRESHOLD_OUT = const(10)
APDS9960_GESTURE_SENSITIVITY_1 = const(50)
APDS9960_GESTURE_SENSITIVITY_2 = const(20)
# APDS9960 device IDs
APDS9960_DEV_ID = [0xab, 0x9c, 0xa8]
# APDS9960 times
APDS9960_TIME_FIFO_PAUSE = 0.03
# APDS9960 register addresses
APDS9960_REG_ENABLE = const(0x80)
APDS9960_REG_ATIME = const(0x81)
APDS9960_REG_WTIME = const(0x83)
APDS9960_REG_AILTL = const(0x84)
APDS9960_REG_AILTH = const(0x85)
APDS9960_REG_AIHTL = const(0x86)
APDS9960_REG_AIHTH = const(0x87)
APDS9960_REG_PILT = const(0x89)
APDS9960_REG_PIHT = const(0x8b)
APDS9960_REG_PERS = const(0x8c)
APDS9960_REG_CONFIG1 = const(0x8d)
APDS9960_REG_PPULSE = const(0x8e)
APDS9960_REG_CONTROL = const(0x8f)
APDS9960_REG_CONFIG2 = const(0x90)
APDS9960_REG_ID = const(0x92)
APDS9960_REG_STATUS = const(0x93)
APDS9960_REG_CDATAL = const(0x94)
APDS9960_REG_CDATAH = const(0x95)
APDS9960_REG_RDATAL = const(0x96)
APDS9960_REG_RDATAH = const(0x97)
APDS9960_REG_GDATAL = const(0x98)
APDS9960_REG_GDATAH = const(0x99)
APDS9960_REG_BDATAL = const(0x9a)
APDS9960_REG_BDATAH = const(0x9b)
APDS9960_REG_PDATA = const(0x9c)
APDS9960_REG_POFFSET_UR = const(0x9d)
APDS9960_REG_POFFSET_DL = const(0x9e)
APDS9960_REG_CONFIG3 = const(0x9f)
APDS9960_REG_GPENTH = const(0xa0)
APDS9960_REG_GEXTH = const(0xa1)
APDS9960_REG_GCONF1 = const(0xa2)
APDS9960_REG_GCONF2 = const(0xa3)
APDS9960_REG_GOFFSET_U = const(0xa4)
APDS9960_REG_GOFFSET_D = const(0xa5)
APDS9960_REG_GOFFSET_L = const(0xa7)
APDS9960_REG_GOFFSET_R = const(0xa9)
APDS9960_REG_GPULSE = const(0xa6)
APDS9960_REG_GCONF3 = const(0xaA)
APDS9960_REG_GCONF4 = const(0xaB)
APDS9960_REG_GFLVL = const(0xae)
APDS9960_REG_GSTATUS = const(0xaf)
APDS9960_REG_IFORCE = const(0xe4)
APDS9960_REG_PICLEAR = const(0xe5)
APDS9960_REG_CICLEAR = const(0xe6)
APDS9960_REG_AICLEAR = const(0xe7)
APDS9960_REG_GFIFO_U = const(0xfc)
APDS9960_REG_GFIFO_D = const(0xfd)
APDS9960_REG_GFIFO_L = const(0xfe)
APDS9960_REG_GFIFO_R = const(0xff)
# APDS9960 bit fields
APDS9960_BIT_PON = const(0b00000001)
APDS9960_BIT_AEN = const(0b00000010)
APDS9960_BIT_PEN = const(0b00000100)
APDS9960_BIT_WEN = const(0b00001000)
APSD9960_BIT_AIEN = const(0b00010000)
APDS9960_BIT_PIEN = const(0b00100000)
APDS9960_BIT_GEN = const(0b01000000)
APDS9960_BIT_GVALID = const(0b00000001)
# APDS9960 modes
APDS9960_MODE_POWER = const(0)
APDS9960_MODE_AMBIENT_LIGHT = const(1)
APDS9960_MODE_PROXIMITY = const(2)
APDS9960_MODE_WAIT = const(3)
APDS9960_MODE_AMBIENT_LIGHT_INT = const(4)
APDS9960_MODE_PROXIMITY_INT = const(5)
APDS9960_MODE_GESTURE = const(6)
APDS9960_MODE_ALL = const(7)
# LED Drive values
APDS9960_LED_DRIVE_100MA = const(0)
APDS9960_LED_DRIVE_50MA = const(1)
APDS9960_LED_DRIVE_25MA = const(2)
APDS9960_LED_DRIVE_12_5MA = const(3)
# Proximity Gain (PGAIN) values
APDS9960_PGAIN_1X = const(0)
APDS9960_PGAIN_2X = const(1)
APDS9960_PGAIN_4X = const(2)
APDS9960_PGAIN_8X = const(3)
# ALS Gain (AGAIN) values
APDS9960_AGAIN_1X = const(0)
APDS9960_AGAIN_4X = const(1)
APDS9960_AGAIN_16X = const(2)
APDS9960_AGAIN_64X = const(3)
# Gesture Gain (GGAIN) values
APDS9960_GGAIN_1X = const(0)
APDS9960_GGAIN_2X = const(1)
APDS9960_GGAIN_4X = const(2)
APDS9960_GGAIN_8X = const(3)
# LED Boost values
APDS9960_LED_BOOST_100 = const(0)
APDS9960_LED_BOOST_150 = const(1)
APDS9960_LED_BOOST_200 = const(2)
APDS9960_LED_BOOST_300 = const(3)
# Gesture wait time values
APDS9960_GWTIME_0MS = const(0)
APDS9960_GWTIME_2_8MS = const(1)
APDS9960_GWTIME_5_6MS = const(2)
APDS9960_GWTIME_8_4MS = const(3)
APDS9960_GWTIME_14_0MS = const(4)
APDS9960_GWTIME_22_4MS = const(5)
APDS9960_GWTIME_30_8MS = const(6)
APDS9960_GWTIME_39_2MS = const(7)
# Default values
APDS9960_DEFAULT_ATIME = const(219) # 103ms
APDS9960_DEFAULT_WTIME = const(246) # 27ms
APDS9960_DEFAULT_PROX_PPULSE = const(0x87) # 16us, 8 pulses
APDS9960_DEFAULT_GESTURE_PPULSE = const(0x89) # 16us, 10 pulses
APDS9960_DEFAULT_POFFSET_UR = const(0) # 0 offset
APDS9960_DEFAULT_POFFSET_DL = const(0) # 0 offset
APDS9960_DEFAULT_CONFIG1 = const(0x60) # No 12x wait (WTIME) factor
APDS9960_DEFAULT_LDRIVE = APDS9960_LED_DRIVE_100MA
APDS9960_DEFAULT_PGAIN = APDS9960_PGAIN_4X
APDS9960_DEFAULT_AGAIN = APDS9960_AGAIN_4X
APDS9960_DEFAULT_PILT = const(0) # Low proximity threshold
APDS9960_DEFAULT_PIHT = const(50) # High proximity threshold
APDS9960_DEFAULT_AILT = const(0xffff) # Force interrupt for calibration
APDS9960_DEFAULT_AIHT = const(0)
APDS9960_DEFAULT_PERS = const(0x11) # 2 consecutive prox or ALS for int.
APDS9960_DEFAULT_CONFIG2 = const(0x01) # No saturation interrupts or LED boost
APDS9960_DEFAULT_CONFIG3 = const(0) # Enable all photodiodes, no SAI
APDS9960_DEFAULT_GPENTH = const(40) # Threshold for entering gesture mode
APDS9960_DEFAULT_GEXTH = const(30) # Threshold for exiting gesture mode
APDS9960_DEFAULT_GCONF1 = const(0x40) # 4 gesture events for int., 1 for exit
APDS9960_DEFAULT_GGAIN = APDS9960_GGAIN_4X
APDS9960_DEFAULT_GLDRIVE = APDS9960_LED_DRIVE_100MA
APDS9960_DEFAULT_GWTIME = APDS9960_GWTIME_2_8MS
APDS9960_DEFAULT_GOFFSET = const(0) # No offset scaling for gesture mode
APDS9960_DEFAULT_GPULSE = const(0xc9) # 32us, 10 pulses
APDS9960_DEFAULT_GCONF3 = const(0) # All photodiodes active during gesture
APDS9960_DEFAULT_GIEN = const(0) # Disable gesture interrupts
# gesture directions
APDS9960_DIR_NONE = const(0)
APDS9960_DIR_LEFT = const(1)
APDS9960_DIR_RIGHT = const(2)
APDS9960_DIR_UP = const(3)
APDS9960_DIR_DOWN = const(4)
APDS9960_DIR_NEAR = const(5)
APDS9960_DIR_FAR = const(6)
APDS9960_DIR_ALL = const(7)
# state definitions
APDS9960_STATE_NA = const(0)
APDS9960_STATE_NEAR = const(1)
APDS9960_STATE_FAR = const(2)
APDS9960_STATE_ALL = const(3)
class ADPS9960InvalidDevId(ValueError):
def __init__(self, id, valid_ids):
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])))
class ADPS9960InvalidMode(ValueError):
def __init__(self, mode):
Exception.__init__(self, "Feature mode {} is invalid!".format(mode))
class APDS9960:
class GestureData:
def __init__(self):
self.u_data = [0] * 32
self.d_data = [0] * 32
self.l_data = [0] * 32
self.r_data = [0] * 32
self.index = 0
self.total_gestures = 0
self.in_threshold = 0
self.out_threshold = 0
def __init__(self, bus, address=APDS9960_I2C_ADDR, valid_id=APDS9960_DEV_ID):
# I2C stuff
self.address = address
self.bus = bus
# instance variables for gesture detection
self.gesture_ud_delta_ = 0
self.gesture_lr_delta_ = 0
self.gesture_ud_count_ = 0
self.gesture_lr_count_ = 0
self.gesture_near_count_ = 0
self.gesture_far_count_ = 0
self.gesture_state_ = 0
self.gesture_motion_ = APDS9960_DIR_NONE
self.gesture_data_ = APDS9960.GestureData()
# check device id
self.dev_id = self._read_byte_data(APDS9960_REG_ID)
if not self.dev_id in valid_id:
raise ADPS9960InvalidDevId(self.dev_id, valid_id)
# disable all features
self.setMode(APDS9960_MODE_ALL, False)
# set default values for ambient light and proximity registers
self._write_byte_data(APDS9960_REG_ATIME, APDS9960_DEFAULT_ATIME)
self._write_byte_data(APDS9960_REG_WTIME, APDS9960_DEFAULT_WTIME)
self._write_byte_data(APDS9960_REG_PPULSE, APDS9960_DEFAULT_PROX_PPULSE)
self._write_byte_data(APDS9960_REG_POFFSET_UR, APDS9960_DEFAULT_POFFSET_UR)
self._write_byte_data(APDS9960_REG_POFFSET_DL, APDS9960_DEFAULT_POFFSET_DL)
self._write_byte_data(APDS9960_REG_CONFIG1, APDS9960_DEFAULT_CONFIG1)
self.setLEDDrive(APDS9960_DEFAULT_LDRIVE)
self.setProximityGain(APDS9960_DEFAULT_PGAIN)
self.setAmbientLightGain(APDS9960_DEFAULT_AGAIN)
self.setProxIntLowThresh(APDS9960_DEFAULT_PILT)
self.setProxIntHighThresh(APDS9960_DEFAULT_PIHT)
self.setLightIntLowThreshold(APDS9960_DEFAULT_AILT)
self.setLightIntHighThreshold(APDS9960_DEFAULT_AIHT)
self._write_byte_data(APDS9960_REG_PERS, APDS9960_DEFAULT_PERS)
self._write_byte_data(APDS9960_REG_CONFIG2, APDS9960_DEFAULT_CONFIG2)
self._write_byte_data(APDS9960_REG_CONFIG3, APDS9960_DEFAULT_CONFIG3)
def getMode(self):
return self._read_byte_data(APDS9960_REG_ENABLE)
def setMode(self, mode, enable=True):
# read ENABLE register
reg_val = self.getMode()
if mode < 0 or mode > APDS9960_MODE_ALL:
raise ADPS9960InvalidMode(mode)
# change bit(s) in ENABLE register */
if mode == APDS9960_MODE_ALL:
if enable:
reg_val = 0x7f
else:
reg_val = 0x00
else:
if enable:
reg_val |= (1 << mode);
else:
reg_val &= ~(1 << mode);
# write value to ENABLE register
self._write_byte_data(APDS9960_REG_ENABLE, reg_val)
# start the light (R/G/B/Ambient) sensor
def enableLightSensor(self, interrupts=True):
self.setAmbientLightGain(APDS9960_DEFAULT_AGAIN)
self.setAmbientLightIntEnable(interrupts)
self.enablePower()
self.setMode(APDS9960_MODE_AMBIENT_LIGHT, True)
# stop the light sensor
def disableLightSensor(self):
self.setAmbientLightIntEnable(False)
self.setMode(APDS9960_MODE_AMBIENT_LIGHT, False)
# start the proximity sensor
def enableProximitySensor(self, interrupts=True):
self.setProximityGain(APDS9960_DEFAULT_PGAIN)
self.setLEDDrive(APDS9960_DEFAULT_LDRIVE)
self.setProximityIntEnable(interrupts)
self.enablePower()
self.setMode(APDS9960_MODE_PROXIMITY, True)
# stop the proximity sensor
def disableProximitySensor(self):
self.setProximityIntEnable(False)
self.setMode(APDS9960_MODE_PROXIMITY, False)
# turn the APDS-9960 on
def enablePower(self):
self.setMode(APDS9960_MODE_POWER, True)
def disablePower(self):
# turn the APDS-9960 off
self.setMode(APDS9960_MODE_POWER, False)
# *******************************************************************************
# ambient light and color sensor controls
# *******************************************************************************
# reads the ambient (clear) light level as a 16-bit value
def readAmbientLight(self):
# read value from clear channel, low byte register
l = self._read_byte_data(APDS9960_REG_CDATAL)
# read value from clear channel, high byte register
h = self._read_byte_data(APDS9960_REG_CDATAH)
return l + (h << 8)
# reads the red light level as a 16-bit value
def readRedLight(self):
# read value from red channel, low byte register
l = self._read_byte_data(APDS9960_REG_RDATAL)
# read value from red channel, high byte register
h = self._read_byte_data(APDS9960_REG_RDATAH)
return l + (h << 8)
# reads the green light level as a 16-bit value
def readGreenLight(self):
# read value from green channel, low byte register
l = self._read_byte_data(APDS9960_REG_GDATAL)
# read value from green channel, high byte register
h = self._read_byte_data(APDS9960_REG_GDATAH)
return l + (h << 8)
# reads the blue light level as a 16-bit value
def readBlueLight(self):
# read value from blue channel, low byte register
l = self._read_byte_data(APDS9960_REG_BDATAL)
# read value from blue channel, high byte register
h = self._read_byte_data(APDS9960_REG_BDATAH)
return l + (h << 8)
# *******************************************************************************
# Proximity sensor controls
# *******************************************************************************
# reads the proximity level as an 8-bit value
def readProximity(self):
return self._read_byte_data(APDS9960_REG_PDATA)
# *******************************************************************************
# Getters and setters for register values
# *******************************************************************************
def getProxIntLowThresh(self):
"""Returns the lower threshold for proximity detection
"""
return self._read_byte_data(APDS9960_REG_PILT)
def setProxIntLowThresh(self, threshold):
"""Sets the lower threshold for proximity detection.
"""
self._write_byte_data(APDS9960_REG_PILT, threshold)
def getProxIntHighThresh(self):
"""Returns the high threshold for proximity detection.
"""
return self._read_byte_data(APDS9960_REG_PIHT)
def setProxIntHighThresh(self, threshold):
"""Sets the high threshold for proximity detection.
"""
self._write_byte_data(APDS9960_REG_PIHT, threshold)
def getLEDDrive(self):
"""Returns LED drive strength for proximity and ALS.
Value LED Current
0 100 mA
1 50 mA
2 25 mA
3 12.5 mA
Returns:
int: the value of the LED drive strength
"""
val = self._read_byte_data(APDS9960_REG_CONTROL)
# shift and mask out LED drive bits
return (val >> 6) & 0b00000011
def setLEDDrive(self, drive):
"""Sets LED drive strength for proximity and ALS.
Value LED Current
0 100 mA
1 50 mA
2 25 mA
3 12.5 mA
Args:
drive (int): value for the LED drive strength
"""
val = self._read_byte_data(APDS9960_REG_CONTROL)
# set bits in register to given value
drive &= 0b00000011
drive = drive << 6
val &= 0b00111111
val |= drive
self._write_byte_data(APDS9960_REG_CONTROL, val)
def getProximityGain(self):
"""Returns receiver gain for proximity detection.
Value Gain
0 1x
1 2x
2 4x
3 8x
Returns:
int: the value of the proximity gain
"""
val = self._read_byte_data(APDS9960_REG_CONTROL)
# shift and mask out PDRIVE bits
return (val >> 2) & 0b00000011
def setProximityGain(self, drive):
"""Returns receiver gain for proximity detection.
Value Gain
0 1x
1 2x
2 4x
3 8x
Args:
drive (int): value for the proximity gain
"""
val = self._read_byte_data(APDS9960_REG_CONTROL)
# set bits in register to given value
drive &= 0b00000011
drive = drive << 2
val &= 0b11110011
val |= drive
self._write_byte_data(APDS9960_REG_CONTROL, val)
def getAmbientLightGain(self):
"""Returns receiver gain for the ambient light sensor (ALS).
Value Gain
0 1x
1 4x
2 16x
3 64x
Returns:
int: the value of the ALS gain
"""
val = self._read_byte_data(APDS9960_REG_CONTROL)
# shift and mask out ADRIVE bits
return (val & 0b00000011)
def setAmbientLightGain(self, drive):
"""Sets the receiver gain for the ambient light sensor (ALS).
Value Gain
0 1x
1 4x
2 16x
3 64x
Args:
drive (int): value for the ALS gain
"""
val = self._read_byte_data(APDS9960_REG_CONTROL)
# set bits in register to given value
drive &= 0b00000011
val &= 0b11111100
val |= drive
self._write_byte_data(APDS9960_REG_CONTROL, val)
def getLEDBoost(self):
"""Get the current LED boost value.
Value Gain
0 100%
1 150%
2 200%
3 300%
Returns:
int: the LED boost value
"""
val = self._read_byte_data(APDS9960_REG_CONFIG2)
# shift and mask out LED_BOOST bits
return (val >> 4) & 0b00000011
def setLEDBoost(self, boost):
"""Sets the LED current boost value.
Value Gain
0 100%
1 150%
2 200%
3 300%
Args:
boost (int): value for the LED boost
"""
val = self._read_byte_data(APDS9960_REG_CONFIG2)
# set bits in register to given value
boost &= 0b00000011
boost = boost << 4
val &= 0b11001111
val |= boost
self._write_byte_data(APDS9960_REG_CONFIG2, val)
def getProxGainCompEnable(self):
"""Gets proximity gain compensation enable.
Returns:
bool: True if compensation is enabled, False if not
"""
val = self._read_byte_data(APDS9960_REG_CONFIG3)
# Shift and mask out PCMP bits
val = (val >> 5) & 0b00000001
return val == 1
def setProxGainCompEnable(self, enable):
"""Sets the proximity gain compensation enable.
Args:
enable (bool): True to enable compensation, False to disable
"""
val = self._read_byte_data(APDS9960_REG_CONFIG3)
# set bits in register to given value
val &= 0b11011111
if enable:
val |= 0b00100000
self._write_byte_data(APDS9960_REG_CONFIG3, val)
def getProxPhotoMask(self):
"""Gets the current mask for enabled/disabled proximity photodiodes.
Bit Photodiode
3 UP
2 DOWN
1 LEFT
0 RIGHT
1 = disabled, 0 = enabled
Returns:
int: Current proximity mask for photodiodes.
"""
val = self._read_byte_data(APDS9960_REG_CONFIG3)
# mask out photodiode enable mask bits
return val & 0b00001111
def setProxPhotoMask(self, mask):
"""Sets the mask for enabling/disabling proximity photodiodes.
Bit Photodiode
3 UP
2 DOWN
1 LEFT
0 RIGHT
1 = disabled, 0 = enabled
Args:
mask (int): 4-bit mask value
"""
val = self._read_byte_data(APDS9960_REG_CONFIG3)
# set bits in register to given value
mask &= 0b00001111
val &= 0b11110000
val |= mask
self._write_byte_data(APDS9960_REG_CONFIG3, val)
def getGestureEnterThresh(self):
"""Gets the entry proximity threshold for gesture sensing.
Returns:
int: current entry proximity threshold
"""
return self._read_byte_data(APDS9960_REG_GPENTH)
def setGestureEnterThresh(self, threshold):
"""Sets the entry proximity threshold for gesture sensing.
Args:
threshold (int): threshold proximity value needed to start gesture mode
"""
self._write_byte_data(APDS9960_REG_GPENTH, threshold)
def getGestureExitThresh(self):
"""Gets the exit proximity threshold for gesture sensing.
Returns:
int: current exit proximity threshold
"""
return self._read_byte_data(APDS9960_REG_GEXTH)
def setGestureExitThresh(self, threshold):
"""Sets the exit proximity threshold for gesture sensing.
Args:
threshold (int): threshold proximity value needed to end gesture mode
"""
self._write_byte_data(APDS9960_REG_GEXTH, threshold)
def getGestureGain(self):
"""Gets the gain of the photodiode during gesture mode.
Value Gain
0 1x
1 2x
2 4x
3 8x
Returns:
int: the current photodiode gain
"""
val = self._read_byte_data(APDS9960_REG_GCONF2)
# shift and mask out PDRIVE bits
return (val >> 5) & 0b00000011
def setGestureGain(self, gain):
"""Sets the gain of the photodiode during gesture mode.
Value Gain
0 1x
1 2x
2 4x
3 8x
Args:
gain (int): the value for the photodiode gain
"""
val = self._read_byte_data(APDS9960_REG_GCONF2)
# set bits in register to given value
gain &= 0b00000011
gain = gain << 5
val &= 0b10011111
val |= gain
self._write_byte_data(APDS9960_REG_GCONF2, val)
def getGestureLEDDrive(self):
"""Gets the drive current of the LED during gesture mode.
Value LED Current
0 100 mA
1 50 mA
2 25 mA
3 12.5 mA
Returns:
int: the LED drive current value
"""
val = self._read_byte_data(APDS9960_REG_GCONF2)
# shift and mask out LED drive bits
return (val >> 3) & 0b00000011
def setGestureLEDDrive(self, drive):
"""Sets LED drive strength for proximity and ALS.
Value LED Current
0 100 mA
1 50 mA
2 25 mA
3 12.5 mA
Args:
drive (int): value for the LED drive current
"""
val = self._read_byte_data(APDS9960_REG_GCONF2)
# set bits in register to given value
drive &= 0b00000011;
drive = drive << 3;
val &= 0b11100111;
val |= drive;
self._write_byte_data(APDS9960_REG_GCONF2, val)
def getGestureWaitTime(self):
"""Gets the time in low power mode between gesture detections.
Value Wait time
0 0 ms
1 2.8 ms
2 5.6 ms
3 8.4 ms
4 14.0 ms
5 22.4 ms
6 30.8 ms
7 39.2 ms
Returns:
int: the current wait time between gestures
"""
val = self._read_byte_data(APDS9960_REG_GCONF2)
# shift and mask out LED drive bits
return val & 0b00000111
def setGestureWaitTime(self, time):
"""Sets the time in low power mode between gesture detections.
Value Wait time
0 0 ms
1 2.8 ms
2 5.6 ms
3 8.4 ms
4 14.0 ms
5 22.4 ms
6 30.8 ms
7 39.2 ms
Args:
time (int): value for the wait time
"""
val = self._read_byte_data(APDS9960_REG_GCONF2)
# set bits in register to given value
time &= 0b00000111
val &= 0b11111000
val |= time
self._write_byte_data(APDS9960_REG_GCONF2, val)
def getLightIntLowThreshold(self):
"""Gets the low threshold for ambient light interrupts.
Returns:
int: threshold current low threshold stored on the APDS9960
"""
return self._read_byte_data(APDS9960_REG_AILTL) | (self._read_byte_data(APDS9960_REG_AILTH) << 8)
def setLightIntLowThreshold(self, threshold):
"""Sets the low threshold for ambient light interrupts.
Args:
threshold (int): low threshold value for interrupt to trigger
"""
# break 16-bit threshold into 2 8-bit values
self._write_byte_data(APDS9960_REG_AILTL, threshold & 0x00ff)
self._write_byte_data(APDS9960_REG_AILTH, (threshold & 0xff00) >> 8)
def getLightIntHighThreshold(self):
"""Gets the high threshold for ambient light interrupts.
Returns:
int: threshold current low threshold stored on the APDS9960
"""
return self._read_byte_data(APDS9960_REG_AIHTL) | (self._read_byte_data(APDS9960_REG_AIHTH) << 8)
def setLightIntHighThreshold(self, threshold):
"""Sets the high threshold for ambient light interrupts.
Args:
threshold (int): high threshold value for interrupt to trigger
"""
# break 16-bit threshold into 2 8-bit values
self._write_byte_data(APDS9960_REG_AIHTL, threshold & 0x00ff)
self._write_byte_data(APDS9960_REG_AIHTH, (threshold & 0xff00) >> 8)
def getProximityIntLowThreshold(self):
"""Gets the low threshold for proximity interrupts.
Returns:
int: threshold current low threshold stored on the APDS9960
"""
return self._read_byte_data(APDS9960_REG_PILT)
def setProximityIntLowThreshold(self, threshold):
"""Sets the low threshold for proximity interrupts.
Args:
threshold (int): low threshold value for interrupt to trigger
"""
self._write_byte_data(APDS9960_REG_PILT, threshold)
def getProximityIntHighThreshold(self):
"""Gets the high threshold for proximity interrupts.
Returns:
int: threshold current high threshold stored on the APDS9960
"""
return self._read_byte_data(APDS9960_REG_PIHT)
def setProximityIntHighThreshold(self, threshold):
"""Sets the high threshold for proximity interrupts.
Args:
threshold (int): high threshold value for interrupt to trigger
"""
self._write_byte_data(APDS9960_REG_PIHT, threshold)
def getAmbientLightIntEnable(self):
"""Gets if ambient light interrupts are enabled or not.
Returns:
bool: True if interrupts are enabled, False if not
"""
val = self._read_byte_data(APDS9960_REG_ENABLE)
return (val >> 4) & 0b00000001 == 1
def setAmbientLightIntEnable(self, enable):
"""Turns ambient light interrupts on or off.
Args:
enable (bool): True to enable interrupts, False to turn them off
"""
val = self._read_byte_data(APDS9960_REG_ENABLE)
# set bits in register to given value
val &= 0b11101111;
if enable:
val |= 0b00010000
self._write_byte_data(APDS9960_REG_ENABLE, val)
def getProximityIntEnable(self):
"""Gets if proximity interrupts are enabled or not.
Returns:
bool: True if interrupts are enabled, False if not
"""
val = self._read_byte_data(APDS9960_REG_ENABLE)
return (val >> 5) & 0b00000001 == 1
def setProximityIntEnable(self, enable):
"""Turns proximity interrupts on or off.
Args:
enable (bool): True to enable interrupts, False to turn them off
"""
val = self._read_byte_data(APDS9960_REG_ENABLE)
# set bits in register to given value
val &= 0b11011111;
if enable:
val |= 0b00100000
self._write_byte_data(APDS9960_REG_ENABLE, val)
def getGestureIntEnable(self):
"""Gets if gesture interrupts are enabled or not.
Returns:
bool: True if interrupts are enabled, False if not
"""
val = self._read_byte_data(APDS9960_REG_GCONF4)
return (val >> 1) & 0b00000001 == 1
def setGestureIntEnable(self, enable):
"""Turns gesture-related interrupts on or off.
Args:
enable (bool): True to enable interrupts, False to turn them off
"""
val = self._read_byte_data(APDS9960_REG_GCONF4)
# set bits in register to given value
val &= 0b11111101
if enable:
val |= 0b00000010
self._write_byte_data(APDS9960_REG_GCONF4, val)
def clearAmbientLightInt(self):
"""Clears the ambient light interrupt.
"""
self._read_byte_data(APDS9960_REG_AICLEAR)
def clearProximityInt(self):
"""Clears the proximity interrupt.
"""
self._read_byte_data(APDS9960_REG_PICLEAR)
# *******************************************************************************
# Raw I2C Reads and Writes
# *******************************************************************************
def _read_byte_data(self, cmd):
return self.bus.readfrom_mem(self.address, cmd, 1)[0]
def _write_byte_data(self, cmd, val):
self.bus.writeto_mem(self.address, cmd, bytes([val]))
def _read_i2c_block_data(self, cmd, num):
return self.bus.readfrom_mem(self.address, cmd, num)
# *******************************************************************************
# High-level gesture controls
# *******************************************************************************
# resets all the parameters in the gesture data member

+ 33
- 0
user_lib/apds9960_test_ambient.py View File

@@ -0,0 +1,33 @@
from time import sleep

from machine import Pin, I2C

D0 = 16
D1 = 5
D2 = 4
D3 = 0
D4 = 2
D5 = 14
D6 = 12
D7 = 13
D8 = 15



from apds9960 import APDS9960

bus = I2C(sda=Pin(D2), scl=Pin(D1))

apds = APDS9960(bus)

print("Light Sensor Test")
print("=================")
apds.enableLightSensor()

oval = -1
while True:
sleep(0.25)
val = apds.readAmbientLight()
if val != oval:
print("AmbientLight={}".format(val))
oval = val

+ 40
- 0
user_lib/apds9960_test_gesture.py View File

@@ -0,0 +1,40 @@
from time import sleep

from machine import Pin, I2C


from apds9960 import APDS9960
D0 = 16
D1 = 5
D2 = 4
D3 = 0
D4 = 2
D5 = 14
D6 = 12
D7 = 13
D8 = 15
bus = I2C(sda=Pin(D2), scl=Pin(D1))

apds = APDS9960(bus)

dirs = {
APDS9960_DIR_NONE: "none",
APDS9960_DIR_LEFT: "left",
APDS9960_DIR_RIGHT: "right",
APDS9960_DIR_UP: "up",
APDS9960_DIR_DOWN: "down",
APDS9960_DIR_NEAR: "near",
APDS9960_DIR_FAR: "far",
}

apds.setProximityIntLowThreshold(50)

print("Gesture Test")
print("============")
apds.enableGestureSensor()

while True:
sleep(0.5)
if apds.isGestureAvailable():
motion = apds.readGesture()
print("Gesture={}".format(dirs.get(motion, "unknown")))

+ 32
- 0
user_lib/apds9960_test_prox.py View File

@@ -0,0 +1,32 @@
from time import sleep

from machine import Pin, I2C
D0 = 16
D1 = 5
D2 = 4
D3 = 0
D4 = 2
D5 = 14
D6 = 12
D7 = 13
D8 = 15

from apds9960_prox import APDS9960

bus = I2C(sda=Pin(D2), scl=Pin(D1))

apds = APDS9960(bus)

apds.setProximityIntLowThreshold(50)

print("Proximity Sensor Test")
print("=====================")
apds.enableProximitySensor()

oval = -1
while True:
sleep(0.25)
val = apds.readProximity()
if val != oval:
print("proximity={}".format(val))
oval = val

+ 216
- 0
user_lib/bme280.py View File

@@ -0,0 +1,216 @@
# Authors: Paul Cunnane 2016, Peter Dahlebrg 2016
#
# This module borrows from the Adafruit BME280 Python library. Original
# Copyright notices are reproduced below.
#
# Those libraries were written for the Raspberry Pi. This modification is
# intended for the MicroPython and esp8266 boards.
#
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
#
# Based on the BMP280 driver with BME280 changes provided by
# David J Taylor, Edinburgh (www.satsignal.eu)
#
# Based on Adafruit_I2C.py created by Kevin Townsend.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import time
from ustruct import unpack, unpack_from
from array import array
# BME280 default address.
BME280_I2CADDR = 0x76
# Operating Modes
BME280_OSAMPLE_1 = 1
BME280_OSAMPLE_2 = 2
BME280_OSAMPLE_4 = 3
BME280_OSAMPLE_8 = 4
BME280_OSAMPLE_16 = 5
BME280_REGISTER_CONTROL_HUM = 0xF2
BME280_REGISTER_CONTROL = 0xF4
class BME280:
def __init__(self,
mode=BME280_OSAMPLE_1,
address=BME280_I2CADDR,
i2c=None,
**kwargs):
# Check that mode is valid.
if mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
raise ValueError(
'Unexpected mode value {0}. Set mode to one of '
'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or '
'BME280_ULTRAHIGHRES'.format(mode))
self._mode = mode
self.address = address
if i2c is None:
raise ValueError('An I2C object is required.')
self.i2c = i2c
# load calibration data
dig_88_a1 = self.i2c.readfrom_mem(self.address, 0x88, 26)
dig_e1_e7 = self.i2c.readfrom_mem(self.address, 0xE1, 7)
self.dig_T1, self.dig_T2, self.dig_T3, self.dig_P1, \
self.dig_P2, self.dig_P3, self.dig_P4, self.dig_P5, \
self.dig_P6, self.dig_P7, self.dig_P8, self.dig_P9, \
_, self.dig_H1 = unpack("<HhhHhhhhhhhhBB", dig_88_a1)
self.dig_H2, self.dig_H3 = unpack("<hB", dig_e1_e7)
e4_sign = unpack_from("<b", dig_e1_e7, 3)[0]
self.dig_H4 = (e4_sign << 4) | (dig_e1_e7[4] & 0xF)
e6_sign = unpack_from("<b", dig_e1_e7, 5)[0]
self.dig_H5 = (e6_sign << 4) | (dig_e1_e7[4] >> 4)
self.dig_H6 = unpack_from("<b", dig_e1_e7, 6)[0]
self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
bytearray([0x3F]))
self.t_fine = 0
# temporary data holders which stay allocated
self._l1_barray = bytearray(1)
self._l8_barray = bytearray(8)
self._l3_resultarray = array("i", [0, 0, 0])
def read_raw_data(self, result):
""" Reads the raw (uncompensated) data from the sensor.
Args:
result: array of length 3 or alike where the result will be
stored, in temperature, pressure, humidity order
Returns:
None
"""
self._l1_barray[0] = self._mode
self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL_HUM,
self._l1_barray)
self._l1_barray[0] = self._mode << 5 | self._mode << 2 | 1
self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
self._l1_barray)
sleep_time = 1250 + 2300 * (1 << self._mode)
sleep_time = sleep_time + 2300 * (1 << self._mode) + 575
sleep_time = sleep_time + 2300 * (1 << self._mode) + 575
time.sleep_us(sleep_time) # Wait the required time
# burst readout from 0xF7 to 0xFE, recommended by datasheet
self.i2c.readfrom_mem_into(self.address, 0xF7, self._l8_barray)
readout = self._l8_barray
# pressure(0xF7): ((msb << 16) | (lsb << 8) | xlsb) >> 4
raw_press = ((readout[0] << 16) | (readout[1] << 8) | readout[2]) >> 4
# temperature(0xFA): ((msb << 16) | (lsb << 8) | xlsb) >> 4
raw_temp = ((readout[3] << 16) | (readout[4] << 8) | readout[5]) >> 4
# humidity(0xFD): (msb << 8) | lsb
raw_hum = (readout[6] << 8) | readout[7]
result[0] = raw_temp
result[1] = raw_press
result[2] = raw_hum
def read_compensated_data(self, result=None):
""" Reads the data from the sensor and returns the compensated data.
Args:
result: array of length 3 or alike where the result will be
stored, in temperature, pressure, humidity order. You may use
this to read out the sensor without allocating heap memory
Returns:
array with temperature, pressure, humidity. Will be the one from
the result parameter if not None
"""
self.read_raw_data(self._l3_resultarray)
raw_temp, raw_press, raw_hum = self._l3_resultarray
# temperature
var1 = ((raw_temp >> 3) - (self.dig_T1 << 1)) * (self.dig_T2 >> 11)
var2 = (((((raw_temp >> 4) - self.dig_T1) *
((raw_temp >> 4) - self.dig_T1)) >> 12) * self.dig_T3) >> 14
self.t_fine = var1 + var2
temp = (self.t_fine * 5 + 128) >> 8
# pressure
var1 = self.t_fine - 128000
var2 = var1 * var1 * self.dig_P6
var2 = var2 + ((var1 * self.dig_P5) << 17)
var2 = var2 + (self.dig_P4 << 35)
var1 = (((var1 * var1 * self.dig_P3) >> 8) +
((var1 * self.dig_P2) << 12))
var1 = (((1 << 47) + var1) * self.dig_P1) >> 33
if var1 == 0:
pressure = 0
else:
p = 1048576 - raw_press
p = (((p << 31) - var2) * 3125) // var1
var1 = (self.dig_P9 * (p >> 13) * (p >> 13)) >> 25
var2 = (self.dig_P8 * p) >> 19
pressure = ((p + var1 + var2) >> 8) + (self.dig_P7 << 4)
# humidity
h = self.t_fine - 76800
h = (((((raw_hum << 14) - (self.dig_H4 << 20) -
(self.dig_H5 * h)) + 16384)
>> 15) * (((((((h * self.dig_H6) >> 10) *
(((h * self.dig_H3) >> 11) + 32768)) >> 10) +
2097152) * self.dig_H2 + 8192) >> 14))
h = h - (((((h >> 15) * (h >> 15)) >> 7) * self.dig_H1) >> 4)
h = 0 if h < 0 else h
h = 419430400 if h > 419430400 else h
humidity = h >> 12
if result:
result[0] = temp
result[1] = pressure
result[2] = humidity
return result
return array("i", (temp, pressure, humidity))
@property
def values(self):
""" human readable values """
t, p, h = self.read_compensated_data()
p = p // 256
pi = p // 100
pd = p - pi * 100
hi = h // 1024
hd = h * 100 // 1024 - hi * 100
return ("{}C".format(t / 100), "{}.{:02d}hPa".format(pi, pd),
"{}.{:02d}%".format(hi, hd))
@property
def values2(self):
""" human readable values without string """
t, p, h = self.read_compensated_data()
p = p // 256
pi = p // 100
pd = p - pi * 100
hi = h // 1024
hd = h * 100 // 1024 - hi * 100
return (t/100,pi+pd/100,hi+hd/100)

+ 338
- 0
user_lib/vl53l0x.py View File

@@ -0,0 +1,338 @@
from micropython import const
import ustruct
import utime
_IO_TIMEOUT = 1000
_SYSRANGE_START = const(0x00)
_EXTSUP_HV = const(0x89)
_MSRC_CONFIG = const(0x60)
_FINAL_RATE_RTN_LIMIT = const(0x44)
_SYSTEM_SEQUENCE = const(0x01)
_SPAD_REF_START = const(0x4f)
_SPAD_ENABLES = const(0xb0)
_REF_EN_START_SELECT = const(0xb6)
_SPAD_NUM_REQUESTED = const(0x4e)
_INTERRUPT_GPIO = const(0x0a)
_INTERRUPT_CLEAR = const(0x0b)
_GPIO_MUX_ACTIVE_HIGH = const(0x84)
_RESULT_INTERRUPT_STATUS = const(0x13)
_RESULT_RANGE_STATUS = const(0x14)
_OSC_CALIBRATE = const(0xf8)
_MEASURE_PERIOD = const(0x04)
class TimeoutError(RuntimeError):
pass
class VL53L0X:
def __init__(self, i2c, address=0x29):
self.i2c = i2c
self.address = address
self.init()
self._started = False
def _registers(self, register, values=None, struct='B'):
if values is None:
size = ustruct.calcsize(struct)
data = self.i2c.readfrom_mem(self.address, register, size)
values = ustruct.unpack(struct, data)
return values
data = ustruct.pack(struct, *values)
self.i2c.writeto_mem(self.address, register, data)
def _register(self, register, value=None, struct='B'):
if value is None:
return self._registers(register, struct=struct)[0]
self._registers(register, (value,), struct=struct)
def _flag(self, register=0x00, bit=0, value=None):
data = self._register(register)
mask = 1 << bit
if value is None:
return bool(data & mask)
elif value:
data |= mask
else:
data &= ~mask
self._register(register, data)
def _config(self, *config):
for register, value in config:
self._register(register, value)
def init(self, power2v8=True):
self._flag(_EXTSUP_HV, 0, power2v8)
# I2C standard mode
self._config(
(0x88, 0x00),
(0x80, 0x01),
(0xff, 0x01),
(0x00, 0x00),
)
self._stop_variable = self._register(0x91)
self._config(
(0x00, 0x01),
(0xff, 0x00),
(0x80, 0x00),
)
# disable signal_rate_msrc and signal_rate_pre_range limit checks
self._flag(_MSRC_CONFIG, 1, True)
self._flag(_MSRC_CONFIG, 4, True)
# rate_limit = 0.25
self._register(_FINAL_RATE_RTN_LIMIT, int(0.25 * (1 << 7)),
struct='>H')
self._register(_SYSTEM_SEQUENCE, 0xff)
spad_count, is_aperture = self._spad_info()
spad_map = bytearray(self._registers(_SPAD_ENABLES, struct='6B'))
# set reference spads
self._config(
(0xff, 0x01),
(_SPAD_REF_START, 0x00),
(_SPAD_NUM_REQUESTED, 0x2c),
(0xff, 0x00),
(_REF_EN_START_SELECT, 0xb4),
)
spads_enabled = 0
for i in range(48):
if i < 12 and is_aperture or spads_enabled >= spad_count:
spad_map[i // 8] &= ~(1 << (i >> 2))
elif spad_map[i // 8] & (1 << (i >> 2)):
spads_enabled += 1
self._registers(_SPAD_ENABLES, spad_map, struct='6B')
self._config(
(0xff, 0x01),
(0x00, 0x00),
(0xff, 0x00),
(0x09, 0x00),
(0x10, 0x00),
(0x11, 0x00),
(0x24, 0x01),
(0x25, 0xFF),
(0x75, 0x00),
(0xFF, 0x01),
(0x4E, 0x2C),
(0x48, 0x00),
(0x30, 0x20),
(0xFF, 0x00),
(0x30, 0x09),
(0x54, 0x00),
(0x31, 0x04),
(0x32, 0x03),
(0x40, 0x83),
(0x46, 0x25),
(0x60, 0x00),
(0x27, 0x00),
(0x50, 0x06),
(0x51, 0x00),
(0x52, 0x96),
(0x56, 0x08),
(0x57, 0x30),
(0x61, 0x00),
(0x62, 0x00),
(0x64, 0x00),
(0x65, 0x00),
(0x66, 0xA0),
(0xFF, 0x01),
(0x22, 0x32),
(0x47, 0x14),
(0x49, 0xFF),
(0x4A, 0x00),
(0xFF, 0x00),
(0x7A, 0x0A),
(0x7B, 0x00),
(0x78, 0x21),
(0xFF, 0x01),
(0x23, 0x34),
(0x42, 0x00),
(0x44, 0xFF),
(0x45, 0x26),
(0x46, 0x05),
(0x40, 0x40),
(0x0E, 0x06),
(0x20, 0x1A),
(0x43, 0x40),
(0xFF, 0x00),
(0x34, 0x03),
(0x35, 0x44),
(0xFF, 0x01),
(0x31, 0x04),
(0x4B, 0x09),
(0x4C, 0x05),
(0x4D, 0x04),
(0xFF, 0x00),
(0x44, 0x00),
(0x45, 0x20),
(0x47, 0x08),
(0x48, 0x28),
(0x67, 0x00),
(0x70, 0x04),
(0x71, 0x01),
(0x72, 0xFE),
(0x76, 0x00),
(0x77, 0x00),
(0xFF, 0x01),
(0x0D, 0x01),
(0xFF, 0x00),
(0x80, 0x01),
(0x01, 0xF8),
(0xFF, 0x01),
(0x8E, 0x01),
(0x00, 0x01),
(0xFF, 0x00),
(0x80, 0x00),
)
self._register(_INTERRUPT_GPIO, 0x04)
self._flag(_GPIO_MUX_ACTIVE_HIGH, 4, False)
self._register(_INTERRUPT_CLEAR, 0x01)
# XXX Need to implement this.
#budget = self._timing_budget()
#self._register(_SYSTEM_SEQUENCE, 0xe8)
#self._timing_budget(budget)
self._register(_SYSTEM_SEQUENCE, 0x01)
self._calibrate(0x40)
self._register(_SYSTEM_SEQUENCE, 0x02)
self._calibrate(0x00)
self._register(_SYSTEM_SEQUENCE, 0xe8)
def _spad_info(self):
self._config(
(0x80, 0x01),
(0xff, 0x01),
(0x00, 0x00),
(0xff, 0x06),
)
self._flag(0x83, 3, True)
self._config(
(0xff, 0x07),
(0x81, 0x01),
(0x80, 0x01),
(0x94, 0x6b),
(0x83, 0x00),
)
for timeout in range(_IO_TIMEOUT):
if self._register(0x83):
break
utime.sleep_ms(1)
else:
raise TimeoutError()
self._config(
(0x83, 0x01),
)
value = self._register(0x92)
self._config(
(0x81, 0x00),
(0xff, 0x06),
)
self._flag(0x83, 3, False)
self._config(
(0xff, 0x01),
(0x00, 0x01),
(0xff, 0x00),
(0x80, 0x00),
)
count = value & 0x7f
is_aperture = bool(value & 0b10000000)
return count, is_aperture
def _calibrate(self, vhv_init_byte):
self._register(_SYSRANGE_START, 0x01 | vhv_init_byte)
for timeout in range(_IO_TIMEOUT):
if self._register(_RESULT_INTERRUPT_STATUS) & 0x07:
break
utime.sleep_ms(1)
else:
raise TimeoutError()
self._register(_INTERRUPT_CLEAR, 0x01)
self._register(_SYSRANGE_START, 0x00)
def start(self, period=0):
self._config(
(0x80, 0x01),
(0xFF, 0x01),
(0x00, 0x00),
(0x91, self._stop_variable),
(0x00, 0x01),
(0xFF, 0x00),
(0x80, 0x00),
)
if period:
oscilator = self._register(_OSC_CALIBRATE, struct='>H')
if oscilator:
period *= oscilator
self._register(_MEASURE_PERIOD, period, struct='>H')
self._register(_SYSRANGE_START, 0x04)
else:
self._register(_SYSRANGE_START, 0x02)
self._started = True
def stop(self):
self._register(_SYSRANGE_START, 0x01)
self._config(
(0xFF, 0x01),
(0x00, 0x00),
(0x91, self._stop_variable),
(0x00, 0x01),
(0xFF, 0x00),
)
self._started = False
def read(self):
if not self._started:
self._config(
(0x80, 0x01),
(0xFF, 0x01),
(0x00, 0x00),
(0x91, self._stop_variable),
(0x00, 0x01),
(0xFF, 0x00),
(0x80, 0x00),
(_SYSRANGE_START, 0x01),
)
for timeout in range(_IO_TIMEOUT):
if not self._register(_SYSRANGE_START) & 0x01:
break
utime.sleep_ms(1)
else:
raise TimeoutError()
for timeout in range(_IO_TIMEOUT):
if self._register(_RESULT_INTERRUPT_STATUS) & 0x07:
break
utime.sleep_ms(1)
else:
raise TimeoutError()
value = self._register(_RESULT_RANGE_STATUS + 10, struct='>H')
self._register(_INTERRUPT_CLEAR, 0x01)
return value

Loading…
Cancel
Save