【发布时间】:2013-11-15 17:11:07
【问题描述】:
我正在开发一个通过串行与 Arduino UNO 通信的 Google Chrome 扩展程序。我编写了以下函数sendSerialCmd,它接受一个端口(字符串)、一个serial_cmd(ArrayBuffer)和一个回调函数,该函数从串行连接中读取到readInfo.data(一个ArrayBuffer)。
var CONNECTION_ID = -1;
var sendSerialCmd = function(port, serial_cmd, callback) {
chrome.serial.open(port, null, function(openInfo){
CONNECTION_ID = openInfo.connectionId;
if (CONNECTION_ID == -1) {
console.log('Could not connect to serial');
return;
}
chrome.serial.write(CONNECTION_ID, serial_cmd, function(writeInfo){
chrome.serial.read(CONNECTION_ID, 8, function(readInfo){
callback(readInfo.data);
});
})
});
chrome.serial.close(CONNECTION_ID, function(result){ console.log(result) });
};
我遇到的一个问题是传递给chrome.serial.read() 函数的第三个参数。在chrome.serial API 中,第三个参数是 bytesToRead ( integer ): 要读取的字节数,但是,从我的 Arduino 传入的字节数可能会发生变化。有时我可能会得到 8 个字节,有时会更多。从我的 Arduino 发回所有字节的最佳方法是什么?
Arduino 通过一个名为Serial.available() 的函数提供了一种新颖的解决方案,该函数返回可供读取的字节数。我可以用 Chrome.serial API 做类似的事情吗?
【问题讨论】:
标签: javascript serial-port arduino google-chrome-app