Created
May 14, 2024 06:14
Raspberry Pi Pico W MicroPython MQTT Tutorial | Control LED using MQTT Node Red
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import network | |
from umqtt.simple import MQTTClient | |
import time | |
import machine | |
MQTT_BROKER="YOUR_SYSTEM_IP" | |
MQTT_PORT = 1883 | |
MQTT_CLIENT_ID="pico_client" | |
led_green = machine.Pin(0, machine.Pin.OUT) | |
led_red = machine.Pin(1, machine.Pin.OUT) | |
#subscribe topics | |
sub_topic_red_led="led_red/topic" | |
sub_topic_green_led="led_green/topic" | |
#publish topic | |
pub_topic_temperature = "temperature/topic" | |
# Connect to the WiFi | |
wlan = network.WLAN(network.STA_IF) | |
wlan.active(True) | |
wlan.connect("YOUR_SSID", "YOUR_PASSWORD") | |
while not wlan.isconnected(): | |
time.sleep(1) | |
print("Connected to the WiFi") | |
def callback(topic, msg): | |
sub_msg = msg.decode('utf-8') | |
sub_topic =topic.decode('utf-8') | |
print("Received message - ", sub_msg , "on topic - ",sub_topic) | |
# if led_red == led_red | |
if sub_topic == sub_topic_red_led: | |
led_red.value(int(sub_msg)) | |
elif sub_topic == sub_topic_green_led: | |
led_green.value(int(sub_msg)) | |
mqtt_client = MQTTClient(client_id=MQTT_CLIENT_ID, server=MQTT_BROKER, port=MQTT_PORT) | |
mqtt_client.set_callback(callback) | |
mqtt_client.connect() | |
print("Connected to MQTT broker") | |
mqtt_client.subscribe(sub_topic_red_led) | |
mqtt_client.subscribe(sub_topic_green_led) | |
def read_temperature(): | |
adc = machine.ADC(4) # Use ADC pin GP4 | |
conversion_factor = 3.3 / (65535) # ADC conversion factor | |
sensor_value = adc.read_u16() * conversion_factor | |
temperature = 27 - (sensor_value - 0.706) / 0.001721 # Convert sensor value to temperature (formula may vary) | |
return temperature | |
try: | |
while True: | |
mqtt_client.check_msg() | |
temperature = read_temperature() | |
temp_str = str(temperature) | |
mqtt_client.publish(pub_topic_temperature,temp_str.encode('utf-8')) | |
print('Temp published',temperature) | |
time.sleep(2) | |
except KeyboardInterrupt: | |
print('Disconnected!') | |
mqtt_client.disconnect() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment