在本章中,我们将使用多个 GPIO 引脚,通过按顺序打开和关闭它们来创建 "flowing" 效果。
为此,您需要:
笔记:您需要的电阻器可能与我们使用的不同,具体取决于您使用的 LED 类型。大多数小型 LED 仅需要一个小电阻,大约 200-500 欧姆。通常使用的具体值并不重要,但电阻值越小,LED 就会越亮。
单击上面列表中的链接以获取不同组件的说明。
现在是时候在我们的面包板上构建电路了。
如果您不熟悉电子产品,我们建议您关闭 Raspberry Pi 的电源。并使用防静电垫或接地带以避免损坏。
使用以下命令正确关闭 Raspberry Pi:
pi@w3demopi:~ $ sudo shutdown -h now
当 Raspberry Pi 上的 LED 停止闪烁后,从 Raspberry Pi 上拔下电源插头(或关闭其连接的电源板)。
仅拔掉插头而不正确关闭可能会导致存储卡损坏。
看上面的电路图。
您的电路现在应该已经完成,并且您的连接应该与上图非常相似。
现在是时候启动 Raspberry Pi 并编写 Node.js 脚本与其交互了。
转到 "nodetest" 目录,然后创建一个名为“flowingleds.js
”:
pi@w3demopi:~ $ nano flowingleds.js
该文件现已打开,可以使用内置的 Nano 编辑器进行编辑。
编写或粘贴以下内容:
var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIO
var LED04 = new Gpio(4, 'out'), //use declare variables for all the GPIO output pins
LED17 = new Gpio(17, 'out'),
LED27 = new Gpio(27, 'out'),
LED22 = new Gpio(22, 'out'),
LED18 = new Gpio(18, 'out'),
LED23 = new Gpio(23, 'out'),
LED24 = new Gpio(24, 'out'),
LED25 = new Gpio(25, 'out');
//Put all the LED variables in an array
var leds = [LED04, LED17, LED27, LED22, LED18, LED23, LED24, LED25];
var indexCount = 0; //a counter
dir = "up"; //variable for flowing direction
var flowInterval = setInterval(flowingLeds, 100); //run the flowingLeds function every 100ms
function flowingLeds() { //function for flowing Leds
leds.forEach(function(currentValue) { //for each item in array
currentValue.writeSync(0); //turn off LED
});
if (indexCount == 0) dir = "up"; //set flow direction to "up" if the count reaches zero
if (indexCount >= leds.length) dir = "down"; //set flow direction to "down" if the count reaches 7
if (dir == "down") indexCount--; //count downwards if direction is down
leds[indexCount].writeSync(1); //turn on LED that where array index matches count
if (dir == "up") indexCount++ //count upwards if direction is up
};
function unexportOnClose() { //function to run when exiting program
clearInterval(flowInterval); //stop flow interwal
leds.forEach(function(currentValue) { //for each LED
currentValue.writeSync(0); //turn off LED
currentValue.unexport(); //unexport GPIO
});
};
process.on('SIGINT', unexportOnClose); //function to run when user closes using ctrl+cc
按下Ctrl+x
保存代码。确认使用 "y
",并确认名称使用 "Enter
"。
运行代码:
pi@w3demopi:~ $ node flowingleds.js
现在 LED 应该按顺序打开和关闭,产生流动的效果。
结束程序Ctrl+c
。