首先,我们需要以下的材料:
树莓派2B+/3
x1
LED
x1
Micro USB线
x1
杜邦线
x2
220欧电阻
x1
Micro SD卡(8GB 以上)
x1
显示器、键盘、鼠标、网络线
@1
HDMI转换器或HDMI线
x1
步骤:
从树莓派网站( https://www.raspberrypi.org/downloads/ )下载RASPBIAN。
把LED、电阻和杜邦线如下图连接:
把杜邦线1、2连接到树莓派的7和9 pin
档案下载完成后,把它解压并完整复制到Micro SD卡中,再把Micro SD卡插到树莓派的卡槽中。
把键盘、鼠标、网络线、显示器(透过HDMI转换器或HDMI线)连接到树莓派。
把Micro USB线接上5V电源及树莓派
选择安装RASPBIAN
打开Terminal 并参考以下网页安装Mosquitto,请紧记”$ sudo mosquitto_passwd -c /etc/mosquitto/conf.d/passwd pi”之后输入的密码 : http://www.rs-online.com/designspark/electronics/eng/blog/building-distributed-node-red-applications-with-mqtt
输入以下指令以安装更新及必要的组件并重启树莓派:
$ sudo apt-get update $ sudo apt-get upgrade $ sudo pip-3.2 install paho-mqtt $ sudo reboot 打开 Node-RED并记下当中显示的IP地址
打开Python及贴上以下指令并储存为LED.py
#!/usr/bin/env python import paho.mqtt.client as mqtt import os import sys from time import sleep import RPi.GPIO as GPIO user = os.getuid() if user !=0: print "Please run script as root" sts.exit() LED=4 GPIO.setmode(GPIO.BCM) GPIO.setup(LED, GPIO.OUT) def pressed(msg): if msg == "On": GPIO.output(LED,True) if msg == "Off": GPIO.output(LED,False) def on_connect(client, userdata, flags, rc): client.subscribe("switch") def on_message(client, userdata, msg): print("got message on topic %s: %s" % (msg.topic, msg.payload)) msgTemp = msg.payload pressed(msgTemp) client = mqtt.Client() client.username_pw_set(username="pi", password="pipi") client.on_connect = on_connect client.on_message = on_message client.connect(" 地址 >", 1883) try: client.loop_forever() except KeyboardInterrupt: print("interrupted!") 输入以下指令以重新运行Mosquitto:
$ sudo /etc/init.d/mosquito stop $ sudo mosquitto 在Terminal 输入以下指令以作运行步骤11的指令:
$ sudo python \LED.py 以浏览器登入Node-RED版面中显示的IP地址如下图:
从左方input栏拉出两个“inject”方块,并双击方块,展开“timestamp”,选择 “string”,两个方块分别输入 “On”和 “Off”
再从左方output栏拉出“mqtt”方块,并双击方块,按下Server 右方的笔按钮, 在弹出窗口的 “Server”栏 输入 Raspberry Pi 的IP地址,按下Add,并在Topic栏输入 “switch”, 按 “Ok”
把3个方块如下图连接并按 “Deploy”
这时候,按On左方的按钮,LED会亮起,Off左方的按钮,LED会熄灭
来源:Designspark/sinwaikwong2000