Home
Features
_Multi DropDown
__DropDown 1
__DropDown 2
__DropDown 3
_ShortCodes
_SiteMap
_Error Page
Mega Menu
Documentation
_Web Documentation
_Video Documentation
Privacy Policy
Daftar Isi
Beranda
Micropython Button Toggle to MQTT
Micropython Button Toggle to MQTT
Mei 03, 2022
Micropython Button Toggle to MQTT
import time from umqtt_simply import MQTTClient import ubinascii import machine import micropython import network import esp from machine import Pin tombol=Pin(4, Pin.IN) led=Pin(2, Pin.OUT) flag=True hitung=1 esp.osdebug(None) import gc gc.collect() ssid = 'AFFAN' password = '66666666' mqtt_server = 'broker.hivemq.com' #EXAMPLE IP ADDRESS #mqtt_server = '192.168.1.144' client_id = ubinascii.hexlify(machine.unique_id()) topic_sub = b'relay0' topic_pub = b'relay1' last_message = 0 message_interval = 15 counter = 0 #msg='Off' station = network.WLAN(network.STA_IF) station.active(True) station.connect(ssid, password) while station.isconnected() == False: pass def sub_cb(topic, msg): print((topic, msg)) if topic == b'relay0' and msg == b'off': print('ESP received OFF message') #receive msq from topic def connect_and_subscribe(): global client_id, mqtt_server, topic_sub client = MQTTClient("client", mqtt_server) client.set_callback(sub_cb) client.connect() client.subscribe(topic_sub) print('Connection successful') print(station.ifconfig()) print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub)) return client def restart_and_reconnect(): print('Failed to connect to MQTT broker. Reconnecting...') time.sleep(100) machine.reset() try: client = connect_and_subscribe() except OSError as e: restart_and_reconnect() while True: try: client.check_msg() status_tombol = tombol.value() if (time.time() - last_message) > message_interval: #msg = 'On-Off #%d' % counter msg='On' if (status_tombol == flag and flag==True): flag = False hitung = hitung + 1 if(hitung==1): msg='On' led.value(0) client.publish(topic_pub, msg) if(hitung==2): msg='Off' led.value(1) client.publish(topic_pub, msg) hitung=0 if(status_tombol==0): flag=True print(msg) time.sleep(1) #client.publish(topic_pub, msg) #publish msg to topic last_message = time.time() counter += 1 except OSError as e: restart_and_reconnect()
Social Plugin
ARTIKEL
3/recent/post-list
Facebook
Subscribe Us