Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use SerialPort Module in Node.js

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use the SerialPort module in Node.js". The content in the article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use the SerialPort module in Node.js".

Purpose

Serial port is often used to communicate between host computer and various circuit modules, and SerialPort module can be used to operate serial port in Node.js. This article will briefly explain its use.

Official website: https://serialport.io/

The current SerialPort module version is 9.2.7

Module installation

The SerialPort module can be installed using the following command:

Npm install serialport

Some of the functions of the SerialPort module are implemented in Champact +, so different platforms need the binaries available on the platform to run, and there are usually precompiled binaries for common platforms. If not, you will usually try to compile using node-gyp (relying on Python 3.x), and usually the package manager will automatically handle the related transactions:

Sometimes or some platforms may need to be compiled manually.

After installing the compilation tool, you can reinstall the SerialPort module or compile it manually.

Basic use

After installing the SerialPort module, you can import it using the const SerialPort = require ('serialport') mode.

Scan port

Use the SerialPort.list (): Promise static method to get a list of serial ports on the device, such as the following demonstration:

Const SerialPort = require ('serialport'); SerialPort.list () .then ((ports) = > {console.log (ports); / / print serial port list}) .catch ((err) = > {console.log (err);})

It is important to note that the same port may be repeated in this list.

You can also use the above method in async / await mode:

Const SerialPort = require ('serialport'); (async () = > {try {let ports = await SerialPort.list (); console.log (ports); / / print serial port list} catch (error) {console.log (error);}}) ()

Open the port

Creating a SerialPort object opens the port by default, such as the following:

Const SerialPort = require ('serialport'); const port = new SerialPort (' COM6', (err) = > {if (err) {console.log ('port opening failed!') ; return;} console.log ('Port opened successfully!') ;})

There is an autoOpen option in the constructor of the SerialPort class to control whether the created object opens the port automatically, which is automatically opened by default, or you can turn it off so that you can manually open the port later:

Const SerialPort = require ('serialport'); const port = new SerialPort (' COM6', {autoOpen: false}); port.open (function (err) {if (err) {console.log ('port opening failed!') ; return;} console.log ('Port opened successfully!') ;})

You can use the baudRate option to set the serial communication baud rate in the constructor of the SerialPort class. The default is 9600:

Const SerialPort = require ('serialport'); const port = new SerialPort (' COM6', {baudRate: 115200}); / / set baud rate to 115200

For more information, please refer to the constructor description of the SerialPort class in the following section.

Send data

You can send data using the write method of the SerialPort object, which puts the data to be sent into the send cache and then sends it in turn, such as the following:

Const SerialPort = require ('serialport'); const port = new SerialPort (' COM6'); port.write ('Hello world!\ n'); / / send string port.write (Buffer.from ('Hey!\ n')); / / send Buffer data port.write (new Uint8Array ([0x48, 0x69, 0x21, 0x0A])); / / send byte array

The write method can also add a callback function:

Const SerialPort = require ('serialport'); const port = new SerialPort (' COM6'); port.write ('Hello world!\ n operations, (err) = > {if (err) {console.log (' write operation failed!') ; return;} console.log ('write operation succeeded!') ;})

It should be noted that when the above callback function is triggered in a non-abnormal state, it only means that the operation of the write method itself is completed, and it does not mean that the data is completely sent from the port. It can be processed by using the drain method, which will block until the sending is completed:

Const SerialPort = require ('serialport'); const port = new SerialPort (' COM6'); port.write ('Hello world!\ n'); port.drain (err = > {if (err) return; console.log ('send complete!') ;}); receive data

You can receive data in the following ways:

Const SerialPort = require ('serialport'); const port = new SerialPort (' COM6'); / / listen for received data with paused mode, you need to actively read data port.on ('readable', () = > {console.log (port.read ()); / / use read method to read data, you can specify the number of bytes to read}); / / listen for received data port.on with flowing mode (' data', (data) = > {console.log (data)) });

In addition to the above, you can also use pipe to transfer data to another stream.

Error handling

Most operations of the SerialPort object have a callback function, and the first parameter in the callback function is the exception object. You can also handle exceptions uniformly through the error event:

