-
function updateUI(temperature, distance) {
-
document.getElementById("temperature").innerText = temperature;
-
for (var i = 1; i < 9; i++) {
30
var index = "d" + i;
-
if (distance <= lights[index][0])
-
document.getElementById(index).style.color = lights[index][1];
-
else
-
document.getElementById(index).style.color = "white";
35
}
-
}
-
-
arduino.connect();
-
To read the sensor data from the Arduino, we use the
SerialDevice
class we’ve
defined in Writing a SerialDevice Class, on page 274. We create a new instance
named
arduino
in the first line. Make sure you’re using the right serial port
path.
Then we define an
onConnect
handler that prints a message to the browser’s
JavaScript console as soon as the application has connected to an Arduino.
In principle, you don’t need the
onConnect
handler. In this case, it’s mostly
useful for debugging purposes.
Things get more interesting in the
onReadLine
handler. In line 9, we split the
data we’ve received from the Arduino. We make sure that we’ve actually
received two values. In this case we turn both values into numbers using
parseInt
, and we also divide them by 100 because the Arduino sends values
that have been multiplied by 100 before. In line 11, we use a popular Java-
Script trick to round the temperature value to one decimal digit. After we’ve
turned both the distance and the temperature into proper numbers, we pass
them to
updateUI
.
updateUI
sets the new temperature value first in line 29. To do this, it looks up
the HTML element having the ID
temperature
using the
getElementById
function.
Then it sets the element’s
innerText
property to the current temperature.
Updating the artificial LED display is a bit more complex, but not too difficult.
We’ve defined a data structure named
lights
that maps the IDs of our display’s
<span>
elements to arrays having two elements each. For example, it maps
the ID
d1
to an array containing the values 35.0 and “orange”. That means
that the color of the element having the ID
d1
will be set to orange when the
distance to the next object is less than or equal 35.0 centimeters.
Using the
lights
data structure, it’s easy to implement the LED display. In line
30, we start a loop iterating over all LEDs. We determine the current LED’s
Chapter 5. Sensing the World Around Us • 96
report erratum • discuss
www.it-ebooks.info