Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 9 ■ IOT PATTERNS: LOCATION AWARE


Code (Arduino)


The final component of this project is the Arduino code for connecting to the Internet
using WiFi, getting the current GPS coordinates, and publishing them to a server.
Start your Arduino IDE and either type the code provided here or download it from
the site and open it. All the code goes into a single source file ( *.ino ), but in order to
make it easy to understand and reuse, it has been divided into five sections.



  • External libraries

  • Internet connectivity (WiFi)

  • Read GPS coordinates

  • HTTP (publish)

  • Standard functions


External Libraries


The first section of code, as provided in Listing 9-5 , includes all the external libraries
required to run the code. This sketch has multiple dependencies—for Internet
connectivity, you need to include the <WiFi.h> , for communication with the GPS module,
you need to include <SoftwareSerial.h> , and for reading the GPS coordinates, you need
to include <TinyGPS.h>. You can download <TinyGPS.h> from https://github.com/
mikalhart/TinyGPS/releases/tag/v13.


Listing 9-5. Code for Including External Dependencies


#include <SPI.h>
#include <WiFi.h>
#include <TinyGPS.h>
#include <SoftwareSerial.h>


Internet Connectivity (Wireless)


The second section of the code defines the variables, constants, and functions that are
going to be used for connecting to the Internet. Use the code from Listings 2-7, 2-8 ,
and 2-9 (Chapter 2 ) here.


Get GPS Coordinates


The third section of the code, as provided in Listing 9-6 , defines the variables, constants,
and functions that are going to be used for reading the GPS coordinates.
Once the GPS module is connected to Arduino and it is powered on, it will look for
a satellite and start sending data on serial ports D2 and D3 to Arduino. This data won’t
make much sense, so in order to find the latitude and longitude information, you will use

Free download pdf