简体   繁体   中英

Send byte (0xFF) with Node.js through SerialPort

I send command with an ending byte, it's : 0xFF three times. In python, this code is working :

import time
import serial

ser = serial.Serial(
  port='/dev/ttyAMA0',
  baudrate = 9600,
  parity=serial.PARITY_NONE,
  stopbits=serial.STOPBITS_ONE,
  bytesize=serial.EIGHTBITS,
  timeout=1
)

while 1:
  EndCom = "\xff\xff\xff"
  ser.write('page 1'+EndCom)
  print EndCom
  time.sleep(1)

The same code in Node.js doesn't working :

var serialport = require('serialport');
var SerialPort = serialport.SerialPort;

var port = new SerialPort('/dev/ttyAMA0', {
  baudrate: 9600
});

port.on('open', function() {
  console.log('Port ouvert sur /dev/ttyAMA0 @ 9600 bds');

  var end = "\xff\xff\xff";
  port.write("page 1"+end);
});

port.on('data', function(byte) {
  console.log("Data :", byte.toString('hex').match(/.{1,2}/g).join(" "));
});

I use this to control a Nextion Screen that is work with SerialPort. With Python i receive "page 1 " with 3 spaces, with Node.js i receive this : "page 1ÿÿÿ".

I don't know why, there isn't any difference to me.

Thanks for the help !

The answer is : I need to use a buffer to send byte with Node.js

This is my function :

function hex(str) {
        var arr = [];
        for (var i = 0, l = str.length; i < l; i ++) {
                var ascii = str.charCodeAt(i);
                arr.push(ascii);
        }
        arr.push(255);
        arr.push(255);
        arr.push(255);
        return new Buffer(arr);
}

I use the function like that :

port.write(hex("page 1"));

The function returns something like that :

<Buffer 70 61 67 65 20 31 ff ff ff>

Hope this code will help someone ! Bye

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM