ChromeApps/SerialDevice/main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Serial Device Demo</title>
</head>
<body>
<div id="main">
<p>The Arduino sends:</p>
<p id="output"></p>
</div>
<script src="js/serial_device.js"></script>
<script src="js/arduino.js"></script>
</body>
</html>
In the HTML page, you’ll find a paragraph element with its
id
attribute set to
output
. That’s the element we’ll fill with the data we read from the serial port.
At the end of the document, we include our new JavaScript library for
accessing the serial device. Also, we include a file named
arduino.js
:
ChromeApps/SerialDevice/js/arduino.js
var arduino = new SerialDevice('/dev/tty.usbmodem24311');
arduino.onConnect.addListener(function() {
console.log('Connected to: ' + arduino.path);
});
arduino.onReadLine.addListener(function(line) {
console.log('Read line: ' + line);
document.getElementById('output').innerText = line;
});
arduino.connect();
Here we create a new
SerialDevice
object named
arduino
. Then we add listener
functions for the
onConnect
and
onReadLine
events. Both write a message to the
console. The
onReadLine
listener puts the line it has read into the browser’s
Document Object Model (DOM).
Make sure you use the correct serial port in the first line of
arduino.js
. Then
connect your Arduino to your computer and upload a sketch that permanently
outputs lines of text on the serial port. You can use the sketch from Building
Your Own Game Controller, on page 106. Start the Chrome app, and you should
see something like the following figure:
report erratum • discuss
Writing a SerialDevice Class • 279
www.it-ebooks.info