for the user interface, such as the screen width, the screen height, and the
font size.
After that, we define a few member variables.
_arduinoPort
contains a reference
to the
Serial
object we use to communicate with the Arduino.
_temperature
con-
tains the last temperature value we received from the Arduino, and
_isCelsius
is true if the value we read was in degrees Celsius. We need the
_font
variable
to define the font we use to output the temperature on the screen.
In the
setup
method, we set the window size and create the font we’re going to
use. Then we print out a list of all serial devices available. We initialize our
_arduinoPort
variable with the first one we find, hoping that it’s the Arduino.
You could also loop through the list automatically and search for something
that looks like an Arduino port name, but that’d be fragile, too.
We call the
clear
method to empty the serial port’s buffer. With
bufferUntil
, we
make sure that we get notified about serial events only when we’ve received
a linefeed character. The call to
readStringUntil
ensures that we start with a fresh
serial buffer that doesn’t contain an incomplete line of data.
The
draw
method prints the last temperature
we received on the screen. It sets the back-
ground color to white using
background
and the
text color to black using
fill
. Then it sets the
font and ensures the text we are printing is
centered horizontally and vertically. Eventually, we print the temperature
using the
text
method. To make the result look nicer, we use the official Uni-
code characters for degrees Celsius (
\u2103
) and Fahrenheit (
\u2109
).
Now let’s implement the business logic of our “Take me to the beach” alarm:
Ethernet/TweetTemperature/TweetTemperature.pde
void serialEvent(Serial port) {
final String arduinoData = port.readStringUntil(LINE_FEED);
if (arduinoData != null) {
final String[] data = split(trim(arduinoData), ' ');
if (data.length == 2 &&
(data[1].equals("C") || data[1].equals("F")))
{
_isCelsius = data[1].equals("C");
_temperature = float(data[0]);
if (Float.isNaN(_temperature))
return;
println(_temperature);
int sleepTime = 5 * 60 * 1000;
if (_temperature > MAX_WORKING_TEMP) {
tweetAlarm();
Chapter 10. Networking with Arduino • 170
report erratum • discuss
www.it-ebooks.info