# LIBRARIES
from machine import I2C, Pin
from time import sleep , sleep_us , ticks_us #so that sleep funciton can be used , similar to delay in arduino ide.
from pico_i2c_lcd import I2cLcd
import network
from umqttsimple import MQTTClient
# PIN DEFINITIONS
# INITIALIZE OBJECTS
i2c_connection = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
I2C_ADDR = i2c_connection.scan()[0] #to get the I2C address
lcd = I2cLcd(i2c_connection, I2C_ADDR, 2, 16) #create lcd object
# LOCAL FUNCTIONS
# The callback function
def sub_callback(topic, msg):
print("Received: {}:{}".format(topic.decode(), msg.decode()))
lcd.clear()
lcd.putstr("Topic: {}\nMessage: {}".format(topic.decode(), msg.decode()))
def wifi_connect():
#Configure your password
SSID = ""
Password = ""
print("Connecting to WiFi", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST","")
while not wlan.isconnected():
print(".", end="")
sleep(0.1)
print(wlan.ifconfig())
print("WiFi Connected!")
def connectMQTT():
client = MQTTClient(client_id="stemventor-dhruv-test",
server="75a0d190cbec4e48be1541fd29bb5360.s1.eu.hivemq.cloud",
port=8883,
user="device001",
password="device001",
keepalive=7200,
ssl=True,
ssl_params={'server_hostname':'75a0d190cbec4e48be1541fd29bb5360.s1.eu.hivemq.cloud'}
)
client.connect()
return client
def publish(topic, value):
print(topic)
print(value)
client.publish(topic, value)
print("publish Done")
lcd.clear()
lcd.putstr("publish done")
# MAIN CODE
print(I2C_ADDR)
lcd.backlight_on()
wifi_connect()
client = connectMQTT()
client.set_callback(sub_callback)
client.subscribe(topic = "stemventor/test/subscribe")
lcd.putstr("ready to receive message")
while True:
client.check_msg()
sleep(0.1)