Electronics · nodejs · raspberry pi

Raspberry PI3 NodeJS GPIO Control: rpi-gpio


I’ve covered this in several other articles as a side effect of getting those higher level goals complete.  But given a simple Google Search failed me…  here is this in case someone else needs it.

When you just want: “Raspberry PI3 NodeJS GPIO Control” – this is how you get it done:

npm install --save rpi-gpio

Then the code.  Note the key piece for the Raspberry PI 3 is this:


Blink NodeJS & rpi-gpio style:

Finally the whole code.  All this does is toggle pin 16. 🙂

var gpio = require('rpi-gpio');

var lampPin = 16;
function pinBlink() {
 gpio.write(lampPin, false, (err) => {
   if (err) {
     console.log("Error in setting gpio pin.",err);
   setTimeout(() => {
     gpio.write(lampPin, true, (err) => {
       if (err) {
         console.log("Error in setting gpio pin.",err);
   }, 1000);

gpio.setup(lampPin, gpio.DIR_OUT, () => {
 setInterval(pinBlink, 2000);

Listening to a button state change (a.k.a. Button press)

Sometimes you just want to process a button press.  This is the code for that.  Note that you can change the transition you listen to with the last param:

var switchPin = 21;
gpio.setup(switchPin, gpio.DIR_IN, gpio.EDGE_FALLING);
gpio.on('change', function(channel, value) {
  //do something on the change.

Handy Pin Ref


Make sure you run as ROOT!

The GPIOs are worked with through the filesystem.  Your code can only reach those files if you run as root.

Channels/Pins you can’t use:

  • 1
  • 2
  • 4
  • 6
  • 9
  • 14
  • 17
  • 20
  • 25
  • 27
  • 28
  • 30
  • 34
  • 39

The above list is all reserved for something else… or ground, or 5V, or 3.3V… you get it. 🙂


Now, hopefully, my future internet search friends will have a chance. 😉


3 thoughts on “Raspberry PI3 NodeJS GPIO Control: rpi-gpio

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.