if
(this.connectionId < 0) {
throw
"No serial device
}
chrome.serial.send(
this.connectionId,
this.stringToArrayBuffer(data),
function() {});
};
onReceive
basically works like the sample listener we implemented in
the Chrome Serial API, on page
mentation looks for newline characters. Whenever it finds one, it passes the
current read buffer to the function that is listening for
that more than one line can be transmitted in a single data chunk. Also note
that
onReceive
checks whether it got data from the correct serial port.
The
onReceiveError
method also makes sure first that it got error information
for the correct connection. In this case, it dispatches the event to the function
that is listening for
onError
For our purposes we don t need a
for the sake of completeness. This way, you have a
can use in many more projects.
Finally, we need our two helper methods for converting
strings and vice versa:
ChromeApps/SerialDevice/js/serial_device.js
SerialDevice.prototype.arrayBufferToString = function(buf) {
var
bufView =
new
Uint8Array(buf);
var
encodedString = String.fromCharCode.apply(null, bufView);
return
decodeURIComponent(escape(encodedString));
};
SerialDevice.prototype.stringToArrayBuffer = function(str) {
var
encodedString = unescape(encodeURIComponent(str));
var
bytes =
new
Uint8Array(encodedString.length);
for (var
i = 0; i < encodedString.length; ++i) {
bytes[i] = encodedString.charCodeAt(i);
}
return
bytes.buffer;
};
That s it! We now have a generic class for communicating with serial devices
from a Chrome app. Let s use it right away and write a small demo application.
This demo will be the simplest serial monitor possible. It will permanently
read data from a serial port and display it in an HTML page. The HTML page
looks as follows:
Appendix 4. Controlling the Arduino with a Browser
connected.";
271. The only difference is that the new imple-
events.
send
method, but it doesn t hurt to add it
www.it-ebooks.info
Exploring
onReadLine
events. Note
SerialDevice
class that you
ArrayBuffer
objects into
278
report erratum
discuss
Need help?
Do you have a question about the Arduino Uno and is the answer not in the manual?