from machine import Pin, I2C,ADC,Timer
import ssd1306
import urequests
import framebuf
import time
import dht
import network
import ujson
from umqtt.simple import MQTTClient
# ESP32 Pin assignment
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_TOPIC = "wather_station1"
p=0
state=False
timer=Timer(0)
class lcd_display():
def __init__(self,olded):
self.oled=olded
def show_LOGO(self):
oled.fill(0)
oled.text("BIDAVATOR",25,25)
oled.show()
def menu_left(self):
oled.fill(0)
oled.text("TEMP/HUM",25,25)
oled.show()
def menu_right(self):
oled.fill(0)
oled.text("WEATHER",25,25)
oled.show()
def show_sensor(self,temp,hum):
oled.fill(0)
oled.text("Temp:",25,25)
oled.text("HUM",25,40)
oled.text(str(temp),60,25)
oled.text(str(hum),60,40)
oled.show()
def left_handler(pin):
global p
p=0
def right_handler(pin):
global p
p=1
def select_hanlder(pin):
global state
state= not state
def initialize_network():
print("connecting WIFI")
net=network.WLAN(network.STA_IF)
net.active(True)
net.connect('Wokwi-GUEST', '')
while not net.isconnected():
print(".",end="")
time.sleep(0.1)
print("Connected")
def publish_data(t):
d.measure()
message={"temp":d.temperature(),
"hum":d.humidity()}
message_parse=ujson.dumps(message)
print(message_parse)
client.publish(MQTT_TOPIC,message_parse)
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
initialize_network()
print("Connecting to MQTT Broker..")
client=MQTTClient(MQTT_CLIENT_ID,MQTT_BROKER,user=None,password=None,port=1883)
client.connect()
display=lcd_display(oled)
display.show_LOGO()
time.sleep(1)
adc=ADC(Pin(32))
ir_left=Pin(34,Pin.IN)
ir_right=Pin(33,Pin.IN)
ir_left.irq(trigger=Pin.IRQ_RISING,handler=left_handler)
ir_right.irq(trigger=Pin.IRQ_RISING,handler=right_handler)
d=dht.DHT22(Pin(26))
select=Pin(27,Pin.IN,Pin.PULL_UP)
select.irq(trigger=Pin.IRQ_RISING,handler=select_hanlder)
timer.init(period=2000,mode=Timer.PERIODIC,callback=publish_data)
while True:
d.measure()
temp=d.temperature()
hum=d.humidity()
if p==0 and state:
display.show_sensor(temp,hum)
elif p==0:
display.menu_left()
if p==1:
display.menu_right()
#print(state)