MQTT&node-RED控制二軸云台-mpython
承接使用PWM控制伺服馬達-micropython這篇,透過node-red加入mqtt訂閱主題控制二軸云台
有一些感想紀錄下來,我發現其實像mqtt或者wifi連網,大都是固定一個寫法,其它不同的模組分為讀取數值或用數值受控制的元件,只要套用上去就可以。
首先主要是被控制的伺服馬達,所以先把它測試一下,參考這篇(點我)
測試好之後,就可以開始加入wifi和mqtt了,但因為我用的是樹莓派建立的MQTT,所以這陪分前提是要有樹苺派,如何在樹苺派上建立Node-RED和MQTT,可以參考這篇(點我)。
Node-RED設定
程式碼
from machine import SLEEP, Pin, PWM, freq
from time import sleep
from umqtttsimple import MQTTClient
import binascii, micropython, network, time, socket, machine
ssid = "------------"
password = "-------"
mqtt_server = "192.168.210.22"
#將客戶端ID轉換為16進位,以便MQTT伺服端讀取
mqtt_id = binascii.hexlify(machine.unique_id())
#和Nord-RED上的主題一致
client_servoPan = b'esp32/servoPan'
client_servoTilt = b'esp32/servoTilt'
servo_pan = PWM(Pin(13), freq=50)
servo_tilt = PWM(Pin(14), freq=50)
#wifi連線
def wifiConn():
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回應訂閱
# Duty 就為 2.5%、7.25%、12%,並 x1024 後可以轉換成 PWM Duty填入的數值
def callBack(topic, msg):
ang0 = int(1023*0.025)
ang90 = int(1023*0.0725)
ang180 = int(1023*0.12)
print((topic, msg))
if topic == client_servoPan:
servo_pan.duty(int(msg))
sleep(0.5)
elif topic == client_servoTilt:
servo_tilt.duty(int(msg))
sleep(0.5)
#連線MQTT,連線成功後訂閱主題
def connToMqtt():
try:
client = MQTTClient(mqtt_id, mqtt_server)
client.set_callback(callBack)
client.connect()
client.subscribe(client_servoPan)
client.subscribe(client_servoTilt)
print("connect to %s"%mqtt_server)
return client
#如果無法連線重新連線
except OSError as e:
print("not to connected for MQTT server!")
machine.reset()
wifiConn()
client = connToMqtt()
while True:
#檢查有無進來的訊息
client.check_msg()
調過等待時間還是會偶爾抖動,雖然不知道抖動原在哪,先這樣好了,下次再來抓原因。