Writing A Serialdevice Class - Arduino Uno Quick Start Manual

Hide thumbs Also See for Arduino Uno:
Table of Contents

Advertisement

function
arrayBufferToString(buf) {
var
bufView =
new
Uint8Array(buf);
var
encodedString = String.fromCharCode.apply(null, bufView);
return
decodeURIComponent(escape(encodedString));
};
Although this function comprises only a few statements, it s very complex. It
expects an
ArrayBuffer
object containing data encoded in UTF-8. That s why it
creates a
Uint8Array
object first. An
memory, and using view classes like
memory chunk should be interpreted. In our case, we want to interpret the
data we ve received as characters encoded in UTF-8.
JavaScript strings are usually encoded in UTF-16, so the next two statements
convert the UTF-8 data we ve received into a UTF-16 string. They use the
function
arrayBufferToString
var
listener = function(r) { console.log(arrayBufferToString(r.data)); }
chrome.serial.onReceive.addListener(listener)
This listener outputs the data received from the Arduino in a readable manner.
Note that you ll see a lot of unexpected line breaks because the serial API
doesn t look for newline characters. Whenever it receives a chunk of data, it
hands the chunk over to the listener. It s the application s responsibility to
interpret the data, and you ll learn how to do this in the next section.
You ve learned how to create your own Chrome apps and how to talk to serial
devices on the JavaScript console. But one of the great things about JavaScript
and Chrome apps is that you can tinker so easily with APIs in the browser.

Writing a SerialDevice Class

Playing with a new library in an interactive environment is a great way to
learn. Still, you eventually have to come up with some proper JavaScript code
that you can actually use in your project.
JavaScript supports object-oriented programming, so it seems logical to put
all code related to accessing the serial port into its own class. This way, you
can reuse it in other projects, and if you have to fix bugs or improve the code,
you have to do it only in one place. In addition, chances are good that there
will be a cross-browser solution for accessing the serial port soon.
happens, you can replace the innards of your class with the new standard
7.
At
http://ecmanaut.blogspot.de/2006/07/encoding-decoding-utf8-in-javascript.html
explanation of this function. It s not for the faint of heart!
8.
http://whatwg.github.io/serial/
Appendix 4. Controlling the Arduino with a Browser
ArrayBuffer
represents an arbitrary chunk of
Uint8Array
to turn
ArrayBuffer
objects into JavaScript strings.
www.it-ebooks.info
, you can specify how the
8
When this
, you can find a detailed
274
7
report erratum
discuss

Hide quick links:

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the Arduino Uno and is the answer not in the manual?

Subscribe to Our Youtube Channel

Table of Contents