Const SerialPort = require ('serialport'); const port = new SerialPort (' COM6'); port.on ('error', err = > {console.log (err);}); data parser

Some data parsers are prepared in the SerialPort module, which are mainly used to process some common forms of serial data received. The main functions are as follows:

ByteLength Parser

Parse in terms of the length of the data received:

Const SerialPort = require ('serialport'); const port = new SerialPort (' COM6'); const ByteLength = require ('@ serialport/parser-byte-length'); const parser = port.pipe (new ByteLength ({length: 8})); / / trigger parser.on every 8 bytes received ('data', chunk = > {console.log (chunk); / / print received data})

CcTalk Parser

Parsing data in ccTalk format

Process data with specified characters as bounds:

Const SerialPort = require ('serialport'); const port = new SerialPort (' COM6'); const Delimiter = require ('@ serialport/parser-delimiter'); const parser = port.pipe (new Delimiter ({delimiter:'\ n'})); / / processing data parser.on separated by\ n ('data', chunk = > {console.log (chunk.toString ()); / / print received data})

The delimiter option can be string | Buffer | number []; the includeDelimiter option indicates whether a delimiter is included in the data, which is not included by default.

InterByteTimeout Parser

No data was received at the specified time to trigger resolution:

Const SerialPort = require ('serialport'); const port = new SerialPort (' COM6'); const InterByteTimeout = require ('@ serialport/parser-inter-byte-timeout'); const parser = port.pipe (new InterByteTimeout ({interval: 2000})); / / trigger parser.on ('data', chunk = > {console.log (chunk); / / print received data}) in 2000 milliseconds

The maxBufferSize option specifies that the action will be triggered even if there is no timeout after that amount of data is received.

Readline Parser

The data is parsed in behavioral units, and the default line delimiter is\ n, which can be reset to something else using the delimiter option, such as\ r\ n.

Ready Parser

Parse with the start flag.

Regex Parser

Parsing is separated by regular expressions.

SerialPort class

To use SerialPort module is mainly to use SerialPort class.

Construction method

New SerialPort (path [, openOptions] [, openCallback])

The constructor is used to create a serial port object. Path is the serial number and openCallback is the callback function when automatic opening fails.

The common options for openOptions are as follows:

Option type description default value autoOpenboolean automatic open port truebaudRatenumber baud rate 9600dataBitsnumber data bit. Available values: 8, 7, 6, 58highWaterMarknumber read and write cache size 65536lockboolean lock port to prevent other platforms from opening (false is not supported on Windows) truestopBitsnumber stop bit, optional values: 1, 21paritystring check, optional values: none, even, mark, odd, spacenonertsctsboolean flow control settings falsexonboolean flow control settings falsexoffboolean flow control settings falsexanyboolean flow control settings false property

SerialPort has the following properties to read:

Path 、 baudRate 、 isOpen 、 binding

Event

The following events are triggered by SerialPort:

Triggered when the open port is open

Triggered when error sends an error

Triggered when the close port is shut down

Triggered when data receives data

Drain if the write method returns false, the event will be triggered when the write method is called again

Method

Some of the methods available for SerialPort are as follows:

Open (() = > {}): void opens the port

Update (options: updateOptions, callback?: err = > {}): void changes the baud rate

Write (data: string | Buffer | Array, encoding?: string, callback?: error = > {}): boolean sends data

Read (size?: number): string | Buffer | null reads data

Close (callback?: error = > {}): void shuts down the port

Set (options: setOptions, callback?: error = > {}): void sets flow control

Get (callback: (error, data: ModemStatus) = > {}): void gets the flow control status of the open port

Flush (callback? Error = > {}): void clears unprocessed data in the receive and send caches

Drain (callback? Error = > {}): void waits for the data to be sent

Pause (): this pauses flowing mode triggers data event and changes to paused mode

Resume (): this resumes the data event, from paused mode to flowing mode

Command line tool

The SerialPort module also provides command-line tools for direct use in the command-line interface. The following is a demonstration of the home page of the official website:

Thank you for reading, the above is the content of "how to use the SerialPort module in Node.js". After the study of this article, I believe you have a deeper understanding of how to use the SerialPort module in Node.js, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report