I'm working on a Google Chrome extension that communicates with an Arduino UNO over serial. I wrote the following function sendSerialCmd
that takes a port (string), a serial_cmd (ArrayBuffer), and a callback function that gets passed readInfo.data (an ArrayBuffer) that is read in from the serial connection.
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) });
};
One of the problems I've run into is the third parameter passed to the chrome.serial.read()
function. In the chrome.serial API, the third parameter is the bytesToRead ( integer ): The number of bytes to read, however, the number of bytes coming in from my Arduino are subject to change. Sometimes I may get 8 bytes, other times more. What's the best way of getting all the bytes sent back from my Arduino?
Arduino has a novel solution through a function called Serial.available() which returns the number of bytes available to read. Is there something similar I can do with the Chrome.serial API?