import machine
import time, math
from machine import Pin, PWM, Timer, I2C, ADC
import dht
import ssd1306
#import paho.mqtt.client as mqtt
from umqtt.robust import MQTTClient
import ujson
import network
import ssd1306
online = True
cmdmode = False
# Pin configurations
start_button = Pin(23, Pin.IN, Pin.PULL_UP)
stop_button = Pin(19, Pin.IN, Pin.PULL_UP)
relay = Pin(33, Pin.OUT)
switch = Pin(25, Pin.IN, Pin.PULL_UP)
pwm = PWM(Pin(18), freq=50, duty=0)
# Wi-Fi and MQTT configurations
wifi_ssid = "Wokwi-GUEST"
wifi_pwd = ""
MQTT_BROKER = "broker.netpie.io"
MQTT_CLIENT = "e4dca146-ac0a-42ae-a52a-4b3c9b6666fb" # Fill in your NETPIE2020 data
MQTT_USER = "tcppiftiXc3RP6Um6MpjjZ2g6E8xVdL5"
MQTT_PWD = "9Hx61pAXQmVCdpEcL6BhXpPALkcTy39S"
PUBLISH_PERIOD = 2000 # milliseconds
t = 0 # Temperature
h = 0 # Humidity
Mode = 0 # Auto = 0, Manual = 1
sensor = dht.DHT22(Pin(14))
sensor_data = {'T': 0, 'H': 0, 'S': 0}
cmdtime_current = 0 # This delay is needed for nodered
cmdtime_prev = 0
CMD_DELAY = 1000
# ---- OLED function -----------
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
def oled_show(oled,t, h, Mode):
oled.fill(0)
l1_txt = "T : "+ str(round(t,2))
l2_txt = "H : "+ str(round(h,2))
l3_txt = "Mode : "+str(Mode)
oled.text(l1_txt,0,0)
oled.text(l2_txt,0,20)
oled.text(l3_txt,0,40)
oled.show()
# -----------------------------------
def read_DHT22():
global t, h
sensor.measure()
t = sensor.temperature()
h = sensor.humidity()
print(f"Temperature: {round(t, 2)}°C, Humidity: {round(h, 2)}%")
# ----- wifi and IoT functions ---------
def wifi_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect(wifi_ssid, wifi_pwd)
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
def init_client():
global client
print("Trying to connect to mqtt broker.")
try:
client = MQTTClient(MQTT_CLIENT, MQTT_BROKER, port=1883, user=MQTT_USER,
password=MQTT_PWD)
#client.set_callback(callback)
client.connect()
print("Connected to ",MQTT_BROKER)
topic_sub = b"@msg/cmd"
print("Subscribed to ",topic_sub)
client.set_callback(sub_cb)
client.subscribe(topic_sub)
except:
print("Trouble to init mqtt.")
def sub_cb(topic, msg):
global cmdtime_current, cmdtime_prev
print((topic, msg))
if topic == b'@msg/cmd':
rcvdstrs = str(msg).split("'") # get rid of b'
rcvdstr = rcvdstrs[1]
cmdInt(rcvdstr)
#print(topic)
def update_dashboard():
timestamp = time.ticks_ms()
updatestr = str(timestamp) + ": Varodom Toochinda 6312345678"
print("@msg/update : " + updatestr)
if online:
client.publish('@msg/update', updatestr)
# -----------------------------------------------------
#command interpreter function
def cmdInt(userstr):
global mindist, cmdmode
result = userstr.find("=")
if result == -1:
noparm = 1
cmdstr = userstr.strip()
else:
noparm = 0
splitstr = userstr.split("=")
cmdstr = splitstr[0].strip()
parmstr = splitstr[1].strip()
#print(cmdstr)
#print(parmstr)
if cmdstr.lower() == "mindist":
# set minimum distance
if noparm==1:
print("Current minimum distance = {} cm".format(mindist))
else:
mindist = float(parmstr)
if mindist > 60.0: # limit range
mindist = 60.0
elif mindist < 5.0:
mindist = 5.0
elif cmdstr.lower() == "distance":
print("distance = "+str(distance))
elif cmdstr.lower() == "sendname":
update_dashboard()
# elif cmdstr.lower() == "run":
# cmdmode = False
else:
print("Invalid command")
if online:
wifi_connect() # connect to WiFi network
init_client()
# set publish period
time_prev = 0
time_current = 0
def user_input():
print('\nEnter command : ')
user_str = input()
cmdInt(user_str)
def enable_cmd():
global cmdmode
cmdmode = True
def turn(position: int = 90):
if position < 0:
position = 0
if position > 180:
position = 180
pwm.duty(int(((position)/180 *2 + 0.5) / 20 * 1023))
def Servo():
position = 90
while True:
# control turn left / right.
if not start_button.value():
position -= 1 # turn left
elif not stop_button.value():
position += 1 # turn right
turn(position)
time.sleep(0.01)
while True:
Servo()