Main issue is that I want to observe a trend, not react to very brief and sporadic changes, to avoid triggering false alarms.
In a bigger computer I would use arrays, append constantly values and statistically monitor the trend. But arrays are not available on micropython. So I initially swapped array for a list - but it looks that it also kills the hardware causing memory leaks in longer periods.
My iniital code is simple, utilising asyncio, these are parts from my larger code of course. One coro is observing the sensor, another one reacts and turns power on and off. But I have an impression it's silly inefficient and complex.
I want to ask you for advice how to properly code it, please!
Code: Select all
async def move_update():
global MOVE, TEMPC
imu = MPU9250('Y')
if 'MOVE' not in globals():
MOVE = []
# TODO: swap from list to array when micropython is ready
# MOVE = array.array('b')
# simulate initial constant movement for ~ 1 minute to warm up the device
if len(MOVE) < 200:
for i in range(200):
await asyncio.sleep(0)
MOVE.append(1.0)
imu.gyro_filter_range = 5
while True:
#print("MV: {}".format(MOVE_PIN.value()))
#submit = MOVE_PIN.value()
# we need to be sure value is fixed
#if submit == 0 or submit == 1:
# MOVE.append(submit)
#print("MV: {}".format(sum(MOVE) / len(MOVE)))
# Append fake movement
#MOVE.append(2.0)
#
TEMPC = imu.temperature
#print(TEMPC)
gyro = imu.gyro.xyz
#print(gyro[0])
if gyro[0] > 2 or gyro[0] < -2 or gyro[1] > 2 or gyro[1] < -2 or gyro[2] > 2 or gyro[2] < -2:
MOVE.append(1.0)
else:
MOVE.append(0.0)
await asyncio.sleep(0.2)
# keep array limited to ~ last few minutes
while len(MOVE) > 201:
MOVE.pop(0)
async def power_control():
while True:
# is someone moving us? if yes, we need to be on
#MOVE = []
if len(MOVE) > 0:
move = sum(MOVE) / len(MOVE)
else:
move = "5.0"
#
# We switch off the power if sensors are not detecting anything around
if move == 0.0:
GPStranzi.off()
GSMtranzi.off()
OLEDtranzi.off()
#print("Switch OFF the lights!")
else:
GPStranzi.on()
GSMtranzi.on()
OLEDtranzi.on()
#print("Switch ON the lights!")
await asyncio.sleep(10)
move_coro = asyncio.create_task(move_update())
power_coro = asyncio.create_task(power_control())