Node.js Raspberry Pi Blinking LED
In this tutorial, we will learn to control an LED connected to the Raspberry Pi using Node.js. We will use the onoff
library, which provides an easy-to-use interface for controlling GPIO pins on the Raspberry Pi.
Prerequisites
Before starting with this tutorial, you should have:
- A Raspberry Pi with Raspbian installed.
- An LED connected to the Raspberry Pi with a resistor in series.
Wiring Setup
Connect the positive lead (anode) of the LED to GPIO 17 (BCM pin 17). Connect the negative lead (cathode) of the LED to any of the ground pins on the Raspberry Pi. Don't forget to include a resistor in series with the LED, typically between 220Ω and 1kΩ.
Installation
We need to install the onoff
library to control GPIO pins on the Raspberry Pi. Use the following command to install the library:
$ npm install onoff
Syntax
var Gpio = require('onoff').Gpio;
var led = new Gpio(17, 'out');
function blinkLED() {
if (led.readSync() === 0) {
led.writeSync(1);
} else {
led.writeSync(0);
}
}
setInterval(blinkLED, 1000); // blink LED every 1 second
Example
var Gpio = require('onoff').Gpio;
var led = new Gpio(17, 'out');
function blinkLED() {
if (led.readSync() === 0) {
led.writeSync(1);
} else {
led.writeSync(0);
}
}
setInterval(blinkLED, 1000); // blink LED every 1 second
Output
When we run the above code, the LED connected to GPIO 17 will start blinking at an interval of 1 second.
Explanation
In the above example, we first imported the Gpio
class from the onoff
library and created an instance of it. We then defined a function called blinkLED()
which reads the current state of the LED and toggles it on or off. Finally, we used the setInterval()
function to call blinkLED()
every 1 second to make the LED blink.
Use
You can use this code as a starting point for controlling GPIO pins on the Raspberry Pi using Node.js. You can modify the code to control different pins or add additional functionality based on your requirements.
Important Points
- Incorrect wiring can damage the Raspberry Pi, so be careful while connecting the LED.
- Always use a resistor in series with the LED to prevent it from getting damaged due to excess current.
- Make sure you have Raspbian installed on your Raspberry Pi before starting with this tutorial.
Summary
In this tutorial, we learned how to control an LED connected to the Raspberry Pi using Node.js. We used the onoff
library to toggle the LED on and off and used the setInterval()
function to make it blink at a regular interval. With this knowledge, you can now control GPIO pins on the Raspberry Pi using Node.js and build projects that incorporate physical computing.