Skip to content

Commit c8a08bc

Browse files
committed
umqtt.simple: Add example to toggle an LED on received subscribed message.
1 parent 64eab7c commit c8a08bc

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

umqtt.simple/example_sub_led.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from umqtt.simple import MQTTClient
2+
from machine import Pin
3+
import ubinascii
4+
import machine
5+
import micropython
6+
7+
8+
# ESP8266 ESP-12 modules have blue, active-low LED on GPIO2, replace
9+
# with something else if needed.
10+
led = Pin(2, Pin.OUT, value=1)
11+
12+
# Default MQTT server to connect to
13+
SERVER = "192.168.1.35"
14+
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
15+
TOPIC = b"led"
16+
17+
18+
state = 0
19+
20+
def sub_cb(topic, msg):
21+
global state
22+
print((topic, msg))
23+
if msg == b"on":
24+
led.value(0)
25+
state = 1
26+
elif msg == b"off":
27+
led.value(1)
28+
state = 0
29+
elif msg == b"toggle":
30+
# LED is inversed, so setting it to current state
31+
# value will make it toggle
32+
led.value(state)
33+
state = 1 - state
34+
35+
36+
def main(server=SERVER):
37+
c = MQTTClient(CLIENT_ID, server)
38+
# Subscribed messages will be delivered to this callback
39+
c.set_callback(sub_cb)
40+
c.connect()
41+
c.subscribe(TOPIC)
42+
print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
43+
44+
try:
45+
while 1:
46+
#micropython.mem_info()
47+
c.wait_msg()
48+
finally:
49+
c.disconnect()

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy