MQTT-Node-RED顯示超音波測距數據+控制LED-mpython
超音波測距(SC-SR04)實驗回顧-點我回顧
樹莓派上裝MQTT和Nord-RED回顧-點我回顧
上述兩個都測試好之後就進入主程式部份
程式
from time import sleep
from machine import Pin, ADC, reset
from umqtttsimple import MQTTClient
import binascii, micropython, network, time, socket, machine
ssid = "---"
password = "---------"
mqtt_server = "192.168.--.--"
#將客戶端ID轉換為16進位,以便MQTT伺服端讀取
client_id = binascii.hexlify(machine.unique_id())
#和Nord-RED上的主題一致
client_adc = b'esp32/value'
client_led = b'esp32/output'
led = Pin(2, Pin.OUT)
lastTime = 0
currentTime = time.time()
#wifi連線
def connectWifi():
global ssid, password
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(ssid, password)
while wifi.isconnected() == False:
pass
print("Connected successful!")
print("IP: {}".format(wifi.ifconfig()))
#樹莓派上的mqtt回應訂閱
def sub_backCall(topic, msg):
global led
print((topic, msg))
if msg == b"on":
led.on()
elif msg == b'off':
led.off()
#連線MQTT,連線成功後訂閱主題
def connToMqtt():
try:
client = MQTTClient(client_id, mqtt_server)
client.set_callback(sub_backCall)
client.connect()
client.subscribe(client_led)
print("connect to %s"%mqtt_server)
return client
#如果無法連線重新連線
except OSError as e:
print("not to connected for MQTT server!")
machine.reset()
#讀取ADC數值
def readVal():
adc = ADC(Pin(36))
adc.atten(ADC.ATTN_11DB)
ADC.width(ADC.WIDTH_10BIT)
while True:
val =adc.read()
return val
connectWifi()
client = connToMqtt()
while True:
#檢查有無進來的訊息
client.check_msg()
value = readVal()
print('val = {}'.format(value))
#發送可調電阻值到MQTT
client.publish(client_adc, str(value))
sleep(0.05)
Nord-RED布署
紫色區塊的主題要和程式一致
client_adc = b'esp32/value'
client_led = b'esp32/output'
開關Payload要和程式接收到的msg一致
#樹莓派上的mqtt回應訂閱
def sub_backCall(topic, msg):
global led
print((topic, msg))
if msg == b"on":
led.on()
elif msg == b'off':
led.off()