import network
import time
from machine import Pin, ADC
import ujson
from umqtt.simple import MQTTClient
from math import log
# MQTT Server Parameters setting
MQTT_CLIENT_ID = "IIOT_ASSIGNMNET"
MQTT_BROKER = "mqtt.eclipseprojects.io"
MQTT_USER = ""
MQTT_PASSWORD= ""
MQTT_TOPIC = "IIOT/2024PD16004/TEMPERATURE"
# WiFi connection parameter setting
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!")
# MQTT connection setup
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
# Setting along pin configuration
ntc_pin = ADC(Pin(35))
ntc_pin.atten(ADC.ATTN_11DB)
R25 = 10000 # resistance at 25 Deg C
BETA = 3950 # should match the Beta Coefficient of the thermistor
# Pin 2 for digital display of msg
pin2 = Pin(2, Pin.OUT)
prev_value = -100
while True:
analog_value = ntc_pin.read()
voltage = analog_value * (3.3 / 4095)
R_ntc = R25 * (3.3 / voltage - 1)
temperature_celsius = 1 / (log(1 / (4095.0 / analog_value - 1)) / BETA + 1.0 / 298.15) - 273.15
if analog_value != prev_value:
print("Temperature: {:.2f} Deg C".format(temperature_celsius))
# MQTT publishing part .. send value every 5 sec
message = ujson.dumps({"TEMPERATURE": temperature_celsius})
client.publish(MQTT_TOPIC, message)
# Blinking LED every time
pin2.value(not pin2.value())
prev_value = analog_value
time.sleep(5) # Publish every 5 seconds
else:
pin2.value(not pin2.value())
time.sleep(0.5)