Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Raspi Gpio Introduction in NodeJs

Raspi Gpio Introduction in NodeJs

Here's a beginner-friendly intro to using GPIO pins on a Raspberry Pi with Node.js β€” perfect if you want to control hardware like LEDs, buttons, sensors, and more using JavaScript! πŸš€


🧠 What is GPIO?

GPIO stands for General Purpose Input/Output.
Raspberry Pi’s GPIO pins allow you to send output (e.g. turn on an LED) or read input (e.g. check if a button is pressed).

GPIO Pin ExampleFunction
GPIO17 (pin 11)Digital Output
GPIO27 (pin 13)Digital Input


βœ… Node.js + GPIO = JavaScript Hardware Control

To interact with GPIO pins in Node.js, the most popular libraries are:

  • onoff – simple GPIO read/write

  • rpi-gpio – similar, slightly older

  • pigpio – for precise PWM, servo, ultrasonic sensors, etc.


βš™οΈ Basic Circuit Example

Let’s start with a basic setup:

Hardware:

  • LED connected to GPIO17 (Pin 11)

  • 330Ξ© resistor

  • GND (Pin 6)


πŸ“¦ Step 1: Install Dependencies

bash

npm init -ynpm install onoff


πŸ’‘ Step 2: Blink an LED (GPIO Output)

js

const Gpio = require('onoff').Gpio;const led = new Gpio(17, 'out'); // GPIO17setInterval(() => { led.writeSync(led.readSync() ^ 1); // Toggle LED}, 500);// Cleanup on Ctrl+Cprocess.on('SIGINT', () => { led.writeSync(0); led.unexport(); console.log('LED turned off'); process.exit();});

Run with:

bash

sudo node led-blink.js


πŸ”˜ Step 3: Read a Button (GPIO Input)

Wire a push button to GPIO27 (Pin 13) and GND (Pin 6).

js

// button.jsconst Gpio = require('onoff').Gpio;const button = new Gpio(27, 'in', 'both');button.watch((err, value) => { if (err) throw err; console.log('Button state:', value);});process.on('SIGINT', () => { button.unexport(); console.log('Button program stopped'); process.exit();});


🧠 GPIO Modes

  • 'out' β†’ output (LEDs, relays, etc.)

  • 'in' β†’ input (buttons, switches, etc.)

  • 'both' β†’ detect rising and falling edges (good for buttons)


🚨 Safety Tips

  • Always use resistors to limit current.

  • Don’t connect high-voltage devices directly.

  • GPIO pins are 3.3V β€” sending 5V can damage your Pi.


🌟 What’s Next?

You can build cool stuff like:

  • LED chasers / flowing lights

  • Motion sensors

  • Web-controlled relays

  • Real-time dashboards with Express or Socket.io

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql