Hardware Reference
In-Depth Information
#
vi json-parse.py
3. Type the letter i to enter insert mode. An āIā will appear in the lower left
hand corner of your screen.
4. Edit the file so that it reflects the code in
Example 6-6
.
5. In the Arduino IDE, create a new sketch with the code from
Example 6-7
. You'll see that it's very similar to
Example 6-3
. Instead of
calling
curl
from the command line, it uses Python to run the script you
wrote from
Example 6-6
.
6. Upload the code to the board.
Example 6-6. Using Python to parse JSON
import
json
import
urllib2
httpResponse
=
urllib2
.
urlopen
(
'http://nextmakemagazine.appspot.com/json'
)
jsonString
=
httpResponse
.
read
()
jsonData
=
json
.
loads
(
jsonString
)
print
jsonData
[
'daysAway'
]
#
Print only the number of days until the next MAKE will come out from
the JSON response.
Example 6-7. Calling Python from Arduino code
void
setup
()
{
Serial
.
begin
(
9600
);
}
void
loop
()
{
Serial
.
println
(
getDays
());
delay
(
5000
);
}
int
getDays
()
{
char
output
[
5
];
FILE
*
fp
;
fp
=
popen
(
"python /home/root/json-parse.py"
,
"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."
);