from machine import Pin, I2C
import ssd1306
from time import sleep
import dht
import json
# ESP32 Pin assignment
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
#Get Temperature & humidity treshold from sfconfig.json
def get_threshold():
with open ('sfconfig.json') as f:
sfconfig = json.load(f)
f.close
return sfconfig
#sensor reading function, return temperature and humidity value
def readsensor():
sensor = dht.DHT22(Pin(14))
sleep(3)
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
return temp,hum
#function to send information to oled display
def showoled(status,msg):
if status =='init' and msg =='':
oled.fill(0)
oled.text('T :', 0,5)
oled.text('Fan :', 65,5)
oled.text('H :',0, 20)
oled.text('Ex :',65,20)
if status == 'temp':
oled.text(str(msg), 25,5)
elif status == 'hum':
oled.text(str(msg),25,20)
elif status == 'fan':
oled.text(str(msg),100,5)
elif status == 'exhaust':
oled.text(str(msg),100,20)
oled.show()
#function to turning on/off the relay
#two relay introduce to the system : fan relay and exhaust relay
def relaycontrol(rel, command):
fan_relay = Pin(26, Pin.OUT)
exhaust_relay = Pin(27, Pin.OUT)
if rel == 'fan' and command == 'on':
fan_relay.value(1)
elif rel == 'fan' and command =='off':
fan_relay.value(0)
elif rel == 'exhaust' and command == 'on':
exhaust_relay.value(1)
elif rel == 'exhaust' and command =='off':
exhaust_relay.value(0)
while True:
config = get_threshold()
print(config)
sleep(5)
'''
showoled('init','')
print(get_threshold()['temp_th'])
temperature, humidity = readsensor()
showoled('temp',temperature)
showoled('hum',humidity)
print (temperature,humidity)
if temperature > get_threshold()['temp_th']:
relaycontrol('fan','on')
showoled('fan','On')
#sleep(5)
else :
relaycontrol('fan', 'off')
showoled('fan','Off')
#sleep(5)
if humidity > get_threshold()['hum_th'] :
relaycontrol('exhaust','on')
showoled('exhaust', 'On')
#sleep(5)
else :
relaycontrol('exhaust','off')
showoled('exhaust','Off')
#sleep(5)
sleep(5)
'''