Connecting a serial port to the WEB via Node.js

A previous post (here) documented how to connect a Python script to a serial port on a microcontroller.  This post documents connecting a serial port to the WEB via Node.js (which is a JavaScript runtime).

Using Node.js and a module for node called serialport, it is very easy to connect a PC to a serial port on a microcontroller.   First install Node.js  (and npm which is the node package manager). Then install the serial port package via:

npm install serialport

NODE.JS to Console Javascript code

Save the following code as serial_port_console.js:

and run it via:

node serial_port_console.js

This is a very simple means to communicate with your serial device just from the console. Data received from the serial device is sent to the console and data typed in on the console is sent to the serial device. Note that the serial port on the PC is hard coded as “/dev/ttyUSB0” and the baud rate is 115200 which should be changed by editing the code to match the connected device.

NODE.JS to WEB Javascript code

Alternatively, use this script for connecting a serial port to the WEB via Node.js:

That script also requires an html file to send to the browser:

Save the Node.Js file as serial_port_web.js and the  html  file as index.html. This script also requires three other npm modules (fs for reading files,  express for the WEB interface and socket.io to maintain a WEB socket connection for the serial data flow).

Install them with:  npm install socket.io fs express

Make sure the microcontroller serial device is connected to the PC, then run the script via:

node serial_port_web.js

The serial_port_web.js script will search for the serial port and use what is found  at a baud rate of 115200 unless it is over ridden with optional parameters on the command line:

node serial_port_web.js  /dev/ttyUSB0 9600

The port is hard coded to 8888 but of course can be changed by editing the code.

When the script is running ,  copy/paste this URL in the browser:

http://localhost:8888

and this screen should appear:

Serial Port to WEB via Node.JsThe large top blue box is where the serial data will be displayed (and a time stamp added). The bottom blue box is where data can be typed to send to the serial device. Note that when Enter is pressed, Enter (or as it is called the Carriage Return or Newline character) is sent to the serial device.  Pressing the Send button (sends the typed in characters without sending Enter.) Depending on what (code) is running on the serial device, sometimes the Enter is needed and sometimes not.

There is a lot more code in the WEB example, than in the console example, however, the WEB example has more features and presents the data in a ‘prettier’ way. Using the WEB example also allows a remote connection to the serial device if the host computer is connected to the internet.

Leave a Reply

Your email address will not be published.