"""
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ An example code to interact with a temperature sensor ┃
┃ Raspberry Pi Pico. ┃
┃ ┃
┃ Copyright (c) 2023 Vinh Bui ┃
┃ License: MIT ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
"""
#import libraries
from machine import Pin, ADC
import utime
import math
import network
import time
from machine import Pin
import dht
import ujson
from umqttsimple import MQTTClient
# WiFi Network Parameters
# SSID: Wokwi-GUEST
# Security: Open
print("Connecting to WiFi", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST", "")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.1)
print(wlan.ifconfig())
print("WiFi Connected!")
# MQTT Server Parameters
MQTT_CLIENT_ID = "picow-01"
MQTT_BROKER = "80230f1c0f6147308f8792b5ec91e45b.s1.eu.hivemq.cloud"
MQTT_USER = "client-1"
MQTT_PASSWORD = "CEghmV31K4HC678HH5Pd81Tp"
MQTT_TOPIC = "prog6002/test"
print("Connecting to MQTT server... ", end="")
client = MQTTClient(client_id=MQTT_CLIENT_ID,
server=MQTT_BROKER, user=MQTT_USER,
password=MQTT_PASSWORD,
keepalive=7200,
ssl=True,
ssl_params={'server_hostname':'80230f1c0f6147308f8792b5ec91e45b.s1.eu.hivemq.cloud'})
# The callback function
def sub_callback(topic, msg):
print("Received: {}:{}".format(topic.decode(), msg.decode()))
led.high() #turn the led ON
client.set_callback(sub_callback)
client.connect()
client.subscribe(topic = MQTT_TOPIC)
print("MQTT Connected!")
#define the temperature sensor input pin
TSENSOR_INPUT_PIN = 28
LED_OUTPUT_PIN = 27
#convert the sensor reading to temperature in celsius
def adc2celsius(x):
BETA = 3950
KELVIN = 273.15
return (1 / (math.log(1 / (65535/x-1)) / BETA + 1/298.15) - KELVIN)
def main():
prev = ""
tempsensor = machine.ADC(TSENSOR_INPUT_PIN)
warning_led = Pin(27, Pin.OUT)
while True:
reading = tempsensor.read_u16()
celsius = adc2celsius(reading)
print("Temp: {:.2f} c".format(celsius))
# new: send to cloud using MQTT
message = ujson.dumps({
"temp": celsius,
})
if message != prev:
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev = message
else:
print(".")
if celsius < 24:
warning_led.high()
else:
warning_led.low()
utime.sleep(1.0)
if __name__ == "__main__":
main()