Files
DoorMicro/main.py
T

76 lines
1.6 KiB
Python

import time
import network
import urequests
from machine import Pin, time_pulse_us
DOOR_OPEN_THRESHOLD = 50 # in cm
echo_pin = Pin(0, Pin.IN)
trig_pin = Pin(1, Pin.OUT)
def getDistanceCM():
trig_pin.value(0)
time.sleep_us(2)
trig_pin.value(1)
time.sleep_us(10)
trig_pin.value(0)
pulse_time = time_pulse_us(echo_pin, 1, 30000)
if pulse_time < 0:
return -1
distance = pulse_time / 58
return distance
def sendDoorStatus(status):
print("door status: " + str(status))
#requestURL = "http://10.69.70.1/status"
#r = urequests.post(requestURL, data={"status", status})
def checkDoorDistance():
dist = -1
timeoutTime = 10
while timeoutTime > 0 and dist == -1:
dist = getDistanceCM()
timeoutTime -= 1
time.sleep(1)
if dist < DOOR_OPEN_THRESHOLD:
sendDoorStatus(1) # door open
elif dist == -1:
sendDoorStatus(-1) # unknown
else:
sendDoorStatus(0) # door closed
def connectToNet():
ssid = "ITRnet"
password = "pink4bubble"
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
MAX_WIFI_CONNECT_WAIT = 30
while MAX_WIFI_CONNECT_WAIT > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
MAX_WIFI_CONNECT_WAIT -= 1
print('waiting to connect...')
time.sleep(1)
if wlan.status() != 3:
raise RuntimeError('network connection failed')
else:
print('connected!')
status = wlan.ifconfig()
print('ip = ' + status[0])
# program
connectToNet()
while True:
time.sleep(5)
checkDoorDistance()