News

Discover more

用(yòng)python接收MQTT消息,控制GPIO


1 安裝 python的(de) MQTT擴展庫

pip install paho-mqtt 

助MQTT擴展庫和(hé)樹莓派的(de)GPIO庫,編寫下(xià)面的(de)python代碼,保存到testgpio.py中

# -*- coding: utf-8 -*-  
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import json
 
# BCM GPIO編号
pins = [17,18,27,22,23,24,25,4]
def gpio_setup():
    # 采用(yòng)BCM編号
    GPIO.setmode(GPIO.BCM)
    # 設置所有GPIO爲輸出狀态,且輸出低電平
    for pin in pins:
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, GPIO.LOW)
        
def gpio_destroy():
    for pin in pins:
        GPIO.output(pin, GPIO.LOW)
        GPIO.setup(pin, GPIO.IN)
        
# 連接成功回調函數
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    # 連接完成之後訂閱gpio主題
    client.subscribe("gpio")
 
# 消息推送回調函數
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
    # 獲得(de)負載中的(de)pin 和(hé) value
    gpio = json.loads(str(msg.payload))
 
    if gpio['pin'] in pins:
        if gpio['value'] == 0:
            GPIO.output(gpio['pin'], GPIO.LOW)
        else:
            GPIO.output(gpio['pin'], GPIO.HIGH)
 
if __name__ == '__main__':
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    gpio_setup()
    
    try:
        # 請根據實際情況改變MQTT代理(lǐ)服務器的(de)IP地址
        client.connect("192.168.1.131", 1883, 60)
        client.loop_forever()
    except KeyboardInterrupt:
        client.disconnect()
        gpio_destroy()

2 在PC端發出消息,控制樹莓派GPIO 17的(de)高(gāo)電平低電平

2.1 樹莓派啓動我們的(de)python代碼

python testgpio.py
testgpio.py:13: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(pin, GPIO.OUT)
Connected with result code 0
2.2 PC端輸入GPIO指令

C:\Program Files\mosquitto>mosquitto_pub -h 192.168.43.131 -t gpio -m "{\"pin\":17,\"value\":0}"

C:\Program Files\mosquitto>mosquitto_pub -t gpio -h 192.168.43.131 -m "{\"pin\":17,\"value\":1}"
2.3 樹莓派上輸出接收到對(duì)GPIO 17的(de)指令

gpio {"pin":17,"value":0}
gpio {"pin":17,"value":1}


相關文章(zhāng)

上拉電阻和(hé)下(xià)拉電阻

上拉電阻和(hé)下(xià)拉電阻

在折騰Arduino或者樹莓派信号輸入的(de)時(shí)候,時(shí)常聽(tīng)到的(de)就是上拉電阻和(hé)下(xià)拉電阻,

查看全文

牛逼的(de)樹莓派dashboard

樹莓派安裝 Nginx + PHP7.3 + Pi Dashboard

查看全文

Linux 下(xià)使用(yòng) system

下(xià)面的(de)教程将介紹如何将命令或程序配置爲開機啓動時(shí)自動運行的(de)服務。完成配置之後,就

查看全文