News

Discover more

用python接收MQTT消息,控制GPIO

  • 发布时间: 2020-09-18 10:51:22
  • 发布人: admin
  • 分类: 物联网技术

1 安装 python的 MQTT扩展库

pip install paho-mqtt 

助MQTT扩展库和树莓派的GPIO库,编写下面的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():
    # 采用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))
    # 获得负载中的pin 和 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代理服务器的IP地址
        client.connect("192.168.1.131", 1883, 60)
        client.loop_forever()
    except KeyboardInterrupt:
        client.disconnect()
        gpio_destroy()

2 在PC端发出消息,控制树莓派GPIO 17的高电平低电平

2.1 树莓派启动我们的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 树莓派上输出接收到对GPIO 17的指令

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


相关文章

上拉电阻和下拉电阻

上拉电阻和下拉电阻

在折腾Arduino或者树莓派信号输入的时候,时常听到的就是上拉电阻和下拉电阻,

查看全文

牛逼的树莓派dashboard

树莓派安装 Nginx + PHP7.3 + Pi Dashboard

查看全文

Linux 下使用 system

下面的教程将介绍如何将命令或程序配置为开机启动时自动运行的服务。完成配置之后,就

查看全文