Menu

串口使用

const SerialPort = require('serialport')
const port = new SerialPort('/dev/tty-usbserial1', {
  baudRate: 57600
})

打开一个串口,按照如下顺序:

  1. 串口路径(必须)
  2. 选项(具体如下)

创建串口对象后会立即打开这个端口,可以对其进行读写操作(端口未开启时,读写操作将形成队列,在端口启用后依次进行)。大多数函数需要串口端口处于开启状态时才能使用,有三种方法可以进行检测:

  • The open event is always emitted when the port is opened.
  • 如果已开启 autoOpen 选项(默认开启)则构造函数将 openCallback 返回给 .open();若已关闭 autoOpen 则不会进行回调。
  • The .open() function takes a callback that is called after the port is opened. You can use this if you've disabled the autoOpen option or have previously closed an open port.
const SerialPort = require('serialport')
const port = new SerialPort('/dev/tty-usbserial1')

port.write('main screen turn on', function(err) {
  if (err) {
    return console.log('Error on write: ', err.message)
  }
  console.log('message written')
})

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

Detecting open-related errors can be moved to the constructor's callback.

const SerialPort = require('serialport')
const port = new SerialPort('/dev/tty-usbserial1', function (err) {
  if (err) {
    return console.log('Error: ', err.message)
  }
})

port.write('main screen turn on', function(err) {
  if (err) {
    return console.log('Error on write: ', err.message)
  }
  console.log('message written')
})

Auto Open

If you disable the autoOpen option, you'll need to open the port on your own.

const SerialPort = require('serialport')
const port = new SerialPort('/dev/tty-usbserial1', { autoOpen: false })

port.open(function (err) {
  if (err) {
    return console.log('Error opening port: ', err.message)
  }

  // Because there's no callback to write, write errors will be emitted on the port:
  port.write('main screen turn on')
})

// The open event is always emitted
port.on('open', function() {
  // open logic
})

Reading Data

Get updates about new data arriving through the serial port as follows:

// Read data that is available but keep the stream in "paused mode"
port.on('readable', function () {
  console.log('Data:', port.read())
})

// Switches the port into "flowing mode"
port.on('data', function (data) {
  console.log('Data:', data)
})

// Pipe the data into another stream (like a parser or standard out)
const lineStream = port.pipe(new Readline())

You can write to the serial port by sending a string or buffer to the write method:

port.write('Hi Mom!')
port.write(Buffer.from('Hi Mom!'))

Enjoy and do cool things with this code.

上一篇 下一篇
讨论数量: 0

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
刻意练习,每日精进。
~
点赞
191
浏览
0
讨论