76 lines
1.9 KiB
Python
76 lines
1.9 KiB
Python
import utime
|
|
import gc
|
|
from delayedswitch import DelayedSwitch
|
|
from ntptime import settime
|
|
from config import DELAY
|
|
from machine import ADC
|
|
|
|
import machine
|
|
|
|
from machine import Pin
|
|
# Wemos D1 pin14 = D5
|
|
d5 = Pin(14, machine.Pin.IN, machine.Pin.PULL_UP)
|
|
|
|
# voltage meter ZMPT101B is attached to pin A0
|
|
ad0 = ADC(0)
|
|
|
|
def read_voltage():
|
|
nsamples = 50
|
|
total = 0
|
|
sq_total = 0
|
|
for _ in range(nsamples):
|
|
v = ad0.read()
|
|
total += v
|
|
sq_total += v * v
|
|
utime.sleep_ms(2)
|
|
mean = total / nsamples
|
|
return (sq_total / nsamples - mean * mean) ** 0.5
|
|
|
|
# check if voltage is over a threshold
|
|
# read_voltage returns between 2-3 when there is no AC input
|
|
# read_voltage returns between 123-127 when there is AC input
|
|
# it seems 100 is a reasonable threshold
|
|
def high_voltage():
|
|
v = read_voltage()
|
|
hv = v > 100
|
|
# if hv:
|
|
# print("High voltage: ", v)
|
|
return hv
|
|
|
|
# setup rtc
|
|
settime()
|
|
rtc = machine.RTC()
|
|
utime.sleep_ms(750)
|
|
print('\nRTC Set from NTP to UTC:', rtc.datetime())
|
|
|
|
def pir_thread(switch):
|
|
pir_on = False
|
|
while True: # change this!
|
|
utime.sleep_ms(20)
|
|
if high_voltage():
|
|
# was PIR on in previous cycle?
|
|
if not pir_on:
|
|
# print some debug info
|
|
if not switch.is_light_on():
|
|
d = "%d %d %d %d, %02d:%02d:%02d" % rtc.datetime()[0:7]
|
|
print("Presence detected at: %s." % d)
|
|
|
|
switch.presence()
|
|
pir_on = True
|
|
else:
|
|
if pir_on:
|
|
d = "%d %d %d %d, %02d:%02d:%02d" % rtc.datetime()[0:7]
|
|
print("Absense detected at: %s." % d)
|
|
switch.absence()
|
|
pir_on = False
|
|
|
|
gc.collect()
|
|
|
|
|
|
print("Starting pir thread")
|
|
switch = DelayedSwitch(DELAY,rtc) # delay in ms
|
|
pir_thread(switch)
|
|
|
|
# Not reached
|
|
print("Done")
|