Hardware Reference
In-Depth Information
}
int
getHours
()
{
//
char
output
[
5
];
//
FILE
*
fp
;
fp
=
popen
(
"curl http://nextmakemagazine.appspot.com/simple"
,
"r"
);
//
if
(
fp
==
NULL
)
{
//
Serial
.
println
(
"Couldn't run the curl command."
);
return
-
1
;
}
else
{
fgets
(
output
,
sizeof
(
output
),
fp
);
}
if
(
pclose
(
fp
)
!=
0
)
{
//
Serial
.
println
(
"The curl command returned an error."
);
return
-
1
;
}
return
atoi
(
output
);
//
}
Call the function
getHours()
and print its result.
getHours()
is defined
below.
Create a new function called
getHours
that will return an integer.
Create an array of characters called
output
for storing the response.
Create a
file pointer
called
fp
, which is how our code will reference
the output of the Linux command.
Use the Linux
curl
command to fetch the number of hours and store
it in
fp
.
If there was a problem running
curl
, report the error in the serial
monitor and have the
getHours()
function return -1.
Otherwise, read the data in
fp
and put it into the
output
array.
If
curl
had a problem getting the data (for instance, if the server is
not available), report the error in the serial monitor and have the
getHours()
function return -1.
Have the function return the contents of the array as an integer using
the built-in
atoi
(ASCII character array/string to integer) function.
Defining Functions
The first thing you might notice in
Example 6-3
is that the
loop
function has
only two lines of code. The
delay(5000)
ensures that each iteration of the
loop happens only every five seconds. But what about
Serial.println(getHours());
? The innermost function,
getHours()
, is ac-
tually defined right below the loop function.