Node.js Raspberry Pi Following LED

Node.js Raspberry Pi Following LED


Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine, which can be used to run JavaScript on a Raspberry Pi. In this tutorial, we will be using Node.js to control a simple LED connected to the Raspberry Pi.

Before we begin, make sure you have a Raspberry Pi with Raspbian installed, and a breadboard and LED connected to the Raspberry Pi's GPIO pins. You will also need to have Node.js and npm (Node Package Manager) installed on your Raspberry Pi.

First, we will need to install the "onoff" package, which is a Node.js module that allows us to control the GPIO pins on the Raspberry Pi. Open the terminal on your Raspberry Pi and enter the following command:

Next, create a new file called "led.js" and open it in your favorite text editor. In this file, we will write the code to control the LED.

In this example, we are using the "onoff" module to access the GPIO pin 4, which is connected to the LED. The "writeSync" method sets the state of the pin to either "1" (on) or "0" (off). In this case, we are setting the pin to "1" to turn the LED on.

To run the script, use the following command in the terminal:

The LED should now be on. To turn the LED off, change the led.writeSync(1); to led.writeSync(0); and re-run the script.

This is just a basic example of how Node.js can be used to control the GPIO pins on a Raspberry Pi, you can use this as a starting point to build more complex projects.