可調燈-PWM_LED-MQTT-micropython


可調燈-PWM_LED-MQTT–micropython

tags: micropython pwm led

這個其實是比較簡單的利用MQTT作法,所以就直接進入正題

材料

  • 樹莓派  x1
  • ESP32 x 1
  • 杜邦線 x少許
  • LED x 1
  • 10k歐姆雷阻 x 1

接線


MQTT_broker布局

樹莓派上裝MQTT和Nord-RED回顧-點我回顧

**1.**首先安裝好MQTT和NODE-RED後,在瀏覽器網址列開啓http://localhost:1880/

如果是樹莓派,localhost替換填上樹莓派的IP加上:1880

**2.**加入slider滑軌和mqtt_out發送

**3.**lable的地方填上PWM,range填入脈波範圍

**4.**接下來布置mqtt_out

服務器選擇本地端

主題填入esp32/pwm,這個是客戶端訂閱主題

**5.**最後按下右上角”部署


程式碼

from machine import Pin, PWM, freq, reset, sleep

import network, binascii, socket, machine

from umqtt.simple import MQTTClient

  
ssid = "---"

password = "--------"

#我樹苺派上的ip

serverIP = "192.168.97.22"

#將客戶端ID轉換為16進位,以便MQTT伺服端讀取

mqtt_id = binascii.hexlify(machine.unique_id())

  

#和Nord-RED上的主題一致

client_topic = b'esp32/pwm'

#led_pwm設定腳位和頻率

led_pwm = PWM(Pin(13), freq=500)

  

#wifi連線

def wifi_connect():

    wifi = network.WLAN(network.STA_IF)

    wifi.active(True)

    wifi.connect(ssid, password)

    while wifi.isconnected() == False:

        pass

    print("connected successed")

    print("IP: {}".format(wifi.ifconfig()))

#連線MQTT,連線成功後訂閱主題

def mqtt_connected():

    try:

        client = MQTTClient(mqtt_id, serverIP)

        client.set_callback(callBack)

        client.connect()

        client.subscribe(client_topic)

        print("connected to %s"%serverIP)

        print("subscribe Topic: %s"%client_topic)

        return client

    except OSError as e:

        print("it's not to connect, wait a moment to connect")

        machine.reset()

#樹莓派上的mqtt回應訂閱

def callBack(topic, msg):

    print((topic, msg))

    if topic == client_topic:

        led_pwm.duty(int(msg))

wifi_connect()

client = mqtt_connected()

while True:

    client.wait_msg()

文章作者: blairan
版權聲明: 本博客所有文章除特別聲明外,均採用 CC BY 4.0 許可協議。轉載請註明來源 blairan !
评论
  目錄