Node.js 串口通訊 node-serialport 使用說明


官網:https://serialport.io/en/

安裝:npm install serialport

Parsers說明:
parser-byte-length:
大概意思是定義了一個長度為length字節的buffer,串口收到數據后先放到buffer中,放滿了才發送給程序,超出的部分等buffer發送清空后繼續放入
parser-cctalk:
一種在貨幣交易等行業廣泛使用的串行協議
parser-delimiter:
意思是遇到某個字符時才把buffer中的數據發給程序,比如設為’a’,那么用字符發送時遇到’a’即發送,用hex發送時遇到61(‘a’的ASCII碼)時發送;注:官方例子中’\n’字符用串口工具字符發送沒生效,但用hex發送其ASCII碼(0A)和在node.js項目中可以生效
parser-readline:
可以自定義換行符,遇到換行符時發送,默認為’\r\n’,對應ASCII為0D 0A;但目前打hex日志時為亂碼
parser-ready:
程序先收到自定義字符串,例’READY’后才開始接收數據
parser-regex:
正則表達式
parser-slip-encoder:
沒弄清楚是什么意思,require模塊也報錯

例子:

var SerialPort = require('serialport');
var port = new SerialPort('COM5');

//發hex
var senddata = [0x01,0x02];
//發字符串
//senddata = 'test data';

function writeport()
{
    port.write(senddata, function (err) {
        if (err) {
            return console.log('Error on write: ', err.message);
        }
        console.log('send: ' + senddata);
    });
}

port.on('open', function () {
    writeport();
});

// open errors will be emitted as an error event
port.on('error', function (err) {
    console.log('Error: ', err.message);
})

setInterval(function () {
    writeport();
}, 5000);


port.on('data', function (data) {
    //收hex
    console.log('recv: ' + data.toString('hex'));
    //收字符串
    //console.log('recv: ' + data.toString('ascii'));
  });

注:版本不同可能使用方式不同,當前使用的版本是7.1.4

簡單例子地址:https://github.com/TLScottChen/node-serialport-example
官方文檔4.0.1地址:https://github.com/node-serialport/node-serialport/blob/4.0.1/README.md

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM