Raspberry pi NodeJS Webserver + WebSocket Control LED
This article show how to use raspberry pi to be NodeJS webserver and control LED via websocket.
What is WebSocket?
WebSocket enables bidirectional communication in real time over the web.
WebSocket can be run together with a normal HTTP server. You can click a button in a web browser, and enable a GPIO on your Raspberry Pi which turns on a light in your house. All in real time, and with communication going both ways!
System Diagram
Wiring Diagram
HardwareRaspberry Pi Board
LED
Push Button Switch
Resistor 100 - 470 Ohm ( for LED )
Resistor 1K - 50K Ohm ( for Pull-up switch )
This is my raspberry pi development board.
Software and Library
Check Node Version$ node -v
If you don't have node. Install Node first
curl -sL https://deb.nodesource.com/setup_10.x | sudo bash -
sudo apt-get install nodejs
Then install npm
Install From Source
curl https://www.npmjs.com/install.sh | sudo sh
or install linux package
sudo apt-get install npm
Install From Source
curl https://www.npmjs.com/install.sh | sudo sh
or install linux package
sudo apt-get install npm
check npm version
$ npm -v
Install the onoff Module
To interface with the GPIO on the Raspberry Pi using Node.js, we will use a Module called "onoff".
Install the onoff module using npm:
$ npm install onoff
Install socket.io for Node.js
To download and install newest version of socket.io, use the following command:
$ npm install socket.io --save
Source Code
Download on Github https://github.com/amphancm/RasberryPi_NodeJS_Control_LED
webserver.js
Public/index.html
Demo
Run Node.js Webserver
$ node webserver.js
Open on Web Browser on your Raspberry pi IP address and port 8080
Control on Checkbox on Web Browser or Push Button Switch on Raspberry pi Board.
End the program with
Ctrl+c
.
Reference
https://www.w3schools.com/nodejs/nodejs_raspberrypi.asp
My Website
email : info@softpowergroup.net ,amphancm@gmail.com Tel .+6681-6452400