Discover more
1 安装 python的 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指令
2.3 树莓派上输出接收到对GPIO 17的指令
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}"
gpio {"pin":17,"value":0}
gpio {"pin":17,"value":1}