Created
May 21, 2020 13:07
-
-
Save benevpi/338dccc931393fd19122cd05b97aa908 to your computer and use it in GitHub Desktop.
a micropython for turning an io pin on or off based on an Adafruit IO feed
This file contains hidden or 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 | |
import time | |
from umqtt.robust import MQTTClient | |
import os | |
import sys | |
from machine import Pin | |
ADAFRUIT_IO_URL = b'io.adafruit.com' | |
ADAFRUIT_USERNAME = b'<insert username here>' | |
ADAFRUIT_IO_KEY = b'<insert Adafruit IO key here>' | |
ADAFRUIT_IO_FEEDNAME = b'<insert feedname here>' | |
WIFI_SSID = '<insert wifi network SSID here>' | |
WIFI_PASSWORD = '<insert wifi password here>' | |
PIN_NUMBER = 5 | |
onoffpin = Pin(PIN_NUMBER, Pin.OUT) | |
def cb(topic, msg): | |
global p5 | |
print('Received Data: Topic = {}, Msg = {}'.format(topic, msg)) | |
if msg == b"ON": p5.value(0) #LED in on when low on the Lolin32 | |
else: p5.value(1) | |
ap_if = network.WLAN(network.AP_IF) | |
ap_if.active(False) | |
wifi = network.WLAN(network.STA_IF) | |
wifi.active(True) | |
wifi.connect(WIFI_SSID, WIFI_PASSWORD) | |
MAX_ATTEMPTS = 20 | |
attempt_count = 0 | |
while not wifi.isconnected() and attempt_count < MAX_ATTEMPTS: | |
attempt_count += 1 | |
time.sleep(1) | |
if attempt_count == MAX_ATTEMPTS: | |
print('could not connect to the WiFi network') | |
sys.exit() | |
random_num = int.from_bytes(os.urandom(3), 'little') | |
mqtt_client_id = bytes('client_'+str(random_num), 'utf-8') | |
client = MQTTClient(client_id=mqtt_client_id, | |
server=ADAFRUIT_IO_URL, | |
user=ADAFRUIT_USERNAME, | |
password=ADAFRUIT_IO_KEY, | |
ssl=False) | |
client.connect() | |
mqtt_feedname = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_FEEDNAME), 'utf-8') | |
client.set_callback(cb) | |
client.subscribe(mqtt_feedname) | |
mqtt_feedname_get = bytes('{:s}/get'.format(mqtt_feedname), 'utf-8') | |
client.publish(mqtt_feedname_get, '\0') | |
while True: | |
client.wait_msg() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hat tip to Mike Teachman. This builds of his work here: https://github.com/miketeachman/micropython-adafruit-mqtt-esp8266