import network, _thread
import time, utime
import socket
from machine import Pin, time_pulse_us, I2C
import gc, dht, ssd1306
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect("Wokwi-GUEST", "")
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print(sta_if.ifconfig())
ip = sta_if.ifconfig()[0]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 80))
s.listen(5)
DIST_ON_CM = 100
TEMP_LIM = 45
MELODY1 = [2425, 2425] #[250, 250] #[2425, 2425]
MELODY2 = [2480, 2480] #[200, 200] #[2480, 2480]
TIME_ON = 15
buzzer = machine.PWM(machine.Pin(17))
gc.collect()
html = None
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
SOUND_SPEED=340 # sound speed in the air
TRIG_PULSE_DURATION_US=10
trig_pin = Pin(19, Pin.OUT)
echo_pin = Pin(18, Pin.IN)
i2c=I2C(0, scl=Pin(21), sda=Pin(20))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.fill(0)
oled.show()
dhts=dht.DHT11(Pin((22))) #;dhts.measure();time.sleep(2)
lock = _thread.allocate_lock()
iot_on = False
iot_off = False
rep_dist = 0
def tone(pin,frequency,duration):
pin.freq(frequency)
pin.duty_u16(30000)
utime.sleep_ms(duration)
pin.duty_u16(0)
def gpio_set(pin,value):
if value >= 1:
Pin(pin, Pin.OUT).on()
else:
Pin(pin, Pin.OUT).off()
def us_cm():
trig_pin.value(0)
time.sleep_us(5)
# 10 µs impulse
trig_pin.value(1)
time.sleep_us(TRIG_PULSE_DURATION_US)
trig_pin.value(0)
ultrason_duration = time_pulse_us(echo_pin, 1, 30000) # Returns the propagation time of the wave. (µs)
distance_cm = SOUND_SPEED * ultrason_duration / 20000
return distance_cm
def rst_oled():
oled.fill(0)
oled.show()
title = "Home Info"
oled.text(title, center_txt(title), 2)
oled.show()
def temp_hum():
global iot_on
global iot_off
global rep_dist
while True:
if iot_on:
gpio_set((16), True)
oled.fill_rect(0, 43, 127, 20, 0)
oled.text("Lights ON", center_txt("Lights ON"), 43)
oled.text("remotely", center_txt("remotely"), 53)
oled.show()
for note in MELODY1:
tone(buzzer,note,250)
utime.sleep_ms(100)
print('ON Requested')
for sec in range(TIME_ON):
if iot_off: break
time.sleep_ms(900)
gpio_set((16), False)
oled.fill_rect(0, 43, 127, 20, 0)
oled.show()
iot_on = False
rep_dist = 0
if iot_off:
gpio_set((16), False)
oled.fill_rect(0, 43, 127, 20, 0)
oled.text("Lights OFF", center_txt("Lights OFF"), 43)
oled.text("remotely", center_txt("remotely"), 53)
oled.show()
print('OFF Requested')
time.sleep(1)
oled.fill_rect(0, 43, 127, 20, 0)
oled.show()
iot_off = False
rep_dist = 0
try:
dhts.measure()
temp_c = dhts.temperature()
hum = dhts.humidity()
#print(''.join([str(x) for x in ['Temp C: ', temp_c, ' / ', 'Humidity %: ', hum, ' / ', 'Distance Cm: ', dist_cm]]))
oled.fill_rect(0, 23, 127, 8, 0) #display.fill_rect(10, 10, 107, 43, 1) # draw a solid rectangle 0,24 to 7,0, colour=0
info = str(temp_c)+ " C / " + str(hum) + "%"
xtx = center_txt(info)
oled.text(info, xtx, 23)
deg(xtx+2*8+4, 23)
oled.show()
time.sleep_ms(600)
if temp_c > TEMP_LIM:
while True:
for note in MELODY2:
tone(buzzer,note,250)
utime.sleep_ms(400)
#lock.release()
except:
oled.fill_rect(0, 23, 127, 8, 0) #display.fill_rect(10, 10, 107, 43, 1) # draw a solid rectangle 0,24 to 7,0, colour=0
info = "__"+ " C / " + "__" + "%"
xtx = center_txt(info)
oled.text(info, xtx, 23)
deg(xtx+2*8+4, 23)
oled.show()
pass
try:
dist_cm = us_cm()
if dist_cm <= DIST_ON_CM and dist_cm > 2:
rep_dist += 1
gpio_set((16), True)
print("Activation cm:", dist_cm)
oled.fill_rect(0, 43, 127, 20, 0)
inf = "ON at " + "{:.0f}".format(dist_cm) + "cm"
oled.text(inf, center_txt(inf), 43)
oled.show()
if rep_dist == 1:
for note in MELODY1:
tone(buzzer,note,250)
utime.sleep_ms(100)
time.sleep_ms(900)
oled.fill_rect(0, 43, 127, 20, 0)
oled.show()
else:
gpio_set((16), False)
rep_dist = 0
time.sleep_ms(300)
except:
oled.fill_rect(0, 43, 127, 20, 0)
inf = "USsensor ERR"
oled.text(inf, center_txt(inf), 43)
oled.show()
pass
def center_txt(txt):
x = (oled_width - len(txt) * 8) // 2
return x
def deg(xx,yy): # Draw Degree symbol
oled.pixel(xx,yy+1,1)
oled.pixel(xx,yy,1)
oled.pixel(xx+1,yy,1)
oled.pixel(xx+1,yy+1,1)
rst_oled()
oled.text("IP Web Server", center_txt("IP Web Server"), 43)
oled.text(ip, center_txt(ip), 53)
oled.show()
time.sleep(3)
oled.fill_rect(0, 43, 127, 20, 0)
oled.show()
_thread.start_new_thread(temp_hum, ())
while True:
try:
#lock.acquire()
if gc.mem_free() < 102000:
gc.collect()
cl, addr = s.accept()
cl.settimeout(3.0)
#print('Got a connection from %s' % str(addr))
request = cl.recv(1024)
cl.settimeout(None)
request = str(request)
#print('Content = %s' % request)
lights_on = request.find('/?lights=on')
lights_off = request.find('/?lights=off')
if lights_on == 6:
iot_on = True
if lights_off == 6:
#gpio_set((16), False)
iot_off = True
html = """<html><head><meta content="width=device-width, initial-scale=1" name="viewport"><style>*, *:before, *:after {box-sizing: border-box;}body {font-family: -apple-system, ".SFNSText-Regular", "Helvetica Neue", "Roboto", "Segoe UI", sans-serif;max-width: 600px;padding-bottom: 25px;text-align: center;margin: 0px auto;padding-top: 30px;}.toggle {cursor: pointer;display: inline-block;}.toggle-switch {display: inline-block;background: #ccc;border-radius: 16px;width: 58px;height: 32px;position: relative;vertical-align: middle;transition: background 0.25s;}.toggle-switch:before, .toggle-switch:after {content: "";}.toggle-switch:before {display: block;background: linear-gradient(to bottom, #fff 0%, #eee 100%);border-radius: 50%;box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.25);width: 24px;height: 24px;position: absolute;top: 4px;left: 4px;transition: left 0.25s;}.toggle:hover .toggle-switch:before {background: linear-gradient(to bottom, #fff 0%, #fff 100%);box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.5);}.toggle-checkbox:checked + .toggle-switch {background: #56c080;}.toggle-checkbox:checked + .toggle-switch:before {left: 30px;}.toggle-checkbox {position: absolute;visibility: hidden;}.toggle-label {margin-left: 5px;position: relative;top: 2px;font-size: x-large;font-weight: bold;display: inline-block;width: 200px;text-align: left;}</style><script>function toggleCheckbox(element) {var xhr = new XMLHttpRequest();if (element.id == "light") {if (element.checked) {xhr.open("GET", "/?lights=on", true);} else {xhr.open("GET", "/?lights=off", true);}xhr.send();}}</script></head><body><h1>IoT through RPi Pico</h1><label class="toggle"><span class="toggle-label">Turn ON/OFF</span><input class="toggle-checkbox" id="light" onchange="toggleCheckbox(this)" type="checkbox"><div class="toggle-switch"></div></label><hr></body></html>"""
response = html
cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
cl.sendall(response)
cl.close()
#lock.release()
except OSError as e:
print(f'IoT Error: {e}')
cl.close()
pass