2020年5月28日 星期四

用MicroPython設計遠距情境燈以機智雲為例

遠距情境燈是指可以在遠方使用資通訊設備,例如:電腦和手機,來進行控制LED的顏色。我們採用物聯網通訊協定MQTT,以主題R,G, B來分別控制紅色、綠色、藍色的亮度,進而經由RGB三種顏色來調變RGB LED顏色。

機智雲:http://wiki.ai-thinker.com/esp8266/boards/gizwits
MicroPython的MQTT參考程式如下:
https://randomnerdtutorials.com/micropython-mqtt-esp32-esp8266/

把該網頁的程式改成遠距情境燈。
boot.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Complete project details at https://RandomNerdTutorials.com

import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
esp.osdebug(None)
import gc
gc.collect()

ssid = '您的熱點'
password = '您的密碼'
mqtt_server = 'broker.hivemq.com'
#EXAMPLE IP ADDRESS
#mqtt_server = '192.168.1.144'
client_id = ubinascii.hexlify(machine.unique_id())
topic_sub = b'R'
topic_sub2 = b'G'
topic_sub3 = b'B'
topic_pub = b'hello'

last_message = 0
message_interval = 5
counter = 0

station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

print('Connection successful')
print(station.ifconfig())

main.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Complete project details at https://RandomNerdTutorials.com
R=0
G=0
B=0
def sub_cb(topic, msg):
  global R, G, B
  print((topic, msg))
  if topic == b'R':
    print('R=', msg)
    try:
      R=int(msg,10)
    except:
      R=0
  if topic == b'G':
    print('G=', msg)
    try:
      G=int(msg,10)
    except:
      G=0
  if topic == b'B':
    print('G=', msg)
    try:
      B=int(msg,10)
    except:
      B=0
  RedLED.duty(R)
  GreenLED.duty(G)
  BlueLED.duty(B)

def connect_and_subscribe():
  global client_id, mqtt_server, topic_sub, topic_sub2, topic_sub3
  client = MQTTClient(client_id, mqtt_server)
  client.set_callback(sub_cb)
  client.connect()
  client.subscribe(topic_sub)
  client.subscribe(topic_sub2)
  client.subscribe(topic_sub3)
  print('Connected to %s MQTT broker, subscribed to %s, %s, %s topic' % (mqtt_server, topic_sub, topic_sub2, topic_sub3))
  return client

def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  time.sleep(10)
  machine.reset()

from machine import Pin, PWM
import time
RedLED = PWM(Pin(15))
GreenLED = PWM(Pin(12))
BlueLED=  PWM(Pin(13))
RedLED.duty(0)
GreenLED.duty(0)
BlueLED.duty(0) 

try:
  client = connect_and_subscribe()
except OSError as e:
  restart_and_reconnect()

while True:
  try:
    client.check_msg()
    if (time.time() - last_message) > message_interval:
      msg = b'Hello #%d' % counter
      client.publish(topic_pub, msg)
      last_message = time.time()
      counter += 1
  except OSError as e:
    restart_and_reconnect()