FUSION AUTOMATE
Published © GPL3+

Monitor Raspberry Pi Pico W Internal Temperature via MQTT

How to Monitor Raspberry Pi Pico W Internal Temperature via Mosquitto MQTT Broker over LAN

BeginnerProtip1 hour591
Monitor Raspberry Pi Pico W Internal Temperature via MQTT

Things used in this project

Hardware components

Raspberry Pi Pico W
Raspberry Pi Pico W
×1

Software apps and online services

MicroPython
MicroPython
Windows 10
Microsoft Windows 10

Story

Read more

Code

main.py

Python
# Import necessary libraries
import time
from machine import ADC
from umqtt.simple import MQTTClient

# WiFi and MQTT Broker Configuration
WIFI_SSID = ""               # Insert your WiFi SSID
WIFI_PASSWORD = ""           # Insert your WiFi password
MQTT_BROKER = ""             # Insert your MQTT broker IP address or domain
MQTT_PORT = 1883             # Default MQTT port
MQTT_TOPIC = "Internal Pico-W Temp"  # MQTT topic to publish temperature data

# ADC Configuration
ADCPIN = 4                   # ADC pin for reading temperature
adc = ADC(ADCPIN)

# MQTT Client Configuration
client = MQTTClient("pico_client", MQTT_BROKER, MQTT_PORT)

# Function to read temperature from internal sensor
def read_temperature():
    adc_value = adc.read_u16()          # Read ADC value
    volt = (3.3 / 65535) * adc_value   # Convert ADC value to voltage
    temperature = 27 - (volt - 0.706) / 0.001721  # Convert voltage to temperature
    return round(temperature, 1)        # Round temperature to one decimal place

# Function to connect to WiFi network
def connect_to_wifi():
    import network
    station = network.WLAN(network.STA_IF)    # Create WiFi station interface
    station.active(True)                      # Activate WiFi station
    station.connect(WIFI_SSID, WIFI_PASSWORD) # Connect to WiFi
    while not station.isconnected():          # Wait until connected
        pass
    print("Connected to WiFi")

# Function to connect to MQTT broker
def connect_to_mqtt():
    client.connect()                          # Connect MQTT client to broker
    print("Connected to MQTT Broker")

# Function to publish temperature to MQTT broker
def publish_temperature():
    temperature = read_temperature()          # Read temperature
    client.publish(MQTT_TOPIC, str(temperature))  # Publish temperature to MQTT topic
    #print("Published temperature:", temperature)  # Uncomment for debug

# Main function
def main():
    connect_to_wifi()                         # Connect to WiFi network
    connect_to_mqtt()                         # Connect to MQTT broker
    while True:
        publish_temperature()                 # Publish temperature data
        time.sleep(5)                         # Wait 5 seconds before next reading

if __name__ == "__main__":
    main()  # Run main function when script is executed

Credits

FUSION AUTOMATE
25 projects • 3 followers
Contact

Comments

Please log in or sign up to comment.