LED ON/OFF
Fistly, you need to contruct the LED connection. Then, you can write a script to turn the LED on and off.
Start by making a directory where we can keep our Node.js scripts:
mkdir nodetest/LED
Go to our new directory:
cd nodetest/LED
Now we will create a new file called “led_onoff.js” using the Nano Editor:
sudo nano led_onoff.js
The file is now open and can be edited with the built in Nano Editor.
Write, or paste the following code:
#———————————————————————————-#
var Gpio = require (‘onoff’).Gpio // include onoff library with GPIO
var LED = new Gpio(17,’out’) // pin BCM17 as an output
LED.writeSync(0); // turn off LED
process.on(‘SIGINT’, () =>
{
led.unexport();
});
#———————————————————————————-#
LED Blinking
Now we will create a new file called “led_blink.js” using the Nano Editor:
sudo nano led_blink.js
The file is now open and can be edited with the built in Nano Editor.
Write, or paste the following code:
#———————————————————————————-#
var Gpio = require (‘onoff’).Gpio // include onoff library with GPIO
var LED = new Gpio(17,’out’) // pin BCM17 as an output
function blinkLED()
{
if(LED.readSync()==0) // check pin state whether in ON or OFF
{LED.writeSync(1);} // turn on LED
else
{LED.writeSync(0);} // turn off LED
}
LED.writeSync(0); // turn off LED
setInterval(blinkLED, 250); // call the function blinkLED and run the function every 250ms