110

下面的代码使用 SerialPort 模块来监听来自蓝牙连接的数据。

我期待在控制台中看到以十六进制格式打印的数据流。但是控制台只显示了一些奇怪的符号。我想知道如何在控制台中解码和显示数据。

var serialPort = new SerialPort("/dev/tty.EV3-SerialPort", {
  parser: SP.parsers.raw
}, false); // this is the openImmediately flag [default is true]

serialPort.open(function () {
 console.log('open');
 serialPort.on('data', function(data) {
   var buff = new Buffer(data, 'utf8'); //no sure about this
  console.log('data received: ' + buff.toString());
 });  
});
4

2 回答 2

247

此代码将数据缓冲区显示为十六进制字符串:

buff.toString('hex');
于 2014-07-01T07:01:21.637 回答
0

最佳答案是最简单的方法。

另一种方法:

data = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);

Array.prototype.map.call(new Uint8Array(data),
               x => ('00' + x.toString(16)).slice(-2))
        .join('').match(/[a-fA-F0-9]{2}/g).reverse().join('');
于 2017-07-25T19:45:31.930 回答