SlideShare a Scribd company logo
1 of 55
Download to read offline
School of Electrical Engineering Systems
Final Year Project, 2016
Candidate Name: Daniel Murray
Student Number: C12314206
Project Title: Asset Tracking Using a Radio Network
Bachelor of Engineering Technology:
Electrical and Control Engineering (DT009)
i
Declaration:
I declare that all work detailed within this report is entirely my own work, other than that which is
otherwise referenced. This report and all work therein have not been previously submitted either in
full or in part for academic accreditation; degree or award, in any other college or university. I now
submit this report for assessment for my Final Year Project in the course DT009. All research
conducted as been appropriately referenced using IEEE referencing.
Signed:______________________________
Date:________________________________
ii
Acknowledgements:
I would thank the following people for their help and support.
My supervisor Michael Core, who fully supported the path that I wished to follow for this project.
You always had great suggestions that made me develop my plans and were always able to explain
things clearly. I enjoyed our meetings and the ideas and plans that were developed therein.
My landlord Paul Byrne, for putting up with me coming in at all hours of the night and for showing
a huge interest in my project.
My upperclassman Glen Byrne, for first making me realise that this project was possible and giving
me advice at the start of my project.
My LoRa provider Forbe from AppconWireless, who provided prompt and detailed support any
time I had any questions. You are a credit to your work.
My classmates from DT009, who rallied together and helped each other along and made a range of
many diverse projects seem like one big team effort.
My mother and father, Siobhán and Macartan Murray, without whom I wouldn’t have clean clothes,
free food or a place to sleep. You gave me a good rural upbringing, which brought about the
inspiration for this project.
My girlfriend Judy Walsh, who has listened to endless tirades, put up with me when I’m at my worst
and provided endless support, advice and understanding throughout the year. I only hope I can do
the same for you when it is your turn.
iii
Abstract:
The original inspiration for this project came from a desire to reduce the time spent performing
menial tasks on a farm and to grasp a greater understanding of how information is transferred
wirelessly. This project aims to make the process of monitoring cattle more time efficient and less
labour intensive by creating an asset tracking system using a radio network. The cost associated
with this project is suitable for small budget applications and the long range offered by the system
ensures its practicality.
This system actively tracks the whereabouts of a number of tracking units. Using GPS modules and
a LoRa radio network, the tracking units have the ability to determine their locations and broadcast
them using radio waves. The Arduino Nano ATMega328 was selected as the controller on the
tracking unit and the AppconWireless RF1276 was used to establish the LoRa Network. A Central
Gateway, a Raspberry Pi 2 Model B, wirelessly poles for location information from the tracking
units using the LoRa Network. This gateway stores the location history, time and date of the reading
and the state of battery on each of the remote nodes. The location information is placed in both an
online and offline database. The most recent values are presented on a web page where all of the
nodes can be viewed on an embedded Google Map. The web page is accessible from a remote
network, such that the operator can access the system when on the go.
iv
Table of Contents:
DECLARATION: ...................................................................................................................................................... I
ABSTRACT: ........................................................................................................................................................... II
TABLE OF CONTENTS:........................................................................................................................................... III
TABLE OF TABLES:................................................................................................................................................IV
TABLE OF FIGURES:..............................................................................................................................................IV
CHAPTER 1: INTRODUCTION: ................................................................................................................................ 1
CHAPTER 2: BACKGROUND RESEARCH: ................................................................................................................. 4
CHAPTER 3: DESIGN OF SYSTEM & IMPLEMENTATION:........................................................................................ 11
CHAPTER 4: TESTING AND RESULTS:.................................................................................................................... 19
CHAPTER 5: CONCLUSIONS & EVALUATION:........................................................................................................ 24
REFERENCES: ................................................................................................................................................... 28
APPENDICES: ...................................................................................................................................................... 30
Table of Tables:
Table 1 Costs involved.....................................................................................................................11
Table 2 Terminal Window installation prompts ..............................................................................13
Table 3 Voltmeter vs. Arduino voltage readings .............................................................................20
Table 4 Test 2 Results......................................................................................................................21
Table of Figures:
Figure 1 Proposed System Block Diagram........................................................................................1
Figure 2 Proposed Testing area..........................................................................................................2
Figure 3 WIFI Logo...........................................................................................................................4
Figure 4 Bluetooth logo .....................................................................................................................5
Figure 5 Zigbee Logo.........................................................................................................................6
Figure 6 AppconWireless RF1276.....................................................................................................6
Figure 7 NEO-6M-001 GPS Module.................................................................................................7
Figure 8 Raspberry Pi logo and Raspberry Pi 2 Model B..................................................................8
Figure 9 Microchip Logo and dsPIC30F4011 ...................................................................................8
Figure 10 TI logo and MSP430g2553................................................................................................9
Figure 11 Arduino Logo and Arduino Nano......................................................................................9
v
Figure 12 Gantt chart Overview.......................................................................................................11
Figure 13 Original Block Diagram of System .................................................................................12
Figure 14 Sparkfun Level Translator Breakout- PCA9306 .............................................................13
Figure 15 PL2303 to RF1276 and RF tool for RF1276...................................................................16
Figure 16 FileZilla window..............................................................................................................16
Figure 17 Online Web Page.............................................................................................................17
Figure 18 Wiring Diagram...............................................................................................................18
Figure 19 Final Block Diagram .......................................................................................................19
Figure 20 Voltmeter vs. Arduino voltage readings..........................................................................20
Figure 21 Arduino Nano Voltage Regulator....................................................................................20
Figure 22 Test 2 wiring diagram......................................................................................................21
Figure 23 Gateway node with battery pack and WiFi Dongle.........................................................23
Figure 24 Example string of information received by gateway node..............................................23
Figure 25 Operator carrying Remote node ......................................................................................23
Figure 26 Screenshot 1.....................................................................................................................24
Figure 27 Gateway node on ground.................................................................................................24
Figure 28 Screenshot 2.....................................................................................................................24
Figure 29 Screenshot 3.....................................................................................................................24
Figure 30 Screenshot 4.....................................................................................................................24
Figure 31 Screenshot 5.....................................................................................................................24
Figure 32 MQTT block diagram......................................................................................................27
Figure 33 Complete Gantt Chart......................................................................................................33
1
Chapter 1: Introduction:
The goal of this project is to design a system for tracking the location of a herd of cattle and to
contribute to the field of “Smart Agriculture”. The network will consist of remote nodes which will
interact with a base station. The remote nodes will gather GPS information and use a radio network
to allow transmission of data. From the base station, information gathered will be uploaded to The
Cloud where the information can be accessed on an external network. The block diagram shown in
Figure 1 outlines the operation of the system.
Figure 1 Proposed System Block Diagram
The benefits of such a project include:
 A low cost network suitable for small budget applications.
 The improved reaction to instances of cattle theft.
 The detection of an animal that has broken out of its enclosure.
 The expansion to the tracking of general assets.
Being able to know exactly when a raid is occurring can allow immediate notification of the theft
to the Gardaí and the farmer. Not only would this help reduce number of cattle thefts but will also
help in the day to day monitoring of cattle and will also let the farmer know if a beast attempts to
break out of its field or enclosure.
Rural Ireland has recently seen an increase in the number of cattle thefts. One of the main issues
with preventing cattle theft is the difficulty in knowing when the theft occurs and the delay in the
reaction of An Garda Siochána to such thefts. This project offers an opportunity for the farmer to
monitor their cattle from a remote internet connection.
It is important that the project be designed in such a way that a working final product is achieved.
This may involve a lower final operability of the project than that would be expected of a
commercial product. The candidate should achieve a fully operational asset tracking system that
transmits:
 Latitude
 Longitude
 Tag ID
 Battery level of remote node
2
To showcase the operability of the system, the candidate should ideally get this system working in
a large open environment to represent a small farm. The goal is to actively track the end nodes, be
that on a webpage local to the Central Gateway or should time permit, via the internet on a
smartphone.
The orange boundaries on the satellite image in Figure 2 depicts the expanse of the testing area to
be simulated:
Figure 2 Proposed Testing area
The “Homestead” marked on the map is where the Central Gateway of the farm will be placed. This
Central Gateway collects information from remote nodes within the testing area. The information
will be received using radio waves; likely from the sub GHz spectrum. This Central Gateway will
have a connection via WIFI/Ethernet to The Cloud, where the information retrieved from the nodes
will be placed into an online database. The hardware associated with the receiving of radio signals
in the Central Gateway depends on the hardware used in the remote nodes.
3
Using radio technology, the cattle should theoretically be traced over a short to medium length
distance using Remote Radio Transmitters with incorporated microcontrollers. This project assumes
the furthest distance between Remote Node and Central Gateway to be 1km, since the furthest
distance to be tracked here is 820m. Since sub-GHz radio transmitters commonly have a high
distance range, the candidate should use one that operates using the 400-900MHz frequency.
The learning outcomes of this project include:
 A good knowledge of wireless systems and how data is transferred between Central Gateway
and remote node.
 A better knowledge of how master and slave nodes work and the structure in which they
receive, store, and transmit information between each other.
 A basic knowledge of how location tracking technology operates and how to apply it to this
system.
 A good knowledge of how data can be stored, both on the cloud and on a local computer.
 A better knowledge of domains, web directories and website hosts.
Some of the boundaries of this project include:
 The limited timespan of the project.
 Keeping the overall cost of the project down.
 How to showcase the final product.
 Having a good range (1km) from end node to receiver. See “Working Area” in appendices.
4
Chapter 2: Background Research:
Radio Technology:
With the plethora of radio technology that is available today, it is important to choose the right one
that suits the application of this project perfectly. To do so one must look at the key requirements
of the radio network to be utilised:
 Allow two-way communication between Central Gateway and remote nodes.
 Have a long range (~850m).
 Be low powered and require low voltage.
 Be portable enough to be carried by a cow.
 Be capable of transmitting simple, low data strings of information.
While researching the various wireless networks that could be utilised as part of this project, it
quickly became apparent that there are many systems that utilise radio technology to transfer
information wirelessly. A radio frequency is formed by applying an alternating electrical current to
an antenna. This alternating current produces an electromagnetic field which propagates into what
is sometimes called an ‘RF Field’. Any frequency between 9 kHz and 300GHz is considered a radio
frequency. What divides the different radio technologies today are the protocols and modulations
used in interpreting and sending information. The use of these trademark protocols influences the
price. This would make the standard radio transceiver to be cheaper than its trademarked
counterparts. However, trademarked protocols have the added benefit of inherent security,
reliability and well documented support. [1]
WIFI:
Figure 3 WIFI Logo
The WiFi trademark (logo in Figure 3) represents one of the most common forms of wireless data
transfer. The WiFi protocol allows electronic devices to communicate wirelessly over a Wireless
Local Area Network (WLAN) connected to a high-speed internet connection. WiFi is governed by
IEEE standards, namely 802.11a/b/g/n/ad/ac. These standards define the communications protocols
utilised by WiFi and result in better quality of service, security and mobility. [2]
WiFi offers the most expensive solution but is highly regarded in terms of security. This would
make WiFi the most effective solution, were the system dealing with sensitive information, such as
financial data or medical records. However, since there is no pertinent information being handled,
such security measures are a luxury not a necessity. What does rule WiFi out as a potential network
for this project is the range; an average of 46m indoors and 92m outdoors.
5
Bluetooth:
Bluetooth, shown in Figure 4, is a standard of radio frequency and operates in the 2.4GHz Industrial,
Scientific and Medical (ISM) band. At the time of Bluetooth’s development, transceivers in the
2.4GHz ISM band were required to employ a spread spectrum technique. Bluetooth employs a
Frequency Hopping Spread Spectrum (FHSS) technique to achieve this, where the device hops
randomly between 79 1MHz channels at a rate of 1600 hops per second. This frequency hopping
helps to avoid conflicts which operate on the same frequency band, such as WiFi and Zigbee. [3]
The Bluetooth protocol operates by pairing two or more Bluetooth nodes together. The range offered
by Bluetooth devices varies with the class of device utilised. Class 1 devices offer a range of 100m,
a power rating of 100mW and are used in industrial applications. Class 2 devices are the most
common sort and are used in mobile phones, headphones and wireless mice. These devices have a
power rating of 2.5mW and have a maximum range of 10m. Class 3 devices have a power rating of
1mA and have a range of 1m. In summary, Bluetooth devices do not offer enough range to satisfy
the scope of this project. [4]
Figure 4 Bluetooth logo
Zigbee:
In researching this project, the candidate interviewed an upperclassman, one Glen Byrne. When
asked about long range radio networks, he suggested the Zigbee module, which he had utilised in
his own final year project. Thus this module became a likely candidate for the project.
In researching this module, it became apparent that the module is used extensively in low cost, low
power wireless applications. It exhibits quite a low transfer rate; 250kB/s. Zigbees can be deployed
in a mesh network configuration, which would theoretically extend the range from central master
node to end node through the use of intermediary nodes. However, they can also be configured in
tree cluster or star configurations, where poling between each node would allow for less information
pileup and leave the receiver less vulnerable to stack overflow. The Zigbee protocol operates
through Direct Sequence Spread Spectrum (DSSS) which allows the Zigbee to operate in a noisy
frequency environment. Digikey produces a number of different XBee modules, each offering
different ranges. For a 300ft module, it costs $24.95 from Sparkfun. For a 40 mile module, it costs
$194.95. The most suitable module to be used is the XBee Pro 63mW RPSMA - Series 2B (ZigBee
Mesh), which has a range of 1 mile and costs $44.95. For a radio module alone, this is too expensive
when one has to consider that a tracking system must also be employed to each remote node. Thus
the cost of the Xbee module proved a considerable deterrent in utilising one for the project. [5]
6
Figure 5 Zigbee Logo
LoRa:
A new form of radio modulation was developed in Semtech’s LoRa network. It consists of low
power, low frequency, and long range end modules that have a range of over 15km in a suburban
environment and operates in the license-free ISM frequency bands. It uses a Chirp Spread Spectrum
protocol to modulate the information processed which allows it to operate in today’s radio saturated
environment without noise [6]. These can act as end nodes and contain embedded Class A protocol
that can connect to any LoRaWAN Gateway. It is possible to make a DIY LoRaWAN Gateway
using an iC880A-SPI 868MHz concentrator. However this module costs €189.00 and is much too
expensive for the sake of this project. [7] An Xbee module does not have the same range and is a
lot more expensive than LoRa modules. Information on some LoRa modules can be found in the
appendices of this report.
The AppconWireless seems to be the most suitable LoRa module for this project. These are used
extensively in the tracking of weather balloons and will provide more than enough range for the
purposes of my project. With a pre soldered SubMiniture version A (SMA) connection for the
attachment of an aerial. The datasheet specifies that this is a suitable module for central and end
node applications. A Semtech SX1272 is integrated in the module and allows it to operate at
169/433/868/915MHz. A high speed microchip from ST controls the module. It is labelled as “easy
to use” and has a “reception sensitivity of up to-148dBm”. Cost: $19.50 per module. [8]
Figure 6 AppconWireless RF1276
7
Tracking technology:
The tracking of objects usually is done in terms of latitude and longitude. A combination of both
leads to a specific point on the earth. For the sake of this project, the candidate compared two forms
of tracking systems.
Signal Strength Telemetry:
This is a land based tracking system. It involves a minimum of three fixed receivers with known
location and at least one remote that needs to be located. Since the Received Signal Strength
Indication (RSSI) of a transmission diminishes with distance, it is possible to measure the distance
between the remote node and each stationary received. For this system to be implemented, 3 base
stations would be required with radio networking installed to allow communication between each.
A calibration process would be required to convert the RSSI to a distance. This system would be
excessively expensive, complicated and power hungry and thus would not be suitable for this
project. [9]
Global Positioning Satellite (GPS):
GPS is a tracking system where the unknown location of a GPS end module is found by using a
number of overhead satellites with a known location. When connection is made between a number
of overhead satellites and the end module, the GPS module receive location information in the form
of a National Marine Electronics Association (NMEA) string and arrives in the form of American
Standard Code of Information Exchange (ASCII) text. This string can then be parsed into relevant
fields, such as latitude, longitude, date and time. On some of the more advanced modules, altitude
can even be determined. Modules are light, cheap and widely available and would be suited for this
project. These modules calculate their position by deducing its distance from visible satellites and
using triangulation to calculate position. One such GPS Module is the UBlox NEO 6M module,
which can be purchased at £10.99 per module from Amazon. It operates of a 5V source and draws
77mA while running. [10]
Figure 7 NEO-6M-001 GPS Module
Existing Radio Tracking Systems:
IOTA Tracking System:
IOTA is an American company which designs a similar tracking system using LoRa technology.
They design remote nodes that have a range of 1-4 miles. The nodes contain temperature sensors, a
GPS module, an audio alarm, a waterproof casing and a long lasting battery. The Central Gateway
and one module can be purchased for $150. Any further remote nodes cost $50. This is very
expensive and is not suitable for the farm industry. While this range would be suitable for the
purposes of this project, The LoRa modules previously mentioned have longer distances detailed in
8
their respective datasheets. It would be quite possible to trump this system in terms of cost and
range. [11]
Types of Controller:
Two forms of controller are required for this project. One controller must act as the Central Gateway.
While researching it was necessary to find one that could operate as a gateway that can connect to
the internet, via either WiFi or Ethernet. One main module stood out:
Raspberry Pi:
Figure 8 Raspberry Pi logo and Raspberry Pi 2 Model B
The Raspberry Pi seemed the most logical choice since it has a plethora of information available
online. It comes stocked with 4 on board USB ports, an Ethernet connection, is relatively low power
(2000mA @ 5V = 10 watts). It contains an array of General Purpose Input Output (GPIO) pins,
some of which can establish a Universal Asynchronous Receiver/Transmitter (UART) connection
with Serial Devices. This could prove useful when dealing with information from a radio module
attached to the GPIO pins to retrieve information from the remote nodes.
The other form of controller must operate as the end node. It will be required to receive serial
information from a GPS module and send and receive information via the selected Radio module.
Three modules in which the candidate has experience in using are outlined below:
 Microchip’s dsPIC
 Texas Instruments MSP430
 Arduino
Microchip’s PIC:
Figure 9 Microchip Logo and dsPIC30F4011
9
Microchip’s dsPIC30F4011 was used in the candidate’s Robotics module, ROBO3109. It proved to
be a durable and reliable microcontroller. With 2 hardware UART ports, this chip has all the
necessary communications capabilities required to communicate with both a GPS module and a
radio module. It operates at between 3.0 and 5.5V, hence it would be possible to find radio and GPS
modules that operate under the same voltage. This would reduce the need for a highly inefficient
voltage regulator. However, there are not many libraries available for the dsPIC that would easily
allow the parsing of a GPS string. This microcontroller would not be suitable for the project since
the parsing of the GPS string would involve too much dedication, waste too much time and risk the
overall completion of the project [12].
Texas Instruments MSP430:
Figure 10 TI logo and MSP430g2553
Used in the Engineering, Practice and Design module, the MSP430 is a small microchip that would
suit the compact end node proposed for the project. It operates off a 3.3V supply and consumes just
330μA when running in active mode at 1MHz with VCC at 3V (not including external current).
However, the device has only one hardware serial port. This would not be suitable for
communicating with both a GPS module and a radio module [13].
Arduino:
Figure 11 Arduino Logo and Arduino Nano
The Arduino is an open source platform. Numerous boards are available, but the Arduino Nano
ATmega328 is readily available in college. This is a small, breadboard-friendly board that can easily
be programmed using the Arduino IDE. Having only one serial channel on digital pins 0 (RX) and
1 (TX), this would appear to be unsuitable for the project. However, many open source libraries are
available for the Arduino Nano. One of these libraries is the Software Serial library, which allows
serial communication on any of the Arduino Nano’s digital pins. The Arduino operates off 7-12V
applied to VCC. However, a 5V supply can be applied to the 5V pin, which bypasses the Arduino’s
voltage regulator. This would match the voltages of the GPS and Radio Modules and remove the
need for any voltage regulation circuits. [14]
10
Cloud Computing:
In order to view the location information from a remote connection, it is necessary to have it on a
webpage online. In order to do this, one needs to own a domain and a web hosting account. While
researching possible domain hosting services, the candidate found www.domain.com. Here the
candidate searched and found an unused domain name; www.donalomuiri.com. This domain was
purchased for one year for $10. However, this only reserves the domain and does not allow for any
server side coding, as is used by the PHP file format. This unfortunately costs a further $4.75 per
month. This hosting package comes with an online MySQL Database which can be used to store
past locations online, and thus was deemed a useful feature to be included in the project.
In order to send files to and from the web directory of files, a third part ftp client is required. One
such client, FileZilla, is free to download and allows transfer of files between the local PC and the
web directory. [15]
11
Chapter 3: Design of System & Implementation:
Project Planning:
Since there is a limited time allotted to this project, it is important to use this time efficiently. In
order to manage time spent at each task, the candidate used the Microsoft Project software package
to plan each stage of the project and the time to be allocated to each stage Figure 12 shows a
condensed version of the Gantt chart that governed the course of the project. A more complete
version can be found in the Appendices section of this report in Figure 33.
Figure 12 Gantt chart Overview
Selected modules:
Item Model Quantity Cost
each
Cost Arrived
GPS
Module
Ublox NEO-6M-0-001 4 £10.99 €55.63 29/2/2016
Radio
Module
AppconWireless RF1276 5 $19.50 €85.31 21/3/2016
Central
Gateway
Raspberry Pi 2- 8GB Starter Kit 1 £51.25 €64.85 26/2/2016
End node
controller
Arduino Nano ATmega328
Clone
4 Was available in college
USB to
Serial
Adapter
Prolific PL2303 1 $3.00 €2.62 21/3/2016
Antennae Stubby antenna (433MHz)
Wire Whip antenna (433MHz)
4
1
$2.00
$3.00
€9.62 21/3/2016
Total Cost: €218.03
Table 1 Costs involved
12
Table 1 constitutes the cost of one Central Gateway and four remote nodes. For the same cost, one
could only buy one gateway and 3 remote nodes from the IOTA tracking company. Thus, this project
shows an improvement upon an existing company’s product in terms of cost.
Original Design of system:
The original design of the system outlined in Figure 13 is inherent with flaws. However, it outlines
a good base from which to start developing the project.
Figure 13 Original Block Diagram of System
This system only allows for one way communication from the end node to the Central Gateway.
This model will not allow poling across all the nodes and a risk of clashing messages is present.
Poling is when the Central Gateway would sequentially request information from each of the remote
nodes. It also only caters for the webpage being displayed on a local network. This is beneficial in
the tracking of remote nodes when in the vicinity of the base station. This is not satisfactory for the
supervision of the nodes when not connected to the same local network.
Configuring the Raspberry Pi:
In order to operate the Raspberry Pi, one must upload an OS to it. This is done by copying the
NOOBS interface onto a microSD card. This will require a computer with internet connection and
a micro SD card slot. It is advised that a minimum sized microSD of 4GB formatted to FAT32 be
used. NOOBS can be downloaded from www.downloads.raspberrypi.org/NOOBS_latest. This will
download the version of NOOBS with the Raspbian OS preinstalled. This is quite similar to the
Debian Linux package. Once the download is finished, the zip file is extracted into the root folder
of the microSD card. When the extraction is complete, the card can then be safely removed from the
computer and placed in the Raspberry Pi. [16]
In order to setup the Raspberry Pi, one must connect a keyboard and mouse into the USB terminals.
A HDMI cable must be connected between the Pi and a monitor and the micro USB power adapter
must be connected. The Pi will boot up into the NOOBS menu, where you can click to install
"Raspbian". This will take then take a few minutes to install, all the while following the basic
prompts. On the login screen, the default user name is “pi” and the default password is “raspberry”.
You will then be directed to the Raspbian desktop.
13
Now that Raspbian is installed, it is now time to start installing the necessary application and drivers.
This is done by entering commands into the Terminal Window. It is good practice to run the
following two commands before each installation:
sudo apt-get update
sudo apt-get upgrade
This will update and upgrade all the current drivers and applications.
Application Command line prompt
Arduino IDE sudo apt-get install arduino
MySQL sudo apt-get install mysql-server Python-mysqldb [17]
Apache2 sudo apt-get install apache2 –y [18]
PHP5 sudo apt-get install php5 libapache2-mod-php5 –y [18]
Table 2 Terminal Window installation prompts
Install the PySerial Library for Python:
The Pyserial library must be installed to let the Python script recognise serial input and to write
serial output to the USB device (PL2303). The simple library can be installed using the following
command line prompt:
-$ sudo pip install pyserial
Configuring Serial Communications between Pi and RF1276:
The original design of the project assumed that you could connect the UART of the LoRa module
to the GPIO pins of the Raspberry Pi. However, since the UART of the AppconWireless RF1276
operates at 5V and the voltage limit of the Pi’s GPIO pins is 3.3V, a direct connection between the
devices is not possible without damaging the 3.3V GPIO pins of the Pi. Thus level conversion must
be used to allow UART via GPIO pins. This can through the use of a Level Translator board, which
can be bought from Sparkfun for €6.58.
Figure 14 Sparkfun Level Translator Breakout- PCA9306
This incurs further cost to the project which is undesirable if the project is to financially compete
with the IOTA tracking system. Thus the design of the project had to be revised. Instead of using
14
the UART GPIO pins of the Raspberry Pi, the Prolific PL2303 USB to Serial adapter would be
constantly left in USB port. This provided a more cost effective solution to the problem.
Fortunately, the driver for the PL2303 comes as standard on the Raspberry Pi. What was required
was to load the necessary “Kernel Module”. The Kernel is the method by which the hardware of a
computer coordinates with the OS. The following steps show how to configure the adapter.
Step 1: “-$ lsusb” was ran in the terminal window. This command listed all devices connected to
the USB ports of the Raspberry Pi. Take note of the line containing the below information.
Bus 005 Device 002: ID 067b:2303 Prolific Technology Inc. PL2303 Serial Port
Step 2: Next the device information was loaded into the Kernel module by typing the following
command into the terminal window.
-$ sudo modprobe usbserial vendor=0x067b product=0x2303
Step 3: To confirm that the device was loaded successfully to the kernel, “-$ dmesg” was ran.
The following lines appeared at the bottom of the response message:
[131.747013] USB Serial support registered for pl2303
[131.747038] pl2303 5-1:1.0: >pl2303 converter detected
[131.758965] usb 5-1: >pl2303 converter now attached to ttyUSB0
The Serial feed from the RF1276 was then utilised using simple “Serial.read()” commands
in Python.
Configuring the Arduino:
In order for the Arduino to operate as intended, two user libraries were utilised.
SoftwareSerial:
This library is native to the Arduino Integrated Development Environment (IDE) and allows the use
of any pair of digital pins to be used as a serial connection. Since there is only one hardware serial
port on the Arduino Nano, the design of this system relies on the use of 2 software serial ports, one
for the GPS and one for the LoRa module. The hardware serial port will be reserved for
troubleshooting purposes. However, data can be received from only one software serial port at a time.
Thus it is necessary to close each software serial port before another can be read. [19]
TinyGPSPlus by Mikal Hart:
This library is very useful in parsing an NMEA string into more user friendly variables. This will limit
the amount of time spent in parsing GPS information. The package was downloaded in the form of a
.zip file. In the Arduino IDE, the candidate navigated to Sketch > Include Library > Add .ZIP Library.
Then the downloaded .zip file was located and selected. [20]
Determining Battery Level:
The Arduino Nano has a 10-bit analogue to Analogue to Digital Converter (ADC). From Nyquist’s
theorem, the number of digital units available to an ADC is (2n
-1), where n is the number of bits. In
this case there are 1023 digital units. The ADC in question is ratiometric, where the analogue
reference voltage is determined from the voltage applied to VCC. There is also a 1.1V bandgap
15
reference voltage in the ATMega328. When the value from the bandgap reference is compared VCC,
it is possible to measure what voltage the batteries are running at. For the sake of the below equation,
x represents the reading of the 1.1V reference.
𝑖𝑓 𝑉𝐶𝐶 𝑖𝑠 5𝑉:
1100
5000
× 1023 = 225
𝑎𝑛𝑑 𝑖𝑓 𝑉𝐶𝐶 𝑖𝑠 3.3𝑉:
1100
3300
× 1023 = 341
𝐺𝑒𝑛𝑒𝑟𝑎𝑙𝑙𝑦:
1100
𝑉𝐶𝐶
× 1023 = 𝑥
𝑅𝑒𝑎𝑟𝑟𝑎𝑛𝑔𝑖𝑛𝑔: 𝑉𝐶𝐶 =
1100
𝑥
× 1023
Hence by reading the value of the bandgap reference value, the voltage on VCC can be determined.
The relevant code can be seen in the readVcc{} function in the Poling_V1.ino file. This script can be
seen sleep_mode_example.ino in the coding section of the Appendices. [21]
Configuring the LoRa Module:
Since the LoRaWAN gateway was so expensive, it was decided that a poling system be utilised. This
operates by assigning one of the nodes as a master. This master is in charge of sending commands out
to each individual remote node. Once the information from one node is attained and processed, the
master then moves on to the next node. The benefits of this mode include:
 No clashing information from remote nodes bombarding the Central Gateway.
 The control of a large quantity of devices.
 A secure handshaking arrangement between nodes before information is processed.
 A very cost effective system.
In order for the LoRa modules to communicate with each other they must have the same
characteristics. 433MHz antennae were purchased from AppconWireless, so it is essential that the
LoRa modules are configured to reflect this. A rather low baud rate of 9600 is used for both serial and
radio transmissions, such as to allow reliable readings to be taken. These settings can be configured
using the “RF tool for RF1276” shown in Figure 15Error! Reference source not found.. Note that
the Power setting is set to 7, the maximum transmission setting for the device. The serial
communications on the Arduino should also be assigned a baud rate of 9600.
16
Online Web Directory:
The online web directory requires having a few integral files uploaded to it from a remote computer
with internet connection. Using FileZilla to establish an FTP connection, the required system files
were uploaded. First a new folder had to be established called “public_html”. This folder is then set
as the domain pointer. Within this folder another folder was placed called “tracker”. Here is where
all online files relevant to the project are located. It is necessary to have your ftp address, provided
by your hosting company.
Figure 16 FileZilla window
While the hosting account came with a MySQL database, it was found that the hosting company did
not allow access to the database from a remote computer for security purposes. This was a huge
problem, as the original plan used the local MySQL on the Raspberry Pi to upload directly into the
online MySQL directory. Instead it was decided that a Python script running on the Raspberry Pi
would that the incoming string of information and place the information in a text file. A File Transfer
Protocol (FTP) library for Python would then upload the string into the online web directory. This
Figure 15 PL2303 to RF1276 and RF tool for RF1276
17
Python script would also have the added benefit of inserting the incoming information into an
identical offline MySQL database to have two records of the past locations of the nodes. The Python
script can be found in the code section of the Appendices at the end of this document.
A PHP file, entitled “txt_2_mysql.php” would then be uploaded into the “tracker” directory. This
webpage operates by extracting information from the uploaded text file and inserting the
information into an online MySQL database. The Sequence Query Language (SQL) code used to
create this table is outlined in the Code section of the Appendices. This PHP file automatically
refreshes every 5 seconds, inserting whatever data is in that text file at that moment into the MySQL
database. This webpage is left running on the base station continuously.
The webpage that shows the locations of the nodes is entitled “index.php”. Relevant code can be
found in the Code section of the Appendices. This webpage operates by using Python script to
extract the 4 most recent entries from the online MySQL database and place them in a table. Since
the readings are taken in a poling format, the four most recent readings will be from each of the 4
end nodes, assuming that all nodes were within range and all readings were received. The Google
Maps JavaScript API with implanted PHP takes the information from the online MySQL database
and inserts it into an addMarker{} JavaScript function, where a new marker is placed on the Google
Maps window on the page.
Figure 17 Online Web Page
18
Wiring Schematic:
Figure 18 shows the wiring diagram for each of the end modules and the Central Gateway.
Final Block Diagram:
Figure 19 shows the final block diagram. It outlines the procedure by which the locations of the end
nodes are processed, sent to the Central Gateway and displayed on the online webpage.
Figure 18 Wiring Diagram
19
Figure19FinalBlockDiagram
20
Chapter 4: Testing and Results:
Test 1: Measuring VCC:
The goal of this test is to acquire the Vin on the Arduino Nano. Since battery’s voltage drop before
they die, monitoring battery voltage gives one an indication of the charge left on a battery. It was
found that this is possible by using the AVR’s internal 1.1V reference and comparing it to the
voltage on the Vin terminal. This is done by pointing then ADC on the Arduino to the Vin terminal.
This method negates the need for any voltage divider circuits, which consume power and reduce the
life of the battery. Unfortunately, voltage higher than the output of the voltage regulator on board
the Arduino Nano cannot be determined without the use of a voltage divider circuit.
Meter 3.75 3.90 4.00 4.2 4.4 4.5 4.7 5 5.2 5.4 5.5 5.7 5.75 5.8 5.9
Arduino
@ 1.1V
3.044 3.19 3.274 3.487 3.717 3.818 4.022 4.349 4.541 4.772 4.876 5.051 5.096 5.143 5.214
Error 0.706 0.713 0.726 0.713 0.683 0.682 0.678 0.651 0.659 0.628 0.624 0.649 0.654 0.657 0.686
Table 3 Voltmeter vs. Arduino voltage readings
Figure 20 Voltmeter vs. Arduino voltage readings
Analysis:
The error seems to be constantly around the 0.7V mark. This
would lead one to believe there is a constant volt drop between
the Vin Terminal and the VCC to the Atmel chip. Looking at
the Arduino schematic, a UA78M058 5V voltage regulator
protects the VCC to the Atmel microprocessor. The 0.7V volt
drop across the in and out terminals causes the error in the
Arduino’s reading. This can be rectified by simply adding
0.7V to the Arduino’s voltage reading.
0
1
2
3
4
5
6
0 2 4 6 8 10 12 14
Voltage(V)
Sample Number
Meter Arduino @ 1.1V Difference
Figure 21 Arduino Nano Voltage Regulator
21
Figure 22 Test 2 wiring diagram
Test 2: Power Consumption:
The function of this test is to monitor the possible states each of the modules can be placed into to
conserve power. Focus will be on preserving as much functionality as is possible. If current from
the battery can be reduced, the battery life will be extended. The code used to test the power
consumption of the Arduino in sleep mode can be viewed in the code section of the Appendices.
Equipment:
 Power Supply
 Ammeter
 Tracking unit
Analysis:
With the current poling setup, the tracking nodes draw 108.7mA when receiving and 162mA when
transmitting. If a reading is taken every minute and since it takes approximately 2 seconds to
transmit a message, an average of 110.47mA can be taken into account.
(108.7 ×
58
60
) + (162 ×
2
60
) = 110.47𝑚𝐴
Using 4 rechargeable NiMH batteries in series, with each rated at 1.2V/1300mAh, the result is a
4.8V source with 1300mAh of energy on board. Using the poling system with the timing outlined
above, one can expect only 11.76 hours of tracking time. Even if the LoRa module only stayed in
receiving state and never transmitted, the device would only operate for:
1300mAh
108.7mA
= 11.96 hours.
It was found that the most energy saving method would involve putting the Arduino to sleep, waking
up every hour to send off information. The GPS module and LoRa module should have their VCCs
powered by a driver chip, such as the SN754410NE for this approach. This can also be done by
simply using two transistors. It was first thought that the Arduino Nano could use some of its digital
pins to power the two modules. Unfortunately the digital pins have a maximum DC current limit of
40mA, hence the need for the driver chip. The SN754410NE draws an off-state current of 0.5mA.
[22] This means that the device could stay in sleep mode for:
Device Current
RF1276 Receiving: 19.2mA
RF1276 Transmitting 73mA
NEO-6M GPS Module: 77mA
Arduino Nano Running: 12.5mA
Arduino Nano Sleeping: 4.9mA
Table 4 Test 2 Results
22
1300𝑚𝐴ℎ
(4.9 + 0.5)𝑚𝐴
= 240 ℎ𝑜𝑢𝑟𝑠 𝑜𝑟 10 𝑑𝑎𝑦𝑠
The downside of this method is that since the LoRa module is turned off by default, a poling system
cannot operate. Each node blindly sends the information, regardless of the fact that information
coming from another node could block the transmission. Another problem is that the GPS won’t
automatically be connected to overhead satellites. It could take more than three minutes with each
reading to reconnect to satellites and gather the relevant GPS information. There would also be no
way to stop two modules from sending information at the one time, which would cause the Central
Gateway to neglect the incoming information from one or both of the clashing end nodes.
Conclusion:
While the poling method is the most user friendly method, the end nodes consume too much power.
The battery life under poling conditions is not suitable for long term monitoring of cattle. In order
to extend the life of the remote node, it is necessary to used modules that are more power efficient.
The GPS module draws 77mA when operating. If a more power efficient GPS module could be
found, the overall power consumption of the end node would be greatly reduced. Alternatively
putting the module into sleep mode would greatly reduce the power consumption, at the expense of
user control.
The end nodes still function as was intended in the design specifications. The only problem is that
they would not operate for long enough to be considered practical for the purposes of this project.
23
Figure 24 Example string of information received by Central Gateway Figure 25 Operator carrying Remote node
Test 3: Field Testing:
The function of this test is to show the capabilities of the tracking
system within a small open area. A convenient place to test this
was on St. Stephen’s Green, Dublin. Figure 23 shows the Central
Gateway attached to an external battery pack. It was connected
to the internet via a WiFi hub. This shows the capability for the
base station to be used remotely, so long as it has an internet
connection and enough charge on the battery. For the sake of this
test, only one remote node was used, since the operator could not
carry more than one tracking unit and there were only enough
charged batteries available for one remote node. This tracking
unit is shown in Figure 25. This script had to be altered to allow
the poling of only one node. This was done by deleting all but
“Cow_1” from the “Node_Inventory” list.
Before leaving for St. Stephen’s Green, the Raspberry Pi was
connected to a monitor in the college. The Pi was turned on and
Poling_with_basic_ftp.py was initiated. Figure 24 shows the
python script response on the monitor. The txt_2_mysql.php web
page was opened in the “Chromium” internet browser.
After the Python script and web page were ran, the monitor was unplugged. The Central Gateway
and tracking unit were then brought to St. Stephen’s Green. The Central Gateway was left on the
ground, as is shown in Figure 27, and the index.php web page was loaded on the operator’s phone.
The operator walked around Stephen’s green, allowing the GPS Coordinates to be sent back to the
base station. The results of this test are shown in Figure 26 to Figure 29.
Figure 23 Central Gateway with battery
pack and WiFi Dongle
24
Figure 27 Central Gateway on ground
Figure 26 Screenshot 1
Figure 31 Screenshot 3
Figure 30 Screenshot 2
Figure 29 Screenshot 5
Figure 28 Screenshot 4
25
Chapter 5: Conclusions & Evaluation:
In concluding this project, it is necessary to ensure that all goals of the system were achieved. The
radio communications between end nodes and Central Gateway were arranged in a neat fashion
using a LoRa network that was tested in a large open area similar to a field and communications
held constant throughout the test. While testing in college it was found that the LoRa device had
some problems in communicating through walls, but this is not a great issue since the goal of the
project was to communicate in an open field. A poling system was employed between Central
Gateway and the remote nodes so as to reduce clashing between the remote nodes and to ensure all
information was reliably processed. A timer interrupt system involving the tracking unit going to
sleep was investigated and proved to be a much more power efficient design. Were there more time
or people available for this project, it would have been interesting to develop this system further and
test for any of the suspected clashing issues that may have arose with such a system. With the time
allocated, a reliable radio network was established that would be appropriate for the tracking of
cattle, albeit for a short period of time. The system in use at the moment would be more suitable for
the tracking of vehicles on a farm or other workplace. This would result in having enough energy
to sustain the end tracking units for a much longer period of time.
The NEO-6M proved a reliable GPS module that was easily configured. This module allowed the
monitoring of latitude, longitude, date and time, all the core goals that were required of the tracking
system. The TinyGPSplus library allowed for a more user friendly approach to the parsing of the
NMEA string. Connection to satellites proved difficult at times when there was not a clear view of
the sky, but since the tracking unit is designed to operate in the open air, this was not a problem.
The GPS module obtained a connection within 3 minutes when in the open air, which is sufficient
for small budget applications such as this.
The Arduino Nano proved to be a reliable microcontroller. In its fully operational state, it only drew
12.5mA from the supply; the most power efficient module in the system. While acknowledging that
the code must specify which serial port is currently being read from, the SoftwareSerial library
worked brilliantly in turning a standard pair of digital pins into a fully operational serial port. This
remote node controller succeeded in maintaining communications with both the LoRa module and
the GPS module, while also parsing the NMEA string into a useful format, as was shown in Figure
24. The obtaining of the battery level in millivolts proved to be a useful method of determining if
the energy levels of the battery were dwindling.
While there was some trouble with blocked access to the online MySQL directory, this problem was
overcome through the use of an ftp Python library and a constantly running text_2_mysql.php script
running on the Central Gateway. The web interface now successfully uploads the end node location
information to The Cloud and is accessible from remote networks and locations. The index.php web
page within the public_html/tracker directory of the www.donalomuiri.com webpage displays the
node's location in a table and in a google maps window. The date, time and tag identifier can be
attained by simply clicking on one of the Google Maps markers, as can be seen in Figure 28.
26
Given extra time, the candidate would have liked to add the following improvements to the project:
Signal Strength Monitoring:
It would be an improvement to introduce an RSSI process to this system to give warning if a node
is out of range. By requesting information on this from the supplier, the “User Guide of RF1276”
was attained. In order to request the RSSI value, the Central Gateway must first receive a message
from the end node. The Arduino Nano must then send the following command via UART port to
the LoRa module:
0xAF,0xAF,0x00,0x00,0xAF,0x80,0x06,0x02,0x00,0x00,0x95,0x0D,0x0A
The response from the LoRa module will be in hexadecimal form:
0xAF,0xAF,0x00,0x00,0xAF,0x00,0x06,0x02,0xXX,0x00,0xCS,0x0D,0x0A
The value for 0xXX will determine the relative RSSI value. This value must be converted from
hexadecimal to decimal form. Then the following formula is used to determine the final RSSI value:
𝑅𝑆𝑆𝐼 = (−164 + 𝑑𝑒𝑐𝑖𝑚𝑎𝑙_𝑟𝑒𝑙𝑎𝑡𝑖𝑣𝑒_𝑅𝑆𝑆𝐼) 𝑑𝐵𝑚
Attaining the RSSI value will help determine any blind spots in the field and give the user an
indication of the coverage of the radio network. [23]
Improvements to the Online Tracking System:
It has already been shown that the tracking system has a tendency to skip putting values into the
online MySQL database due to the timing issue with the text_2_mysql.php page. One way to avoid
this timing issue is to only run the txt_2_mysql.php page whenever the Remote_information.txt file
is updated. If there were any further time to expand on this, it is quite possible to make a much more
reliable system.
Another possible improvement would be the creation of different tables for each remote node within
the online MySQL database and have the txt_2_mysql.php page parsing the information in the
Remote_information.txt file. This would detect which node it is from the first term in the string, and
insert the information into each node’s respective table. Then the index.php file would extract the
Google Maps markers from each table. This would have the effect of having the most recent location
of each node being placed on the map.
Message Queuing Telemetry Transport (MQTT) Protocol:
A completely different method of placing IOT information onto the Internet is through the use of
MQTT protocol. This is a Publish/Subscribe service, where devices can publish to a specific topic
on an MQTT server, and other devices can subscribe to the messages posted into this topic. Figure
33 depicts the block diagram of the proposed MQTT system.
27
Figure 32 MQTT block diagram
The benefit of this system is that a MySQL database is not required. Each of the different end nodes
can be assigned their own topic. The webpage itself could subscribe to each of these topics and
display them on a webpage similar to that which is currently being used in index.php. The most
recent reading for each node could be retained by enabling the “Last Will and Testament” protocol
for each topic. This would negate the need for multiple MySQL databases.
The disadvantage with this method is that there is no history available for where the nodes have
been before the most recent reading. This is not necessary for the scope of this project but is a nice
feature that is available with the MySQL method that is being applied at present. Another
disadvantage is that a hosting account would still be necessary to be able to access the webpage
online.
While these additions would prove beneficial to the project, they were not essential to the objectives
outlined in the introduction. A fully operational asset tracking system was created using a LoRa
radio network and the webpage clearly displays the information gathered by the system.
28
References:
[1] N. Instruments, “Introduction to RF & Wireless Communications Systems,” 23 09 2015.
[Online]. Available: http://www.ni.com/tutorial/3541/en/.
[2] D. Beck, “Choosing RF protocols for industrial, scientific and medical applications,”
EETimes, 28 05 2013. [Online]. Available:
http://www.eetimes.com/document.asp?doc_id=1280890&page_number=1.
[3] E. H. C. Jr., Wireless Sensor Networks- Architectures and Protocols, Florida: Auerbach
Publications, 2004.
[4] B. H. Ranjith Antony, Bluetooth for Java, Apress, 2008.
[5] S. Electronics, “XBee Guide,” [Online]. Available:
https://www.sparkfun.com/pages/xbee_guide.
[6] Semtech, “Semtech's RF Tranceivers,” Semtech, [Online]. Available:
http://www.semtech.com/wireless-rf/rf-transceivers/. [Accessed 01 02 2016].
[7] IMST, “iC880A-SPI – LoRaWAN Concentrator 868MHz,” [Online]. Available:
http://webshop.imst.de/ic880a-spi-lorawan-concentrator-868mhz.html.
[8] APPCON WIRELESS TECHNOLOGIES CO.,LTD, “RF1276 Long Distance Transceiver
module V2.0,” Appcon Wireless, 12 1 2014. [Online]. Available:
http://www.appconwireless.com/Uploadfiles/20160309020333595.pdf.
[9] C. Mathias, “Location and tracking technologies: Understanding the technology,” Network
World, 06 08 2012. [Online]. Available:
http://www.networkworld.com/article/2190180/wireless/location-and-tracking-technologies-
-understanding-the-technology.html.
[10] U-Blox, “NEO-6 u-blox 6 GPS Modules Datasheet,” 5 12 2011. [Online]. Available:
https://www.u-blox.com/sites/default/files/products/documents/NEO-
6_DataSheet_%28GPS.G6-HW-
09005%29.pdf?utm_source=en%2Fimages%2Fdownloads%2FProduct_Docs%2FNEO-
6_DataSheet_%28GPS.G6-HW-09005%29.pdf.
[11] iota, “Iota GPS Tracker,” Iotera, Inc., 2005. [Online]. Available:
http://www.iotatracker.com/.
29
[12] Microchip, “DSPIC30F4011/12 DATASHEET,” 2005. [Online]. Available:
http://ww1.microchip.com/downloads/en/devicedoc/70135C.pdf.
[13] T. Instruments, “MSP430G2x53 datasheet,” 05 2013. [Online]. Available:
http://www.ti.com/lit/ds/symlink/msp430g2553.pdf.
[14] Arduino, “Arduino Nano,” [Online]. Available:
https://www.arduino.cc/en/Main/ArduinoBoardNano.
[15] T. Kosse, “Filezilla Overview,” NDC Host, 09 05 2016. [Online]. Available: https://filezilla-
project.org/.
[16] R. P. Foundation, “Getting Started with NOOBs,” Raspberry Pi Foundation, [Online].
Available: https://www.raspberrypi.org/help/noobs-setup/.
[17] http://raspberrywebserver.com/, “Using MySQL on a Raspberry Pi,”
http://raspberrywebserver.com/, 10 09 2013. [Online]. Available:
http://raspberrywebserver.com/sql-databases/using-mysql-on-a-raspberry-pi.html. [Accessed
12 03 2016].
[18] Raspberry Pi Foundation, “SETTING UP AN APACHE WEB SERVER ON A
RASPBERRY PI,” [Online]. Available: https://www.raspberrypi.org/documentation/remote-
access/web-server/apache.md.
[19] Genuino, “SoftwareSerial Library,” Arduino, 2016. [Online]. Available:
https://www.arduino.cc/en/Reference/SoftwareSerial.
[20] M. Hart, “TinyGPSPlus,” 26 11 2013. [Online]. Available:
https://github.com/mikalhart/TinyGPSPlus.
[21] J.-C. Wipler, “Measuring VCC via the bandgap,” JC's Environmental Electronics, 04 05
2012. [Online]. Available: http://jeelabs.org/2012/05/04/measuring-vcc-via-the-bandgap/.
[22] Texas Instruments, “SN754410 Quadruple Half-H Driver,” Texas Instruments, 1 2015.
[Online]. Available: http://www.ti.com/lit/ds/symlink/sn754410.pdf.
[23] Appcon Wireless Technologies Co., User Guide of RF1276 V1.0, Hong Kong: Appcon
Wireless Technologies Co., 2015.
[24] microchip, “microchip web,” 2005. [Online]. Available:
http://ww1.microchip.com/downloads/en/DeviceDoc/70005219A.pdf.
30
Appendices:
31
Possible LoRa Modules
Name Image Properties Cost
RN2483
Standalone IC
Microchip
RN2483-
I/RM10 3.6V
LoRa Module,
LoRaWAN™
Class A UART
Supported Bus interfaces: UART
Supply Voltage: 3.6V
Dimensions: 17.8 x 26.7 x 3mm
Max Temp: +85°C
Min Temp: -40°C
Datasheet:
http://www.farnell.com/datasheets/1947946
.pdf
Useful links:
https://thinginnovations.uk/getting-started-
with-microchip-rn2483-lorawan-modules
RN2483 LoRa Long-Range Sub-GHz Transceiver
Module
The Microchip RN2483 Long Range LoRa™
Transceiver Module provides designers an
easy-to-use LoRaWAN™ Class A protocol
compliant solution for Internet of Things (IoT)
applications that require low-power data
communications. The RN2483 Integrates a
Baseband Controller and an Application
Programming Interface (API) processor,
simplifying the integration of LoRa™
technology into products.
General Features:
On-board LoRaWAN™ Class A protocol stack
ASCII command interface over UART
Compact form factor 17.8 x 26.7 x 3 mm
Castellated SMT pads for easy and reliable PCB
mounting
Device Firmware Upgrade (DFU) over UART
14 GPIO for control, status, and ADC
Highly integrated module with MCU, crystal, EUI-64
Node Identity Serial EEPROM, Radio transceiver
with analogue front end and matching circuitry
European R&TTE Directive Assessed Radio
Module
RF Features:
433 MHz and 868 MHz operating frequency
Programmable RF Communication Bit Rate
up to 300 kbps with FSK modulation, 5468
bps with LoRa™ Technology modulation
High Receiver Sensitivity: down to -148 dBm
TX Power: adjustable up to +14 dBm high
efficiency PA
FSK, GFSK, and LoRa Technology
modulation
IIP3 = -11 dBm
>15 km coverage in suburban environments,
>5 km coverage in urban environments
Radionics:
Temporarily out of
stock: - back order
for dispatch 11-3-
2016.
Delivery within 2
working days -
€13.21
Farnell:
Out of stock
€12.27
RN2483 LoRa
PICtail/PICtail
Plus Board
Microchip’s RN-2483-PICtail is a development
board featuring the RN2483 LoRa® 433/868
MHz LoRa Module. The board gives users
access to all the RN2483 Module’s UART and
GPIO ports.
The PICtail/PICtail Plus connector allows the
RN2483 to be developed with Microchip MCU
development tools such as the Explorer 16
(DM240001) and Explorer 8 (DM160228),
adding LoRa technology to these platforms.
Features:
Microchip RN2483 Low-Power Long Range, LoRa®
Technology Transceiver Module
SMA connectors for 433 MHz and 868 MHz bands
PIC18 MCU with In-Circuit Serial Programming
(ICSP) header for custom functions
Radionics:
Temporarily out of
stock - back order
for despatch 7-3-
16, delivery within
2 working days -
€58.62
Farnell:
Out of Stock
€59.84
32
Solder pads around the module for GPIOs, power
pins and communication signals
Supply Current measurement points
On-board LDO
UART traffic LEDs
USB connector
PICtail /PICtail Plus connection interface
New RN2483
LoRa Mote
Development
Node
RN2483 868 MHz LoRa Mote Development Node
The board provides a quick and easy to use
platform for demonstrating the capabilities of
the RN2483.
The LoRa®Mote is battery powered, providing
a portable tool to demonstrate the excellent
long-range capabilities of the RN2483. The
interoperability with LoRaWANv1.0 compliant
gateways and infrastructure can also be
verified.
Also demonstrated is Wireless Sensor
Network communication. Telemetry provided
by an on-board Ambient Light Sensor and
Thermistor can be transmitted as per a user-
defined schedule, or initiated on demand via
button-press on the Mote. An OLED display
provides feedback on connection status,
sensor values, downlink data and
acknowledgements.
A standard USB interface is provided for
connecting the Mote to a host computer.
When connected, the on-board USB-to-UART
bridge allows simple setup and control of the
LoRaWAN™ protocol stack using the high-
level ASCII command set.
Features:
868 MHz High-Frequency SMA Connector
433 MHz Low-Frequency Antenna test Point
Ambient Light Sensor
Linear Active Thermistor (MCP9700T)
OLED Display
Menu Navigation Switches
USB Mini-B Connector
PIC18LF25K50 8-bit MCU
Mote ICSP Programming
Indicator LEDs
Battery Powered – 2 x AAA Batteries
Alternative Power Supply Option via Through-
Hole Connectors
Kit Contents:
RN2483 868 MHz LoRa® Mote
Development Node
SMA Antenna
USB cable
Radionics:
Temporarily out of
stock - back order
for despatch 21-
03-2016, delivery
within 2 working
days - €64.43
Farnell:
Out of Stock -
€64.42
33
Figure 33 Complete Gantt Chart
34
Coding
<txt_2_mysql.php
<?php
// Page runs constantly on gateway computer, inserting code from the uploaded
// "Remote_Information.txt" file into the "latlong_V2" table in the "asset-tracker"
// online MySQL database.
// http://stackoverflow.com/questions/2601349/read-a-text-file-and-transfer-contents-to-mysql-database
// Opens a connection to a MySQL server
$connection=mysql_connect ('donalomuirieng.domaincommysql.com', 'donalomuirieng', 'Sheskin1993!');
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db("asset_tracker", $connection);
if (!$db_selected) {
die ('Can't use db: ' . mysql_error());
}
mysql_select_db("my_database");
$result = mysql_query("LOAD DATA LOCAL INFILE 'Remote_Information.txt'" .
" INTO TABLE latlong_V2 FIELDS TERMINATED BY ','");
if (!$result) {
die("Could not load. " . mysql_error());
}
?>
<html>
<head>
<meta http-equiv="refresh" content = "5">
</head>
<body>
<?php
echo "This page inserts data from 'Remote_Information.txt' into MySQL database."
?>
</body>
</html>
35
<index.php>
<?php
// This is the online webpage that extracts the most recent 4 entries from the "latlong_V2"
// MySQL database and inserts them into a table and into a google maps window, with latitude
// and longitude governing the construction of a marker, and inserting Tag_ID, DATE and TIME
// into a popup window.
// http://stackoverflow.com/questions/15633604/php-mysql-google-map
$conn = mysql_connect("donalomuirieng.domaincommysql.com", "donalomuirieng", "Sheskin1993!") or die(mysql_error());
mysql_select_db("asset_tracker") or die(mysql_error());
//construct a query and issue it to the database
// Anything begining with a dollar sign is parsed as a variable
$result = mysql_query("SELECT * FROM latlong_V2 ORDER BY READING_NUM DESC LIMIT 4") or die(mysql_error());
//Close our PHP (for now) and write our HTML page
?>
<link rel="stylesheet" type="text/css" href="mystyles.css" media="screen" />
<html>
<head>
<title>Asset Tracker</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="10">
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
// Code adapted from August Li’s
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/red.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
36
<?php
$query = mysql_query("SELECT * FROM latlong_V2 ORDER BY READING_NUM DESC LIMIT 4")or die(mysql_error());
while($row = mysql_fetch_array($query))
{
$name = $row['TAG_ID'];
$lat = $row['LATITUDE'];
$lon = $row['LONGITUDE'];
$time = $row['TIME'];
$date = $row['DATE'];
$battery_mV = $row['BATTERY_mV'];
echo("addMarker($lat, $lon, '<b>$name</b><br>$time<br>$date</b><br>$battery_mV</b>');n");
}
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" align="centre">
<h1>Asset Tracking</h1>
<p id ="p1"> latlong_V2 Table:
<br> Here we retrieve the Node location records from the `latlong_V2` table. </p>
<p align="center">
<table border="1" width="750px" align="centre" cellpadding="3">
<tr>
<th>Sample Number</th>
<th>Tag ID</th>
<th>Latitude</th>
<th>Longitude</th>
<th>Date</th>
<th>Time</th>
<th>Battery (mV)</th>
</tr>
<?php
// Now use a PHP while loop to output data as HTML table rows
while($data = mysql_fetch_array( $result ))
// Retrieve each row in $result & store it in the array '$data'
{
echo "<tr>"; // HTML command to start a table row
echo "<td>" . $data['READING_NUM'] ."</td> ";
echo "<td>" . $data['TAG_ID'] . "</td>";
echo "<td>" . $data['LATITUDE'] . "</td>";
echo "<td>" . $data['LONGITUDE'] . "</td>";
echo "<td>" . $data['DATE'] . "</td>";
echo "<td>" . $data['TIME'] . "</td>";
echo "<td>" . $data['BATTERY_mV'] . "</td>";
echo "</tr>"; // Close the table row
}
?>
</table>
<div id="map" style="width: 900px; height: 600px" align="centre" >
</p>
</body>
</html>
37
<mystyles.css>
html {
background: url(Cow.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
th,td {
opacity: 1;
text-align: center;
border: 2px solid black;
color: #000033;
padding: 2px;
font-size: 130%;
background: #ffFFff;
}
td {
border: 1px solid black;
color: #000066;
font-size: 100%;
background: #ffFFff;
}
table,
{
text-align: centre;
background: #FFFFFF;
opacity: 0.6;
}
h1 {
text-align: center;
color: white;
text-shadow:
3px 3px 0 #000,
-1px -1px 0 #000,
1px -1px 0 #000,
-1px 1px 0 #000,
1px 1px 0 #000;
font-size: 210%;
}
h2, p#p1 {
text-align: center;
border: 2px solid black;
color: #000033;
padding: 2px;
background: #ffFFff;
width:70%;
margin-left:15%;
margin-right:15%
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
38
a:link, a:visited {
display: block;
font-weight: bold;
color: #FFFFFF;
background-color: #98bf21;
width: 120px;
text-align: center;
padding: 4px;
text-decoration: none;
text-transform: uppercase;
}
div#googleMap { margin: 0 auto 0 auto; }
a:hover, a:active {
background-color: #7A991A;
}
39
<Poling_with_basic_ftp.py>
#!/usr/bin/python
import serial
import MySQLdb
import ftplib
import os
node_inventory = ["Cow_1","Cow_2","Cow_3","Cow_4"] #,"Cow_2","Cow_3","Cow_4"
# establish connection to MySQL.
dbConn = MySQLdb.connect("localhost","root","Sheskin1","asset_tracker")
print "Connecting to MYSQL database"
# open a cursor to the database
cursor = dbConn.cursor()
Device = '/dev/ttyUSB0'
ser = serial.Serial(Device, 9600, timeout=7)
index = 0
retries = 10
while 1:
Databuff = ""
# Call out to Cow
while len(Databuff) < 5:
ser.write("READ " + node_inventory[index] + "n")
print index
print "Trying to READ " + node_inventory[index] + "...n"
retries = retries - 1
if retries == 0:
print "Cannot read n",
index += 1
retries = 10
if index == len(node_inventory):
index = 0
# Read input from Serial Port
Data = ser.readline()
print Data
Databuff = Data
print "Data Recieved!"
for line in Data.splitlines(): # Process each line of code
if len(line)>0: # If there is any content in the line
term = line.split(",") # Split line of code into variables, Delimiter =
","
# If there are 6 variables, commit terms to seperate variables
if (len(term) == 6 and term[0] == node_inventory[index]):
retries = 10
index += 1
if index == len(node_inventory):
index = 0
tag_id = term[0]
latitude = term[1]
longitude = term[2]
date = term[3]
time = term[4]
battery = term [5]
40
print "The Tag Number is: " ,tag_id
print "The Latitude is: " ,latitude
print "The Longitude is: " ,longitude
print "The Date is: " ,date
print "The Time is: " ,time
print "The Battery Voltage is: " ,battery
print ""
try:
cursor.execute("INSERT INTO latlong_V2(TAG_ID, LATITUDE,
LONGITUDE, DATE, TIME, BATTERY_mV)
VALUES(%s,%s,%s,%s,%s,%s)",(term[0],term[1],term[2],term[3],term[4],term[5]))
dbConn.commit() # commit the cursor
except MySQLdb.IntegrityError:
print "failed to insert data"
print "Creating a text file with the write() method"
text_file = open("cycling_string.txt", "w")
print "file created"
text_file.write(tag_id +"," + latitude + "," + longitude + "," + date +
"," + time + "," + battery + "n")
print "written to file"
text_file.close()
print "close file"
filename = "remote_information.txt"
ftp = ftplib.FTP("ftp.donalomuiri.com")
ftp.login("donalomuirieng", "Sheskin1993!")
print "ftp logged in"
ftp.cwd("/public_html/tracker")
os.chdir(r"/home/pi/RASPBERRY_PI/python/project_files")
myfile = open("cycling_string.txt", 'r')
print "opened online file"
ftp.storlines('STOR ' + filename, myfile)
print "lines added to online file"
myfile.close()
print "file closed"
ftp.quit()
print "ftp quited"
else:
print "... data corrupt, RETRYING"
cursor.close() # close the cursor
dbConn.close()
41
<Poling_V1.ino>
#include <SoftwareSerial.h>
#include <TinyGPS++.h>
// Reserve digital pins 11 and 10 for serial connection with LoRa module
static const int LoRaRXPin = 11, LoRaTXPin = 10;
// Reserve digital pins 4 and 3 for serial connection with GPS module
static const int GPSRXPin = 4, GPSTXPin = 3;
// The serial connection to the LoRa device
SoftwareSerial LoRa(LoRaRXPin, LoRaTXPin);
// The serial connection to the GPS device
SoftwareSerial GPS(GPSRXPin, GPSTXPin);
// The TinyGPS++ object
TinyGPSPlus gps;
String Tag_ID, command, term[10];
void parseCommand();
void processMessage();
long readVcc();
int flag = 0;
void setup()
{
// Open serial communications:
Serial.begin(9600);
Tag_ID = "Cow_1";
// Start each software serial port at 9600 baud
LoRa.begin(9600);
GPS.begin(9600);
}
void loop()
{
// By default, the last intialized port is listening.
// when you want to listen on a port, explicitly select it:
LoRa.listen();
if( flag == 0)
{
LoRa.listen();
Serial.println("Data from port one:");
// while there is data coming in, read LoRa incoming
// data and send to the hardware serial port:
while(!LoRa.available()); // wait until LoRa signal is recieved
while (LoRa.available()>0)
{
char c = LoRa.read(); // read character from LoRa command
if(c == 'n')
{
parseCommand(command); // parse command at end of message
Serial.println (command); // print command to serial monitor
//If the command is "READ" and the tag matches the node in question
if((term[0] == "READ") && (term[1] == &Tag_ID[0u]))
{
Serial.println("Process Code");
flag = 1; // read from GPS module
}
command = "";
}
else
{
command += c; // add character to
}
}
}
42
// blank line to separate data from the two ports:
Serial.println();
if(flag ==1)
{
GPS.listen(); // begin listening to GPS device
Serial.println("Data from port two:");
unsigned long start = millis();
while(start + 10000 > millis()) //scan for GPS for 10 seconds
{
if (GPS.available() > 0)
{
if (gps.encode(GPS.read()))
displayInfo();
delayMicroseconds(2);
}
}
Serial.println();
flag = 0;
}
}
// Send GPS information via LoRa and SerialMonitor
void displayInfo()
{
Serial.print(Tag_ID);
LoRa.print(Tag_ID);
Serial.print(F(","));
LoRa.print(F(","));
if (gps.location.isValid())
{
Serial.print(gps.location.lat(), 6);
LoRa.print(gps.location.lat(), 6);
Serial.print(F(","));
LoRa.print(F(","));
Serial.print(gps.location.lng(), 6);
LoRa.print(gps.location.lng(), 6);
}
else
{
Serial.print(F("INVALID"));
LoRa.print(F("INVALID"));
}
if (gps.date.isValid())
{
Serial.print(F(","));
LoRa.print(F(","));
Serial.print(gps.date.day());
LoRa.print(gps.date.day());
Serial.print(F("/"));
LoRa.print(F("/"));
Serial.print(gps.date.month());
LoRa.print(gps.date.month());
Serial.print(F("/"));
LoRa.print(F("/"));
Serial.print(gps.date.year());
LoRa.print(gps.date.year());
}
else
{
Serial.print(F("INVALID"));
LoRa.print(F("INVALID"));
}
if (gps.time.isValid())
{
Serial.print(F(","));
43
LoRa.print(F(","));
if (gps.time.hour() < 10) {Serial.print(F("0")); LoRa.print(F("0"));}
Serial.print(gps.time.hour());
LoRa.print(gps.time.hour());
Serial.print(F(":"));
LoRa.print(F(":"));
if (gps.time.minute() < 10) {Serial.print(F("0")); LoRa.print(F("0"));}
Serial.print(gps.time.minute());
LoRa.print(gps.time.minute());
Serial.print(F(":"));
LoRa.print(F(":"));
if (gps.time.second() < 10) {Serial.print(F("0")); LoRa.print(F("0"));}
Serial.print(gps.time.second());
LoRa.print(gps.time.second());
}
else
{
Serial.print(F("INVALID"));
LoRa.print(F("INVALID"));
}
LoRa.print(F(","));
Serial.print(F(","));
LoRa.print( readVcc(), DEC );
Serial.print( readVcc(), DEC );
Serial.println();
LoRa.println();
delay(2000);
}
void parseCommand(String com)
{
char delimiters[] = "!:, "; // markers that split message into terms
char* valPosition;
// This initializes strtok with our string to tokenize
// &com[0u] turns the com string into a character array
valPosition = strtok(&com[0u], delimiters);
for(int i=0; i<10; i++)
{
if (valPosition != "")
{
term[i] = valPosition;
//Serial.println(term[i]);
valPosition = strtok(NULL, delimiters);
}
}
}
/*
Read VCC:
https://code.google.com/archive/p/tinkerit/wikis/SecretVoltmeter.wiki
This code takes the Value of VCC in millivolts and sends it as a string
via the LoRa Module. This is required to get an accurate reading
of the voltage applied to VCC.
*/
long readVcc()
{
// Read 1.1V reference against AVcc
// set the reference to Vcc and the measurement to the internal 1.1V reference
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Start conversion
while (bit_is_set(ADCSRA,ADSC)); // measuring
uint8_t low = ADCL; // must read ADCL first - it then locks ADCH
44
uint8_t high = ADCH; // unlocks both
long result = (high<<8) | low;
result = (1125300L / result) + 800; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
return result; // Vcc in millivolts
}
45
MySQL scripting
CREATE DATABASE asset_tracker;
USE asset_tracker;
CREATE TABLE latlong_V2
(
READING_NUM int unsigned not null auto_increment primary key,
TAG_ID varchar(20),
LATITUDE double,
LONGITUDE double,
DATE varchar(12),
TIME varchar(10),
BATTERY_mV int (4)
);
DESCRIBE latlong_V2;
INSERT INTO latlong_V2
(TAG_ID, LATITUDE, LONGITUDE, DATE, TIME, BATTERY_mV)
values("Cow_12", 53.337155, -6.266823, "15/3/2016", "20:01:40", 5000);
SELECT * FROM latlong_V2;
46
<sleep_mode_example.ino>
#include <avr/sleep.h>
/* Sleep Demo Serial
* -----------------
* Example code to demonstrate the sleep functions in an Arduino.
*
* http://playground.arduino.cc/Learning/ArduinoSleepCode
*
* use a resistor between RX and pin2. By default RX is pulled up to 5V
* therefore, we can use a sequence of Serial data forcing RX to 0, what
* will make pin2 go LOW activating INT0 external interrupt, bringing
* the MCU back to life
*
* there is also a time counter that will put the MCU to sleep after 10 secs
*
* NOTE: when coming back from POWER-DOWN mode, it takes a bit
* until the system is functional at 100%!! (typically <1sec)
*
* Copyright (C) 2006 MacSimski 2006-12-30
* Copyright (C) 2007 D. Cuartielles 2007-07-08 - Mexico DF
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
int wakePin = 2; // pin used for waking up
int sleepStatus = 0; // variable to store a request for sleep
int count = 0; // counter
void wakeUpNow() // here the interrupt is handled after wakeup
{
// execute code here after wake-up before returning to the loop() function
// timers and code using timers (serial.print and more...) will not work here.
// we don't really need to execute any special functions here, since we
// just want the thing to wake up
}
void setup()
{
pinMode(wakePin, INPUT);
Serial.begin(9600);
/* Now it is time to enable an interrupt. In the function call
* attachInterrupt(A, B, C)
* A can be either 0 or 1 for interrupts on pin 2 or 3.
*
* B Name of a function you want to execute while in interrupt A.
*
* C Trigger mode of the interrupt pin. can be:
47
* LOW a low level trigger
* CHANGE a change in level trigger
* RISING a rising edge of a level trigger
* FALLING a falling edge of a level trigger
*
* In all but the IDLE sleep modes only LOW can be used.
*/
attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
// wakeUpNow when pin 2 gets LOW
}
void sleepNow() // here we put the arduino to sleep
{
/* Now is the time to set the sleep mode. In the Atmega8 datasheet
* http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
* there is a list of sleep modes which explains which clocks and
* wake up sources are available in which sleep mode.
*
* In the avr/sleep.h file, the call names of these sleep modes are to be found:
*
* The 5 different modes are:
* SLEEP_MODE_IDLE -the least power savings
* SLEEP_MODE_ADC
* SLEEP_MODE_PWR_SAVE
* SLEEP_MODE_STANDBY
* SLEEP_MODE_PWR_DOWN -the most power savings
*
* For now, we want as much power savings as possible, so we
* choose the according
* sleep mode: SLEEP_MODE_PWR_DOWN
*
*/
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
sleep_enable(); // enables the sleep bit in the mcucr register
// so sleep is possible. just a safety pin
/* Now it is time to enable an interrupt. We do it here so an
* accidentally pushed interrupt button doesn't interrupt
* our running program. if you want to be able to run
* interrupt code besides the sleep function, place it in
* setup() for example.
*
* In the function call attachInterrupt(A, B, C)
* A can be either 0 or 1 for interrupts on pin 2 or 3.
*
* B Name of a function you want to execute at interrupt for A.
*
* C Trigger mode of the interrupt pin. can be:
* LOW a low level triggers
* CHANGE a change in level triggers
* RISING a rising edge of a level triggers
* FALLING a falling edge of a level triggers
*
* In all but the IDLE sleep modes only LOW can be used.
*/
attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
// wakeUpNow when pin 2 gets LOW
sleep_mode(); // here the device is actually put to sleep!!
// THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
48
sleep_disable(); // first thing after waking from sleep:
// disable sleep...
detachInterrupt(0); // disables interrupt 0 on pin 2 so the
// wakeUpNow code will not be executed
// during normal running time.
}
void loop()
{
// display information about the counter
Serial.print("Awake for ");
Serial.print(count);
Serial.println("sec");
count++;
delay(1000); // waits for a second
// compute the serial input
if (Serial.available()) {
int val = Serial.read();
if (val == 'S') {
Serial.println("Serial: Entering Sleep mode");
delay(100); // this delay is needed, the sleep
//function will provoke a Serial error otherwise!!
count = 0;
sleepNow(); // sleep function called here
}
if (val == 'A') {
Serial.println("Hola Caracola"); // classic dummy message
}
}
// check if it should go to sleep because of time
if (count >= 10) {
Serial.println("Timer: Entering Sleep mode");
delay(100); // this delay is needed, the sleep
//function will provoke a Serial error otherwise!!
count = 0;
sleepNow(); // sleep function called here
}
}
49

More Related Content

Similar to Daniel Murray Final Report

Computer networking-principles-bonaventure-1-30-31-otc1
Computer networking-principles-bonaventure-1-30-31-otc1Computer networking-principles-bonaventure-1-30-31-otc1
Computer networking-principles-bonaventure-1-30-31-otc1javibadi
 
Better neuroimaging data processing: driven by evidence, open communities, an...
Better neuroimaging data processing: driven by evidence, open communities, an...Better neuroimaging data processing: driven by evidence, open communities, an...
Better neuroimaging data processing: driven by evidence, open communities, an...Gael Varoquaux
 
INL-EXT-16-39808 CBP_ Design_Guidance
INL-EXT-16-39808 CBP_ Design_GuidanceINL-EXT-16-39808 CBP_ Design_Guidance
INL-EXT-16-39808 CBP_ Design_GuidanceJohanna Oxstrand
 
Fan remote control report
Fan remote control reportFan remote control report
Fan remote control reportSoung Sreynoch
 
telecentre.org start-up evaluation
telecentre.org start-up evaluation telecentre.org start-up evaluation
telecentre.org start-up evaluation April Pojman
 
CSS NC II Module : Set-up Computer Networks
CSS NC II Module : Set-up Computer NetworksCSS NC II Module : Set-up Computer Networks
CSS NC II Module : Set-up Computer NetworksEric Talamisan
 
Scalable Distributed Real-Time Clustering for Big Data Streams
Scalable Distributed Real-Time Clustering for Big Data StreamsScalable Distributed Real-Time Clustering for Big Data Streams
Scalable Distributed Real-Time Clustering for Big Data StreamsAntonio Severien
 
Report final
Report finalReport final
Report finalJim Kats
 
IPv6 readiness globally
IPv6 readiness globallyIPv6 readiness globally
IPv6 readiness globallyAPNIC
 
TOGETHER: TOpology GEneration THrough HEuRistics
TOGETHER: TOpology GEneration THrough HEuRisticsTOGETHER: TOpology GEneration THrough HEuRistics
TOGETHER: TOpology GEneration THrough HEuRisticsSubin Mathew
 
Design and Development of a Knowledge Community System
Design and Development of a Knowledge Community SystemDesign and Development of a Knowledge Community System
Design and Development of a Knowledge Community SystemHuu Bang Le Phan
 
Bike sharing android application
Bike sharing android applicationBike sharing android application
Bike sharing android applicationSuraj Sawant
 
Internet Traffic Measurement and Analysis
Internet Traffic Measurement and AnalysisInternet Traffic Measurement and Analysis
Internet Traffic Measurement and AnalysisNikolaos Draganoudis
 
Manuscrit de Doctorat_El Abdellaouy Hanane
Manuscrit de Doctorat_El Abdellaouy HananeManuscrit de Doctorat_El Abdellaouy Hanane
Manuscrit de Doctorat_El Abdellaouy HananeElabdellaouy Hanane
 
Study On 3G Data Card Usage Trends
Study On 3G Data Card Usage TrendsStudy On 3G Data Card Usage Trends
Study On 3G Data Card Usage TrendsRajesh Aluru
 

Similar to Daniel Murray Final Report (20)

Term paper
Term paperTerm paper
Term paper
 
Computer networking-principles-bonaventure-1-30-31-otc1
Computer networking-principles-bonaventure-1-30-31-otc1Computer networking-principles-bonaventure-1-30-31-otc1
Computer networking-principles-bonaventure-1-30-31-otc1
 
Better neuroimaging data processing: driven by evidence, open communities, an...
Better neuroimaging data processing: driven by evidence, open communities, an...Better neuroimaging data processing: driven by evidence, open communities, an...
Better neuroimaging data processing: driven by evidence, open communities, an...
 
INL-EXT-16-39808 CBP_ Design_Guidance
INL-EXT-16-39808 CBP_ Design_GuidanceINL-EXT-16-39808 CBP_ Design_Guidance
INL-EXT-16-39808 CBP_ Design_Guidance
 
Fan remote control report
Fan remote control reportFan remote control report
Fan remote control report
 
telecentre.org start-up evaluation
telecentre.org start-up evaluation telecentre.org start-up evaluation
telecentre.org start-up evaluation
 
CSS NC II Module : Set-up Computer Networks
CSS NC II Module : Set-up Computer NetworksCSS NC II Module : Set-up Computer Networks
CSS NC II Module : Set-up Computer Networks
 
Scalable Distributed Real-Time Clustering for Big Data Streams
Scalable Distributed Real-Time Clustering for Big Data StreamsScalable Distributed Real-Time Clustering for Big Data Streams
Scalable Distributed Real-Time Clustering for Big Data Streams
 
Thesis
ThesisThesis
Thesis
 
thesis
thesisthesis
thesis
 
Report final
Report finalReport final
Report final
 
IPv6 readiness globally
IPv6 readiness globallyIPv6 readiness globally
IPv6 readiness globally
 
FYP Thesis
FYP ThesisFYP Thesis
FYP Thesis
 
TOGETHER: TOpology GEneration THrough HEuRistics
TOGETHER: TOpology GEneration THrough HEuRisticsTOGETHER: TOpology GEneration THrough HEuRistics
TOGETHER: TOpology GEneration THrough HEuRistics
 
Design and Development of a Knowledge Community System
Design and Development of a Knowledge Community SystemDesign and Development of a Knowledge Community System
Design and Development of a Knowledge Community System
 
Bike sharing android application
Bike sharing android applicationBike sharing android application
Bike sharing android application
 
be_report - report
be_report - reportbe_report - report
be_report - report
 
Internet Traffic Measurement and Analysis
Internet Traffic Measurement and AnalysisInternet Traffic Measurement and Analysis
Internet Traffic Measurement and Analysis
 
Manuscrit de Doctorat_El Abdellaouy Hanane
Manuscrit de Doctorat_El Abdellaouy HananeManuscrit de Doctorat_El Abdellaouy Hanane
Manuscrit de Doctorat_El Abdellaouy Hanane
 
Study On 3G Data Card Usage Trends
Study On 3G Data Card Usage TrendsStudy On 3G Data Card Usage Trends
Study On 3G Data Card Usage Trends
 

Daniel Murray Final Report

  • 1. School of Electrical Engineering Systems Final Year Project, 2016 Candidate Name: Daniel Murray Student Number: C12314206 Project Title: Asset Tracking Using a Radio Network Bachelor of Engineering Technology: Electrical and Control Engineering (DT009)
  • 2. i Declaration: I declare that all work detailed within this report is entirely my own work, other than that which is otherwise referenced. This report and all work therein have not been previously submitted either in full or in part for academic accreditation; degree or award, in any other college or university. I now submit this report for assessment for my Final Year Project in the course DT009. All research conducted as been appropriately referenced using IEEE referencing. Signed:______________________________ Date:________________________________
  • 3. ii Acknowledgements: I would thank the following people for their help and support. My supervisor Michael Core, who fully supported the path that I wished to follow for this project. You always had great suggestions that made me develop my plans and were always able to explain things clearly. I enjoyed our meetings and the ideas and plans that were developed therein. My landlord Paul Byrne, for putting up with me coming in at all hours of the night and for showing a huge interest in my project. My upperclassman Glen Byrne, for first making me realise that this project was possible and giving me advice at the start of my project. My LoRa provider Forbe from AppconWireless, who provided prompt and detailed support any time I had any questions. You are a credit to your work. My classmates from DT009, who rallied together and helped each other along and made a range of many diverse projects seem like one big team effort. My mother and father, Siobhán and Macartan Murray, without whom I wouldn’t have clean clothes, free food or a place to sleep. You gave me a good rural upbringing, which brought about the inspiration for this project. My girlfriend Judy Walsh, who has listened to endless tirades, put up with me when I’m at my worst and provided endless support, advice and understanding throughout the year. I only hope I can do the same for you when it is your turn.
  • 4. iii Abstract: The original inspiration for this project came from a desire to reduce the time spent performing menial tasks on a farm and to grasp a greater understanding of how information is transferred wirelessly. This project aims to make the process of monitoring cattle more time efficient and less labour intensive by creating an asset tracking system using a radio network. The cost associated with this project is suitable for small budget applications and the long range offered by the system ensures its practicality. This system actively tracks the whereabouts of a number of tracking units. Using GPS modules and a LoRa radio network, the tracking units have the ability to determine their locations and broadcast them using radio waves. The Arduino Nano ATMega328 was selected as the controller on the tracking unit and the AppconWireless RF1276 was used to establish the LoRa Network. A Central Gateway, a Raspberry Pi 2 Model B, wirelessly poles for location information from the tracking units using the LoRa Network. This gateway stores the location history, time and date of the reading and the state of battery on each of the remote nodes. The location information is placed in both an online and offline database. The most recent values are presented on a web page where all of the nodes can be viewed on an embedded Google Map. The web page is accessible from a remote network, such that the operator can access the system when on the go.
  • 5. iv Table of Contents: DECLARATION: ...................................................................................................................................................... I ABSTRACT: ........................................................................................................................................................... II TABLE OF CONTENTS:........................................................................................................................................... III TABLE OF TABLES:................................................................................................................................................IV TABLE OF FIGURES:..............................................................................................................................................IV CHAPTER 1: INTRODUCTION: ................................................................................................................................ 1 CHAPTER 2: BACKGROUND RESEARCH: ................................................................................................................. 4 CHAPTER 3: DESIGN OF SYSTEM & IMPLEMENTATION:........................................................................................ 11 CHAPTER 4: TESTING AND RESULTS:.................................................................................................................... 19 CHAPTER 5: CONCLUSIONS & EVALUATION:........................................................................................................ 24 REFERENCES: ................................................................................................................................................... 28 APPENDICES: ...................................................................................................................................................... 30 Table of Tables: Table 1 Costs involved.....................................................................................................................11 Table 2 Terminal Window installation prompts ..............................................................................13 Table 3 Voltmeter vs. Arduino voltage readings .............................................................................20 Table 4 Test 2 Results......................................................................................................................21 Table of Figures: Figure 1 Proposed System Block Diagram........................................................................................1 Figure 2 Proposed Testing area..........................................................................................................2 Figure 3 WIFI Logo...........................................................................................................................4 Figure 4 Bluetooth logo .....................................................................................................................5 Figure 5 Zigbee Logo.........................................................................................................................6 Figure 6 AppconWireless RF1276.....................................................................................................6 Figure 7 NEO-6M-001 GPS Module.................................................................................................7 Figure 8 Raspberry Pi logo and Raspberry Pi 2 Model B..................................................................8 Figure 9 Microchip Logo and dsPIC30F4011 ...................................................................................8 Figure 10 TI logo and MSP430g2553................................................................................................9 Figure 11 Arduino Logo and Arduino Nano......................................................................................9
  • 6. v Figure 12 Gantt chart Overview.......................................................................................................11 Figure 13 Original Block Diagram of System .................................................................................12 Figure 14 Sparkfun Level Translator Breakout- PCA9306 .............................................................13 Figure 15 PL2303 to RF1276 and RF tool for RF1276...................................................................16 Figure 16 FileZilla window..............................................................................................................16 Figure 17 Online Web Page.............................................................................................................17 Figure 18 Wiring Diagram...............................................................................................................18 Figure 19 Final Block Diagram .......................................................................................................19 Figure 20 Voltmeter vs. Arduino voltage readings..........................................................................20 Figure 21 Arduino Nano Voltage Regulator....................................................................................20 Figure 22 Test 2 wiring diagram......................................................................................................21 Figure 23 Gateway node with battery pack and WiFi Dongle.........................................................23 Figure 24 Example string of information received by gateway node..............................................23 Figure 25 Operator carrying Remote node ......................................................................................23 Figure 26 Screenshot 1.....................................................................................................................24 Figure 27 Gateway node on ground.................................................................................................24 Figure 28 Screenshot 2.....................................................................................................................24 Figure 29 Screenshot 3.....................................................................................................................24 Figure 30 Screenshot 4.....................................................................................................................24 Figure 31 Screenshot 5.....................................................................................................................24 Figure 32 MQTT block diagram......................................................................................................27 Figure 33 Complete Gantt Chart......................................................................................................33
  • 7. 1 Chapter 1: Introduction: The goal of this project is to design a system for tracking the location of a herd of cattle and to contribute to the field of “Smart Agriculture”. The network will consist of remote nodes which will interact with a base station. The remote nodes will gather GPS information and use a radio network to allow transmission of data. From the base station, information gathered will be uploaded to The Cloud where the information can be accessed on an external network. The block diagram shown in Figure 1 outlines the operation of the system. Figure 1 Proposed System Block Diagram The benefits of such a project include:  A low cost network suitable for small budget applications.  The improved reaction to instances of cattle theft.  The detection of an animal that has broken out of its enclosure.  The expansion to the tracking of general assets. Being able to know exactly when a raid is occurring can allow immediate notification of the theft to the Gardaí and the farmer. Not only would this help reduce number of cattle thefts but will also help in the day to day monitoring of cattle and will also let the farmer know if a beast attempts to break out of its field or enclosure. Rural Ireland has recently seen an increase in the number of cattle thefts. One of the main issues with preventing cattle theft is the difficulty in knowing when the theft occurs and the delay in the reaction of An Garda Siochána to such thefts. This project offers an opportunity for the farmer to monitor their cattle from a remote internet connection. It is important that the project be designed in such a way that a working final product is achieved. This may involve a lower final operability of the project than that would be expected of a commercial product. The candidate should achieve a fully operational asset tracking system that transmits:  Latitude  Longitude  Tag ID  Battery level of remote node
  • 8. 2 To showcase the operability of the system, the candidate should ideally get this system working in a large open environment to represent a small farm. The goal is to actively track the end nodes, be that on a webpage local to the Central Gateway or should time permit, via the internet on a smartphone. The orange boundaries on the satellite image in Figure 2 depicts the expanse of the testing area to be simulated: Figure 2 Proposed Testing area The “Homestead” marked on the map is where the Central Gateway of the farm will be placed. This Central Gateway collects information from remote nodes within the testing area. The information will be received using radio waves; likely from the sub GHz spectrum. This Central Gateway will have a connection via WIFI/Ethernet to The Cloud, where the information retrieved from the nodes will be placed into an online database. The hardware associated with the receiving of radio signals in the Central Gateway depends on the hardware used in the remote nodes.
  • 9. 3 Using radio technology, the cattle should theoretically be traced over a short to medium length distance using Remote Radio Transmitters with incorporated microcontrollers. This project assumes the furthest distance between Remote Node and Central Gateway to be 1km, since the furthest distance to be tracked here is 820m. Since sub-GHz radio transmitters commonly have a high distance range, the candidate should use one that operates using the 400-900MHz frequency. The learning outcomes of this project include:  A good knowledge of wireless systems and how data is transferred between Central Gateway and remote node.  A better knowledge of how master and slave nodes work and the structure in which they receive, store, and transmit information between each other.  A basic knowledge of how location tracking technology operates and how to apply it to this system.  A good knowledge of how data can be stored, both on the cloud and on a local computer.  A better knowledge of domains, web directories and website hosts. Some of the boundaries of this project include:  The limited timespan of the project.  Keeping the overall cost of the project down.  How to showcase the final product.  Having a good range (1km) from end node to receiver. See “Working Area” in appendices.
  • 10. 4 Chapter 2: Background Research: Radio Technology: With the plethora of radio technology that is available today, it is important to choose the right one that suits the application of this project perfectly. To do so one must look at the key requirements of the radio network to be utilised:  Allow two-way communication between Central Gateway and remote nodes.  Have a long range (~850m).  Be low powered and require low voltage.  Be portable enough to be carried by a cow.  Be capable of transmitting simple, low data strings of information. While researching the various wireless networks that could be utilised as part of this project, it quickly became apparent that there are many systems that utilise radio technology to transfer information wirelessly. A radio frequency is formed by applying an alternating electrical current to an antenna. This alternating current produces an electromagnetic field which propagates into what is sometimes called an ‘RF Field’. Any frequency between 9 kHz and 300GHz is considered a radio frequency. What divides the different radio technologies today are the protocols and modulations used in interpreting and sending information. The use of these trademark protocols influences the price. This would make the standard radio transceiver to be cheaper than its trademarked counterparts. However, trademarked protocols have the added benefit of inherent security, reliability and well documented support. [1] WIFI: Figure 3 WIFI Logo The WiFi trademark (logo in Figure 3) represents one of the most common forms of wireless data transfer. The WiFi protocol allows electronic devices to communicate wirelessly over a Wireless Local Area Network (WLAN) connected to a high-speed internet connection. WiFi is governed by IEEE standards, namely 802.11a/b/g/n/ad/ac. These standards define the communications protocols utilised by WiFi and result in better quality of service, security and mobility. [2] WiFi offers the most expensive solution but is highly regarded in terms of security. This would make WiFi the most effective solution, were the system dealing with sensitive information, such as financial data or medical records. However, since there is no pertinent information being handled, such security measures are a luxury not a necessity. What does rule WiFi out as a potential network for this project is the range; an average of 46m indoors and 92m outdoors.
  • 11. 5 Bluetooth: Bluetooth, shown in Figure 4, is a standard of radio frequency and operates in the 2.4GHz Industrial, Scientific and Medical (ISM) band. At the time of Bluetooth’s development, transceivers in the 2.4GHz ISM band were required to employ a spread spectrum technique. Bluetooth employs a Frequency Hopping Spread Spectrum (FHSS) technique to achieve this, where the device hops randomly between 79 1MHz channels at a rate of 1600 hops per second. This frequency hopping helps to avoid conflicts which operate on the same frequency band, such as WiFi and Zigbee. [3] The Bluetooth protocol operates by pairing two or more Bluetooth nodes together. The range offered by Bluetooth devices varies with the class of device utilised. Class 1 devices offer a range of 100m, a power rating of 100mW and are used in industrial applications. Class 2 devices are the most common sort and are used in mobile phones, headphones and wireless mice. These devices have a power rating of 2.5mW and have a maximum range of 10m. Class 3 devices have a power rating of 1mA and have a range of 1m. In summary, Bluetooth devices do not offer enough range to satisfy the scope of this project. [4] Figure 4 Bluetooth logo Zigbee: In researching this project, the candidate interviewed an upperclassman, one Glen Byrne. When asked about long range radio networks, he suggested the Zigbee module, which he had utilised in his own final year project. Thus this module became a likely candidate for the project. In researching this module, it became apparent that the module is used extensively in low cost, low power wireless applications. It exhibits quite a low transfer rate; 250kB/s. Zigbees can be deployed in a mesh network configuration, which would theoretically extend the range from central master node to end node through the use of intermediary nodes. However, they can also be configured in tree cluster or star configurations, where poling between each node would allow for less information pileup and leave the receiver less vulnerable to stack overflow. The Zigbee protocol operates through Direct Sequence Spread Spectrum (DSSS) which allows the Zigbee to operate in a noisy frequency environment. Digikey produces a number of different XBee modules, each offering different ranges. For a 300ft module, it costs $24.95 from Sparkfun. For a 40 mile module, it costs $194.95. The most suitable module to be used is the XBee Pro 63mW RPSMA - Series 2B (ZigBee Mesh), which has a range of 1 mile and costs $44.95. For a radio module alone, this is too expensive when one has to consider that a tracking system must also be employed to each remote node. Thus the cost of the Xbee module proved a considerable deterrent in utilising one for the project. [5]
  • 12. 6 Figure 5 Zigbee Logo LoRa: A new form of radio modulation was developed in Semtech’s LoRa network. It consists of low power, low frequency, and long range end modules that have a range of over 15km in a suburban environment and operates in the license-free ISM frequency bands. It uses a Chirp Spread Spectrum protocol to modulate the information processed which allows it to operate in today’s radio saturated environment without noise [6]. These can act as end nodes and contain embedded Class A protocol that can connect to any LoRaWAN Gateway. It is possible to make a DIY LoRaWAN Gateway using an iC880A-SPI 868MHz concentrator. However this module costs €189.00 and is much too expensive for the sake of this project. [7] An Xbee module does not have the same range and is a lot more expensive than LoRa modules. Information on some LoRa modules can be found in the appendices of this report. The AppconWireless seems to be the most suitable LoRa module for this project. These are used extensively in the tracking of weather balloons and will provide more than enough range for the purposes of my project. With a pre soldered SubMiniture version A (SMA) connection for the attachment of an aerial. The datasheet specifies that this is a suitable module for central and end node applications. A Semtech SX1272 is integrated in the module and allows it to operate at 169/433/868/915MHz. A high speed microchip from ST controls the module. It is labelled as “easy to use” and has a “reception sensitivity of up to-148dBm”. Cost: $19.50 per module. [8] Figure 6 AppconWireless RF1276
  • 13. 7 Tracking technology: The tracking of objects usually is done in terms of latitude and longitude. A combination of both leads to a specific point on the earth. For the sake of this project, the candidate compared two forms of tracking systems. Signal Strength Telemetry: This is a land based tracking system. It involves a minimum of three fixed receivers with known location and at least one remote that needs to be located. Since the Received Signal Strength Indication (RSSI) of a transmission diminishes with distance, it is possible to measure the distance between the remote node and each stationary received. For this system to be implemented, 3 base stations would be required with radio networking installed to allow communication between each. A calibration process would be required to convert the RSSI to a distance. This system would be excessively expensive, complicated and power hungry and thus would not be suitable for this project. [9] Global Positioning Satellite (GPS): GPS is a tracking system where the unknown location of a GPS end module is found by using a number of overhead satellites with a known location. When connection is made between a number of overhead satellites and the end module, the GPS module receive location information in the form of a National Marine Electronics Association (NMEA) string and arrives in the form of American Standard Code of Information Exchange (ASCII) text. This string can then be parsed into relevant fields, such as latitude, longitude, date and time. On some of the more advanced modules, altitude can even be determined. Modules are light, cheap and widely available and would be suited for this project. These modules calculate their position by deducing its distance from visible satellites and using triangulation to calculate position. One such GPS Module is the UBlox NEO 6M module, which can be purchased at £10.99 per module from Amazon. It operates of a 5V source and draws 77mA while running. [10] Figure 7 NEO-6M-001 GPS Module Existing Radio Tracking Systems: IOTA Tracking System: IOTA is an American company which designs a similar tracking system using LoRa technology. They design remote nodes that have a range of 1-4 miles. The nodes contain temperature sensors, a GPS module, an audio alarm, a waterproof casing and a long lasting battery. The Central Gateway and one module can be purchased for $150. Any further remote nodes cost $50. This is very expensive and is not suitable for the farm industry. While this range would be suitable for the purposes of this project, The LoRa modules previously mentioned have longer distances detailed in
  • 14. 8 their respective datasheets. It would be quite possible to trump this system in terms of cost and range. [11] Types of Controller: Two forms of controller are required for this project. One controller must act as the Central Gateway. While researching it was necessary to find one that could operate as a gateway that can connect to the internet, via either WiFi or Ethernet. One main module stood out: Raspberry Pi: Figure 8 Raspberry Pi logo and Raspberry Pi 2 Model B The Raspberry Pi seemed the most logical choice since it has a plethora of information available online. It comes stocked with 4 on board USB ports, an Ethernet connection, is relatively low power (2000mA @ 5V = 10 watts). It contains an array of General Purpose Input Output (GPIO) pins, some of which can establish a Universal Asynchronous Receiver/Transmitter (UART) connection with Serial Devices. This could prove useful when dealing with information from a radio module attached to the GPIO pins to retrieve information from the remote nodes. The other form of controller must operate as the end node. It will be required to receive serial information from a GPS module and send and receive information via the selected Radio module. Three modules in which the candidate has experience in using are outlined below:  Microchip’s dsPIC  Texas Instruments MSP430  Arduino Microchip’s PIC: Figure 9 Microchip Logo and dsPIC30F4011
  • 15. 9 Microchip’s dsPIC30F4011 was used in the candidate’s Robotics module, ROBO3109. It proved to be a durable and reliable microcontroller. With 2 hardware UART ports, this chip has all the necessary communications capabilities required to communicate with both a GPS module and a radio module. It operates at between 3.0 and 5.5V, hence it would be possible to find radio and GPS modules that operate under the same voltage. This would reduce the need for a highly inefficient voltage regulator. However, there are not many libraries available for the dsPIC that would easily allow the parsing of a GPS string. This microcontroller would not be suitable for the project since the parsing of the GPS string would involve too much dedication, waste too much time and risk the overall completion of the project [12]. Texas Instruments MSP430: Figure 10 TI logo and MSP430g2553 Used in the Engineering, Practice and Design module, the MSP430 is a small microchip that would suit the compact end node proposed for the project. It operates off a 3.3V supply and consumes just 330μA when running in active mode at 1MHz with VCC at 3V (not including external current). However, the device has only one hardware serial port. This would not be suitable for communicating with both a GPS module and a radio module [13]. Arduino: Figure 11 Arduino Logo and Arduino Nano The Arduino is an open source platform. Numerous boards are available, but the Arduino Nano ATmega328 is readily available in college. This is a small, breadboard-friendly board that can easily be programmed using the Arduino IDE. Having only one serial channel on digital pins 0 (RX) and 1 (TX), this would appear to be unsuitable for the project. However, many open source libraries are available for the Arduino Nano. One of these libraries is the Software Serial library, which allows serial communication on any of the Arduino Nano’s digital pins. The Arduino operates off 7-12V applied to VCC. However, a 5V supply can be applied to the 5V pin, which bypasses the Arduino’s voltage regulator. This would match the voltages of the GPS and Radio Modules and remove the need for any voltage regulation circuits. [14]
  • 16. 10 Cloud Computing: In order to view the location information from a remote connection, it is necessary to have it on a webpage online. In order to do this, one needs to own a domain and a web hosting account. While researching possible domain hosting services, the candidate found www.domain.com. Here the candidate searched and found an unused domain name; www.donalomuiri.com. This domain was purchased for one year for $10. However, this only reserves the domain and does not allow for any server side coding, as is used by the PHP file format. This unfortunately costs a further $4.75 per month. This hosting package comes with an online MySQL Database which can be used to store past locations online, and thus was deemed a useful feature to be included in the project. In order to send files to and from the web directory of files, a third part ftp client is required. One such client, FileZilla, is free to download and allows transfer of files between the local PC and the web directory. [15]
  • 17. 11 Chapter 3: Design of System & Implementation: Project Planning: Since there is a limited time allotted to this project, it is important to use this time efficiently. In order to manage time spent at each task, the candidate used the Microsoft Project software package to plan each stage of the project and the time to be allocated to each stage Figure 12 shows a condensed version of the Gantt chart that governed the course of the project. A more complete version can be found in the Appendices section of this report in Figure 33. Figure 12 Gantt chart Overview Selected modules: Item Model Quantity Cost each Cost Arrived GPS Module Ublox NEO-6M-0-001 4 £10.99 €55.63 29/2/2016 Radio Module AppconWireless RF1276 5 $19.50 €85.31 21/3/2016 Central Gateway Raspberry Pi 2- 8GB Starter Kit 1 £51.25 €64.85 26/2/2016 End node controller Arduino Nano ATmega328 Clone 4 Was available in college USB to Serial Adapter Prolific PL2303 1 $3.00 €2.62 21/3/2016 Antennae Stubby antenna (433MHz) Wire Whip antenna (433MHz) 4 1 $2.00 $3.00 €9.62 21/3/2016 Total Cost: €218.03 Table 1 Costs involved
  • 18. 12 Table 1 constitutes the cost of one Central Gateway and four remote nodes. For the same cost, one could only buy one gateway and 3 remote nodes from the IOTA tracking company. Thus, this project shows an improvement upon an existing company’s product in terms of cost. Original Design of system: The original design of the system outlined in Figure 13 is inherent with flaws. However, it outlines a good base from which to start developing the project. Figure 13 Original Block Diagram of System This system only allows for one way communication from the end node to the Central Gateway. This model will not allow poling across all the nodes and a risk of clashing messages is present. Poling is when the Central Gateway would sequentially request information from each of the remote nodes. It also only caters for the webpage being displayed on a local network. This is beneficial in the tracking of remote nodes when in the vicinity of the base station. This is not satisfactory for the supervision of the nodes when not connected to the same local network. Configuring the Raspberry Pi: In order to operate the Raspberry Pi, one must upload an OS to it. This is done by copying the NOOBS interface onto a microSD card. This will require a computer with internet connection and a micro SD card slot. It is advised that a minimum sized microSD of 4GB formatted to FAT32 be used. NOOBS can be downloaded from www.downloads.raspberrypi.org/NOOBS_latest. This will download the version of NOOBS with the Raspbian OS preinstalled. This is quite similar to the Debian Linux package. Once the download is finished, the zip file is extracted into the root folder of the microSD card. When the extraction is complete, the card can then be safely removed from the computer and placed in the Raspberry Pi. [16] In order to setup the Raspberry Pi, one must connect a keyboard and mouse into the USB terminals. A HDMI cable must be connected between the Pi and a monitor and the micro USB power adapter must be connected. The Pi will boot up into the NOOBS menu, where you can click to install "Raspbian". This will take then take a few minutes to install, all the while following the basic prompts. On the login screen, the default user name is “pi” and the default password is “raspberry”. You will then be directed to the Raspbian desktop.
  • 19. 13 Now that Raspbian is installed, it is now time to start installing the necessary application and drivers. This is done by entering commands into the Terminal Window. It is good practice to run the following two commands before each installation: sudo apt-get update sudo apt-get upgrade This will update and upgrade all the current drivers and applications. Application Command line prompt Arduino IDE sudo apt-get install arduino MySQL sudo apt-get install mysql-server Python-mysqldb [17] Apache2 sudo apt-get install apache2 –y [18] PHP5 sudo apt-get install php5 libapache2-mod-php5 –y [18] Table 2 Terminal Window installation prompts Install the PySerial Library for Python: The Pyserial library must be installed to let the Python script recognise serial input and to write serial output to the USB device (PL2303). The simple library can be installed using the following command line prompt: -$ sudo pip install pyserial Configuring Serial Communications between Pi and RF1276: The original design of the project assumed that you could connect the UART of the LoRa module to the GPIO pins of the Raspberry Pi. However, since the UART of the AppconWireless RF1276 operates at 5V and the voltage limit of the Pi’s GPIO pins is 3.3V, a direct connection between the devices is not possible without damaging the 3.3V GPIO pins of the Pi. Thus level conversion must be used to allow UART via GPIO pins. This can through the use of a Level Translator board, which can be bought from Sparkfun for €6.58. Figure 14 Sparkfun Level Translator Breakout- PCA9306 This incurs further cost to the project which is undesirable if the project is to financially compete with the IOTA tracking system. Thus the design of the project had to be revised. Instead of using
  • 20. 14 the UART GPIO pins of the Raspberry Pi, the Prolific PL2303 USB to Serial adapter would be constantly left in USB port. This provided a more cost effective solution to the problem. Fortunately, the driver for the PL2303 comes as standard on the Raspberry Pi. What was required was to load the necessary “Kernel Module”. The Kernel is the method by which the hardware of a computer coordinates with the OS. The following steps show how to configure the adapter. Step 1: “-$ lsusb” was ran in the terminal window. This command listed all devices connected to the USB ports of the Raspberry Pi. Take note of the line containing the below information. Bus 005 Device 002: ID 067b:2303 Prolific Technology Inc. PL2303 Serial Port Step 2: Next the device information was loaded into the Kernel module by typing the following command into the terminal window. -$ sudo modprobe usbserial vendor=0x067b product=0x2303 Step 3: To confirm that the device was loaded successfully to the kernel, “-$ dmesg” was ran. The following lines appeared at the bottom of the response message: [131.747013] USB Serial support registered for pl2303 [131.747038] pl2303 5-1:1.0: >pl2303 converter detected [131.758965] usb 5-1: >pl2303 converter now attached to ttyUSB0 The Serial feed from the RF1276 was then utilised using simple “Serial.read()” commands in Python. Configuring the Arduino: In order for the Arduino to operate as intended, two user libraries were utilised. SoftwareSerial: This library is native to the Arduino Integrated Development Environment (IDE) and allows the use of any pair of digital pins to be used as a serial connection. Since there is only one hardware serial port on the Arduino Nano, the design of this system relies on the use of 2 software serial ports, one for the GPS and one for the LoRa module. The hardware serial port will be reserved for troubleshooting purposes. However, data can be received from only one software serial port at a time. Thus it is necessary to close each software serial port before another can be read. [19] TinyGPSPlus by Mikal Hart: This library is very useful in parsing an NMEA string into more user friendly variables. This will limit the amount of time spent in parsing GPS information. The package was downloaded in the form of a .zip file. In the Arduino IDE, the candidate navigated to Sketch > Include Library > Add .ZIP Library. Then the downloaded .zip file was located and selected. [20] Determining Battery Level: The Arduino Nano has a 10-bit analogue to Analogue to Digital Converter (ADC). From Nyquist’s theorem, the number of digital units available to an ADC is (2n -1), where n is the number of bits. In this case there are 1023 digital units. The ADC in question is ratiometric, where the analogue reference voltage is determined from the voltage applied to VCC. There is also a 1.1V bandgap
  • 21. 15 reference voltage in the ATMega328. When the value from the bandgap reference is compared VCC, it is possible to measure what voltage the batteries are running at. For the sake of the below equation, x represents the reading of the 1.1V reference. 𝑖𝑓 𝑉𝐶𝐶 𝑖𝑠 5𝑉: 1100 5000 × 1023 = 225 𝑎𝑛𝑑 𝑖𝑓 𝑉𝐶𝐶 𝑖𝑠 3.3𝑉: 1100 3300 × 1023 = 341 𝐺𝑒𝑛𝑒𝑟𝑎𝑙𝑙𝑦: 1100 𝑉𝐶𝐶 × 1023 = 𝑥 𝑅𝑒𝑎𝑟𝑟𝑎𝑛𝑔𝑖𝑛𝑔: 𝑉𝐶𝐶 = 1100 𝑥 × 1023 Hence by reading the value of the bandgap reference value, the voltage on VCC can be determined. The relevant code can be seen in the readVcc{} function in the Poling_V1.ino file. This script can be seen sleep_mode_example.ino in the coding section of the Appendices. [21] Configuring the LoRa Module: Since the LoRaWAN gateway was so expensive, it was decided that a poling system be utilised. This operates by assigning one of the nodes as a master. This master is in charge of sending commands out to each individual remote node. Once the information from one node is attained and processed, the master then moves on to the next node. The benefits of this mode include:  No clashing information from remote nodes bombarding the Central Gateway.  The control of a large quantity of devices.  A secure handshaking arrangement between nodes before information is processed.  A very cost effective system. In order for the LoRa modules to communicate with each other they must have the same characteristics. 433MHz antennae were purchased from AppconWireless, so it is essential that the LoRa modules are configured to reflect this. A rather low baud rate of 9600 is used for both serial and radio transmissions, such as to allow reliable readings to be taken. These settings can be configured using the “RF tool for RF1276” shown in Figure 15Error! Reference source not found.. Note that the Power setting is set to 7, the maximum transmission setting for the device. The serial communications on the Arduino should also be assigned a baud rate of 9600.
  • 22. 16 Online Web Directory: The online web directory requires having a few integral files uploaded to it from a remote computer with internet connection. Using FileZilla to establish an FTP connection, the required system files were uploaded. First a new folder had to be established called “public_html”. This folder is then set as the domain pointer. Within this folder another folder was placed called “tracker”. Here is where all online files relevant to the project are located. It is necessary to have your ftp address, provided by your hosting company. Figure 16 FileZilla window While the hosting account came with a MySQL database, it was found that the hosting company did not allow access to the database from a remote computer for security purposes. This was a huge problem, as the original plan used the local MySQL on the Raspberry Pi to upload directly into the online MySQL directory. Instead it was decided that a Python script running on the Raspberry Pi would that the incoming string of information and place the information in a text file. A File Transfer Protocol (FTP) library for Python would then upload the string into the online web directory. This Figure 15 PL2303 to RF1276 and RF tool for RF1276
  • 23. 17 Python script would also have the added benefit of inserting the incoming information into an identical offline MySQL database to have two records of the past locations of the nodes. The Python script can be found in the code section of the Appendices at the end of this document. A PHP file, entitled “txt_2_mysql.php” would then be uploaded into the “tracker” directory. This webpage operates by extracting information from the uploaded text file and inserting the information into an online MySQL database. The Sequence Query Language (SQL) code used to create this table is outlined in the Code section of the Appendices. This PHP file automatically refreshes every 5 seconds, inserting whatever data is in that text file at that moment into the MySQL database. This webpage is left running on the base station continuously. The webpage that shows the locations of the nodes is entitled “index.php”. Relevant code can be found in the Code section of the Appendices. This webpage operates by using Python script to extract the 4 most recent entries from the online MySQL database and place them in a table. Since the readings are taken in a poling format, the four most recent readings will be from each of the 4 end nodes, assuming that all nodes were within range and all readings were received. The Google Maps JavaScript API with implanted PHP takes the information from the online MySQL database and inserts it into an addMarker{} JavaScript function, where a new marker is placed on the Google Maps window on the page. Figure 17 Online Web Page
  • 24. 18 Wiring Schematic: Figure 18 shows the wiring diagram for each of the end modules and the Central Gateway. Final Block Diagram: Figure 19 shows the final block diagram. It outlines the procedure by which the locations of the end nodes are processed, sent to the Central Gateway and displayed on the online webpage. Figure 18 Wiring Diagram
  • 26. 20 Chapter 4: Testing and Results: Test 1: Measuring VCC: The goal of this test is to acquire the Vin on the Arduino Nano. Since battery’s voltage drop before they die, monitoring battery voltage gives one an indication of the charge left on a battery. It was found that this is possible by using the AVR’s internal 1.1V reference and comparing it to the voltage on the Vin terminal. This is done by pointing then ADC on the Arduino to the Vin terminal. This method negates the need for any voltage divider circuits, which consume power and reduce the life of the battery. Unfortunately, voltage higher than the output of the voltage regulator on board the Arduino Nano cannot be determined without the use of a voltage divider circuit. Meter 3.75 3.90 4.00 4.2 4.4 4.5 4.7 5 5.2 5.4 5.5 5.7 5.75 5.8 5.9 Arduino @ 1.1V 3.044 3.19 3.274 3.487 3.717 3.818 4.022 4.349 4.541 4.772 4.876 5.051 5.096 5.143 5.214 Error 0.706 0.713 0.726 0.713 0.683 0.682 0.678 0.651 0.659 0.628 0.624 0.649 0.654 0.657 0.686 Table 3 Voltmeter vs. Arduino voltage readings Figure 20 Voltmeter vs. Arduino voltage readings Analysis: The error seems to be constantly around the 0.7V mark. This would lead one to believe there is a constant volt drop between the Vin Terminal and the VCC to the Atmel chip. Looking at the Arduino schematic, a UA78M058 5V voltage regulator protects the VCC to the Atmel microprocessor. The 0.7V volt drop across the in and out terminals causes the error in the Arduino’s reading. This can be rectified by simply adding 0.7V to the Arduino’s voltage reading. 0 1 2 3 4 5 6 0 2 4 6 8 10 12 14 Voltage(V) Sample Number Meter Arduino @ 1.1V Difference Figure 21 Arduino Nano Voltage Regulator
  • 27. 21 Figure 22 Test 2 wiring diagram Test 2: Power Consumption: The function of this test is to monitor the possible states each of the modules can be placed into to conserve power. Focus will be on preserving as much functionality as is possible. If current from the battery can be reduced, the battery life will be extended. The code used to test the power consumption of the Arduino in sleep mode can be viewed in the code section of the Appendices. Equipment:  Power Supply  Ammeter  Tracking unit Analysis: With the current poling setup, the tracking nodes draw 108.7mA when receiving and 162mA when transmitting. If a reading is taken every minute and since it takes approximately 2 seconds to transmit a message, an average of 110.47mA can be taken into account. (108.7 × 58 60 ) + (162 × 2 60 ) = 110.47𝑚𝐴 Using 4 rechargeable NiMH batteries in series, with each rated at 1.2V/1300mAh, the result is a 4.8V source with 1300mAh of energy on board. Using the poling system with the timing outlined above, one can expect only 11.76 hours of tracking time. Even if the LoRa module only stayed in receiving state and never transmitted, the device would only operate for: 1300mAh 108.7mA = 11.96 hours. It was found that the most energy saving method would involve putting the Arduino to sleep, waking up every hour to send off information. The GPS module and LoRa module should have their VCCs powered by a driver chip, such as the SN754410NE for this approach. This can also be done by simply using two transistors. It was first thought that the Arduino Nano could use some of its digital pins to power the two modules. Unfortunately the digital pins have a maximum DC current limit of 40mA, hence the need for the driver chip. The SN754410NE draws an off-state current of 0.5mA. [22] This means that the device could stay in sleep mode for: Device Current RF1276 Receiving: 19.2mA RF1276 Transmitting 73mA NEO-6M GPS Module: 77mA Arduino Nano Running: 12.5mA Arduino Nano Sleeping: 4.9mA Table 4 Test 2 Results
  • 28. 22 1300𝑚𝐴ℎ (4.9 + 0.5)𝑚𝐴 = 240 ℎ𝑜𝑢𝑟𝑠 𝑜𝑟 10 𝑑𝑎𝑦𝑠 The downside of this method is that since the LoRa module is turned off by default, a poling system cannot operate. Each node blindly sends the information, regardless of the fact that information coming from another node could block the transmission. Another problem is that the GPS won’t automatically be connected to overhead satellites. It could take more than three minutes with each reading to reconnect to satellites and gather the relevant GPS information. There would also be no way to stop two modules from sending information at the one time, which would cause the Central Gateway to neglect the incoming information from one or both of the clashing end nodes. Conclusion: While the poling method is the most user friendly method, the end nodes consume too much power. The battery life under poling conditions is not suitable for long term monitoring of cattle. In order to extend the life of the remote node, it is necessary to used modules that are more power efficient. The GPS module draws 77mA when operating. If a more power efficient GPS module could be found, the overall power consumption of the end node would be greatly reduced. Alternatively putting the module into sleep mode would greatly reduce the power consumption, at the expense of user control. The end nodes still function as was intended in the design specifications. The only problem is that they would not operate for long enough to be considered practical for the purposes of this project.
  • 29. 23 Figure 24 Example string of information received by Central Gateway Figure 25 Operator carrying Remote node Test 3: Field Testing: The function of this test is to show the capabilities of the tracking system within a small open area. A convenient place to test this was on St. Stephen’s Green, Dublin. Figure 23 shows the Central Gateway attached to an external battery pack. It was connected to the internet via a WiFi hub. This shows the capability for the base station to be used remotely, so long as it has an internet connection and enough charge on the battery. For the sake of this test, only one remote node was used, since the operator could not carry more than one tracking unit and there were only enough charged batteries available for one remote node. This tracking unit is shown in Figure 25. This script had to be altered to allow the poling of only one node. This was done by deleting all but “Cow_1” from the “Node_Inventory” list. Before leaving for St. Stephen’s Green, the Raspberry Pi was connected to a monitor in the college. The Pi was turned on and Poling_with_basic_ftp.py was initiated. Figure 24 shows the python script response on the monitor. The txt_2_mysql.php web page was opened in the “Chromium” internet browser. After the Python script and web page were ran, the monitor was unplugged. The Central Gateway and tracking unit were then brought to St. Stephen’s Green. The Central Gateway was left on the ground, as is shown in Figure 27, and the index.php web page was loaded on the operator’s phone. The operator walked around Stephen’s green, allowing the GPS Coordinates to be sent back to the base station. The results of this test are shown in Figure 26 to Figure 29. Figure 23 Central Gateway with battery pack and WiFi Dongle
  • 30. 24 Figure 27 Central Gateway on ground Figure 26 Screenshot 1 Figure 31 Screenshot 3 Figure 30 Screenshot 2 Figure 29 Screenshot 5 Figure 28 Screenshot 4
  • 31. 25 Chapter 5: Conclusions & Evaluation: In concluding this project, it is necessary to ensure that all goals of the system were achieved. The radio communications between end nodes and Central Gateway were arranged in a neat fashion using a LoRa network that was tested in a large open area similar to a field and communications held constant throughout the test. While testing in college it was found that the LoRa device had some problems in communicating through walls, but this is not a great issue since the goal of the project was to communicate in an open field. A poling system was employed between Central Gateway and the remote nodes so as to reduce clashing between the remote nodes and to ensure all information was reliably processed. A timer interrupt system involving the tracking unit going to sleep was investigated and proved to be a much more power efficient design. Were there more time or people available for this project, it would have been interesting to develop this system further and test for any of the suspected clashing issues that may have arose with such a system. With the time allocated, a reliable radio network was established that would be appropriate for the tracking of cattle, albeit for a short period of time. The system in use at the moment would be more suitable for the tracking of vehicles on a farm or other workplace. This would result in having enough energy to sustain the end tracking units for a much longer period of time. The NEO-6M proved a reliable GPS module that was easily configured. This module allowed the monitoring of latitude, longitude, date and time, all the core goals that were required of the tracking system. The TinyGPSplus library allowed for a more user friendly approach to the parsing of the NMEA string. Connection to satellites proved difficult at times when there was not a clear view of the sky, but since the tracking unit is designed to operate in the open air, this was not a problem. The GPS module obtained a connection within 3 minutes when in the open air, which is sufficient for small budget applications such as this. The Arduino Nano proved to be a reliable microcontroller. In its fully operational state, it only drew 12.5mA from the supply; the most power efficient module in the system. While acknowledging that the code must specify which serial port is currently being read from, the SoftwareSerial library worked brilliantly in turning a standard pair of digital pins into a fully operational serial port. This remote node controller succeeded in maintaining communications with both the LoRa module and the GPS module, while also parsing the NMEA string into a useful format, as was shown in Figure 24. The obtaining of the battery level in millivolts proved to be a useful method of determining if the energy levels of the battery were dwindling. While there was some trouble with blocked access to the online MySQL directory, this problem was overcome through the use of an ftp Python library and a constantly running text_2_mysql.php script running on the Central Gateway. The web interface now successfully uploads the end node location information to The Cloud and is accessible from remote networks and locations. The index.php web page within the public_html/tracker directory of the www.donalomuiri.com webpage displays the node's location in a table and in a google maps window. The date, time and tag identifier can be attained by simply clicking on one of the Google Maps markers, as can be seen in Figure 28.
  • 32. 26 Given extra time, the candidate would have liked to add the following improvements to the project: Signal Strength Monitoring: It would be an improvement to introduce an RSSI process to this system to give warning if a node is out of range. By requesting information on this from the supplier, the “User Guide of RF1276” was attained. In order to request the RSSI value, the Central Gateway must first receive a message from the end node. The Arduino Nano must then send the following command via UART port to the LoRa module: 0xAF,0xAF,0x00,0x00,0xAF,0x80,0x06,0x02,0x00,0x00,0x95,0x0D,0x0A The response from the LoRa module will be in hexadecimal form: 0xAF,0xAF,0x00,0x00,0xAF,0x00,0x06,0x02,0xXX,0x00,0xCS,0x0D,0x0A The value for 0xXX will determine the relative RSSI value. This value must be converted from hexadecimal to decimal form. Then the following formula is used to determine the final RSSI value: 𝑅𝑆𝑆𝐼 = (−164 + 𝑑𝑒𝑐𝑖𝑚𝑎𝑙_𝑟𝑒𝑙𝑎𝑡𝑖𝑣𝑒_𝑅𝑆𝑆𝐼) 𝑑𝐵𝑚 Attaining the RSSI value will help determine any blind spots in the field and give the user an indication of the coverage of the radio network. [23] Improvements to the Online Tracking System: It has already been shown that the tracking system has a tendency to skip putting values into the online MySQL database due to the timing issue with the text_2_mysql.php page. One way to avoid this timing issue is to only run the txt_2_mysql.php page whenever the Remote_information.txt file is updated. If there were any further time to expand on this, it is quite possible to make a much more reliable system. Another possible improvement would be the creation of different tables for each remote node within the online MySQL database and have the txt_2_mysql.php page parsing the information in the Remote_information.txt file. This would detect which node it is from the first term in the string, and insert the information into each node’s respective table. Then the index.php file would extract the Google Maps markers from each table. This would have the effect of having the most recent location of each node being placed on the map. Message Queuing Telemetry Transport (MQTT) Protocol: A completely different method of placing IOT information onto the Internet is through the use of MQTT protocol. This is a Publish/Subscribe service, where devices can publish to a specific topic on an MQTT server, and other devices can subscribe to the messages posted into this topic. Figure 33 depicts the block diagram of the proposed MQTT system.
  • 33. 27 Figure 32 MQTT block diagram The benefit of this system is that a MySQL database is not required. Each of the different end nodes can be assigned their own topic. The webpage itself could subscribe to each of these topics and display them on a webpage similar to that which is currently being used in index.php. The most recent reading for each node could be retained by enabling the “Last Will and Testament” protocol for each topic. This would negate the need for multiple MySQL databases. The disadvantage with this method is that there is no history available for where the nodes have been before the most recent reading. This is not necessary for the scope of this project but is a nice feature that is available with the MySQL method that is being applied at present. Another disadvantage is that a hosting account would still be necessary to be able to access the webpage online. While these additions would prove beneficial to the project, they were not essential to the objectives outlined in the introduction. A fully operational asset tracking system was created using a LoRa radio network and the webpage clearly displays the information gathered by the system.
  • 34. 28 References: [1] N. Instruments, “Introduction to RF & Wireless Communications Systems,” 23 09 2015. [Online]. Available: http://www.ni.com/tutorial/3541/en/. [2] D. Beck, “Choosing RF protocols for industrial, scientific and medical applications,” EETimes, 28 05 2013. [Online]. Available: http://www.eetimes.com/document.asp?doc_id=1280890&page_number=1. [3] E. H. C. Jr., Wireless Sensor Networks- Architectures and Protocols, Florida: Auerbach Publications, 2004. [4] B. H. Ranjith Antony, Bluetooth for Java, Apress, 2008. [5] S. Electronics, “XBee Guide,” [Online]. Available: https://www.sparkfun.com/pages/xbee_guide. [6] Semtech, “Semtech's RF Tranceivers,” Semtech, [Online]. Available: http://www.semtech.com/wireless-rf/rf-transceivers/. [Accessed 01 02 2016]. [7] IMST, “iC880A-SPI – LoRaWAN Concentrator 868MHz,” [Online]. Available: http://webshop.imst.de/ic880a-spi-lorawan-concentrator-868mhz.html. [8] APPCON WIRELESS TECHNOLOGIES CO.,LTD, “RF1276 Long Distance Transceiver module V2.0,” Appcon Wireless, 12 1 2014. [Online]. Available: http://www.appconwireless.com/Uploadfiles/20160309020333595.pdf. [9] C. Mathias, “Location and tracking technologies: Understanding the technology,” Network World, 06 08 2012. [Online]. Available: http://www.networkworld.com/article/2190180/wireless/location-and-tracking-technologies- -understanding-the-technology.html. [10] U-Blox, “NEO-6 u-blox 6 GPS Modules Datasheet,” 5 12 2011. [Online]. Available: https://www.u-blox.com/sites/default/files/products/documents/NEO- 6_DataSheet_%28GPS.G6-HW- 09005%29.pdf?utm_source=en%2Fimages%2Fdownloads%2FProduct_Docs%2FNEO- 6_DataSheet_%28GPS.G6-HW-09005%29.pdf. [11] iota, “Iota GPS Tracker,” Iotera, Inc., 2005. [Online]. Available: http://www.iotatracker.com/.
  • 35. 29 [12] Microchip, “DSPIC30F4011/12 DATASHEET,” 2005. [Online]. Available: http://ww1.microchip.com/downloads/en/devicedoc/70135C.pdf. [13] T. Instruments, “MSP430G2x53 datasheet,” 05 2013. [Online]. Available: http://www.ti.com/lit/ds/symlink/msp430g2553.pdf. [14] Arduino, “Arduino Nano,” [Online]. Available: https://www.arduino.cc/en/Main/ArduinoBoardNano. [15] T. Kosse, “Filezilla Overview,” NDC Host, 09 05 2016. [Online]. Available: https://filezilla- project.org/. [16] R. P. Foundation, “Getting Started with NOOBs,” Raspberry Pi Foundation, [Online]. Available: https://www.raspberrypi.org/help/noobs-setup/. [17] http://raspberrywebserver.com/, “Using MySQL on a Raspberry Pi,” http://raspberrywebserver.com/, 10 09 2013. [Online]. Available: http://raspberrywebserver.com/sql-databases/using-mysql-on-a-raspberry-pi.html. [Accessed 12 03 2016]. [18] Raspberry Pi Foundation, “SETTING UP AN APACHE WEB SERVER ON A RASPBERRY PI,” [Online]. Available: https://www.raspberrypi.org/documentation/remote- access/web-server/apache.md. [19] Genuino, “SoftwareSerial Library,” Arduino, 2016. [Online]. Available: https://www.arduino.cc/en/Reference/SoftwareSerial. [20] M. Hart, “TinyGPSPlus,” 26 11 2013. [Online]. Available: https://github.com/mikalhart/TinyGPSPlus. [21] J.-C. Wipler, “Measuring VCC via the bandgap,” JC's Environmental Electronics, 04 05 2012. [Online]. Available: http://jeelabs.org/2012/05/04/measuring-vcc-via-the-bandgap/. [22] Texas Instruments, “SN754410 Quadruple Half-H Driver,” Texas Instruments, 1 2015. [Online]. Available: http://www.ti.com/lit/ds/symlink/sn754410.pdf. [23] Appcon Wireless Technologies Co., User Guide of RF1276 V1.0, Hong Kong: Appcon Wireless Technologies Co., 2015. [24] microchip, “microchip web,” 2005. [Online]. Available: http://ww1.microchip.com/downloads/en/DeviceDoc/70005219A.pdf.
  • 37. 31 Possible LoRa Modules Name Image Properties Cost RN2483 Standalone IC Microchip RN2483- I/RM10 3.6V LoRa Module, LoRaWAN™ Class A UART Supported Bus interfaces: UART Supply Voltage: 3.6V Dimensions: 17.8 x 26.7 x 3mm Max Temp: +85°C Min Temp: -40°C Datasheet: http://www.farnell.com/datasheets/1947946 .pdf Useful links: https://thinginnovations.uk/getting-started- with-microchip-rn2483-lorawan-modules RN2483 LoRa Long-Range Sub-GHz Transceiver Module The Microchip RN2483 Long Range LoRa™ Transceiver Module provides designers an easy-to-use LoRaWAN™ Class A protocol compliant solution for Internet of Things (IoT) applications that require low-power data communications. The RN2483 Integrates a Baseband Controller and an Application Programming Interface (API) processor, simplifying the integration of LoRa™ technology into products. General Features: On-board LoRaWAN™ Class A protocol stack ASCII command interface over UART Compact form factor 17.8 x 26.7 x 3 mm Castellated SMT pads for easy and reliable PCB mounting Device Firmware Upgrade (DFU) over UART 14 GPIO for control, status, and ADC Highly integrated module with MCU, crystal, EUI-64 Node Identity Serial EEPROM, Radio transceiver with analogue front end and matching circuitry European R&TTE Directive Assessed Radio Module RF Features: 433 MHz and 868 MHz operating frequency Programmable RF Communication Bit Rate up to 300 kbps with FSK modulation, 5468 bps with LoRa™ Technology modulation High Receiver Sensitivity: down to -148 dBm TX Power: adjustable up to +14 dBm high efficiency PA FSK, GFSK, and LoRa Technology modulation IIP3 = -11 dBm >15 km coverage in suburban environments, >5 km coverage in urban environments Radionics: Temporarily out of stock: - back order for dispatch 11-3- 2016. Delivery within 2 working days - €13.21 Farnell: Out of stock €12.27 RN2483 LoRa PICtail/PICtail Plus Board Microchip’s RN-2483-PICtail is a development board featuring the RN2483 LoRa® 433/868 MHz LoRa Module. The board gives users access to all the RN2483 Module’s UART and GPIO ports. The PICtail/PICtail Plus connector allows the RN2483 to be developed with Microchip MCU development tools such as the Explorer 16 (DM240001) and Explorer 8 (DM160228), adding LoRa technology to these platforms. Features: Microchip RN2483 Low-Power Long Range, LoRa® Technology Transceiver Module SMA connectors for 433 MHz and 868 MHz bands PIC18 MCU with In-Circuit Serial Programming (ICSP) header for custom functions Radionics: Temporarily out of stock - back order for despatch 7-3- 16, delivery within 2 working days - €58.62 Farnell: Out of Stock €59.84
  • 38. 32 Solder pads around the module for GPIOs, power pins and communication signals Supply Current measurement points On-board LDO UART traffic LEDs USB connector PICtail /PICtail Plus connection interface New RN2483 LoRa Mote Development Node RN2483 868 MHz LoRa Mote Development Node The board provides a quick and easy to use platform for demonstrating the capabilities of the RN2483. The LoRa®Mote is battery powered, providing a portable tool to demonstrate the excellent long-range capabilities of the RN2483. The interoperability with LoRaWANv1.0 compliant gateways and infrastructure can also be verified. Also demonstrated is Wireless Sensor Network communication. Telemetry provided by an on-board Ambient Light Sensor and Thermistor can be transmitted as per a user- defined schedule, or initiated on demand via button-press on the Mote. An OLED display provides feedback on connection status, sensor values, downlink data and acknowledgements. A standard USB interface is provided for connecting the Mote to a host computer. When connected, the on-board USB-to-UART bridge allows simple setup and control of the LoRaWAN™ protocol stack using the high- level ASCII command set. Features: 868 MHz High-Frequency SMA Connector 433 MHz Low-Frequency Antenna test Point Ambient Light Sensor Linear Active Thermistor (MCP9700T) OLED Display Menu Navigation Switches USB Mini-B Connector PIC18LF25K50 8-bit MCU Mote ICSP Programming Indicator LEDs Battery Powered – 2 x AAA Batteries Alternative Power Supply Option via Through- Hole Connectors Kit Contents: RN2483 868 MHz LoRa® Mote Development Node SMA Antenna USB cable Radionics: Temporarily out of stock - back order for despatch 21- 03-2016, delivery within 2 working days - €64.43 Farnell: Out of Stock - €64.42
  • 39. 33 Figure 33 Complete Gantt Chart
  • 40. 34 Coding <txt_2_mysql.php <?php // Page runs constantly on gateway computer, inserting code from the uploaded // "Remote_Information.txt" file into the "latlong_V2" table in the "asset-tracker" // online MySQL database. // http://stackoverflow.com/questions/2601349/read-a-text-file-and-transfer-contents-to-mysql-database // Opens a connection to a MySQL server $connection=mysql_connect ('donalomuirieng.domaincommysql.com', 'donalomuirieng', 'Sheskin1993!'); if (!$connection) { die('Not connected : ' . mysql_error()); } // Set the active MySQL database $db_selected = mysql_select_db("asset_tracker", $connection); if (!$db_selected) { die ('Can't use db: ' . mysql_error()); } mysql_select_db("my_database"); $result = mysql_query("LOAD DATA LOCAL INFILE 'Remote_Information.txt'" . " INTO TABLE latlong_V2 FIELDS TERMINATED BY ','"); if (!$result) { die("Could not load. " . mysql_error()); } ?> <html> <head> <meta http-equiv="refresh" content = "5"> </head> <body> <?php echo "This page inserts data from 'Remote_Information.txt' into MySQL database." ?> </body> </html>
  • 41. 35 <index.php> <?php // This is the online webpage that extracts the most recent 4 entries from the "latlong_V2" // MySQL database and inserts them into a table and into a google maps window, with latitude // and longitude governing the construction of a marker, and inserting Tag_ID, DATE and TIME // into a popup window. // http://stackoverflow.com/questions/15633604/php-mysql-google-map $conn = mysql_connect("donalomuirieng.domaincommysql.com", "donalomuirieng", "Sheskin1993!") or die(mysql_error()); mysql_select_db("asset_tracker") or die(mysql_error()); //construct a query and issue it to the database // Anything begining with a dollar sign is parsed as a variable $result = mysql_query("SELECT * FROM latlong_V2 ORDER BY READING_NUM DESC LIMIT 4") or die(mysql_error()); //Close our PHP (for now) and write our HTML page ?> <link rel="stylesheet" type="text/css" href="mystyles.css" media="screen" /> <html> <head> <title>Asset Tracker</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <meta http-equiv="refresh" content="10"> <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script> <script type="text/javascript"> // Code adapted from August Li’s var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/red.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32)); var center = null; var map = null; var currentPopup; var bounds = new google.maps.LatLngBounds(); function addMarker(lat, lng, info) { var pt = new google.maps.LatLng(lat, lng); bounds.extend(pt); var marker = new google.maps.Marker({ position: pt, icon: icon, map: map }); var popup = new google.maps.InfoWindow({ content: info }); google.maps.event.addListener(marker, "click", function() { if (currentPopup != null) { currentPopup.close(); currentPopup = null; } popup.open(map, marker); currentPopup = popup; }); google.maps.event.addListener(popup, "closeclick", function() { map.panTo(center); currentPopup = null; }); } function initMap() { map = new google.maps.Map(document.getElementById("map"), { center: new google.maps.LatLng(0, 0), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP, });
  • 42. 36 <?php $query = mysql_query("SELECT * FROM latlong_V2 ORDER BY READING_NUM DESC LIMIT 4")or die(mysql_error()); while($row = mysql_fetch_array($query)) { $name = $row['TAG_ID']; $lat = $row['LATITUDE']; $lon = $row['LONGITUDE']; $time = $row['TIME']; $date = $row['DATE']; $battery_mV = $row['BATTERY_mV']; echo("addMarker($lat, $lon, '<b>$name</b><br>$time<br>$date</b><br>$battery_mV</b>');n"); } ?> center = bounds.getCenter(); map.fitBounds(bounds); } </script> </head> <body onload="initMap()" align="centre"> <h1>Asset Tracking</h1> <p id ="p1"> latlong_V2 Table: <br> Here we retrieve the Node location records from the `latlong_V2` table. </p> <p align="center"> <table border="1" width="750px" align="centre" cellpadding="3"> <tr> <th>Sample Number</th> <th>Tag ID</th> <th>Latitude</th> <th>Longitude</th> <th>Date</th> <th>Time</th> <th>Battery (mV)</th> </tr> <?php // Now use a PHP while loop to output data as HTML table rows while($data = mysql_fetch_array( $result )) // Retrieve each row in $result & store it in the array '$data' { echo "<tr>"; // HTML command to start a table row echo "<td>" . $data['READING_NUM'] ."</td> "; echo "<td>" . $data['TAG_ID'] . "</td>"; echo "<td>" . $data['LATITUDE'] . "</td>"; echo "<td>" . $data['LONGITUDE'] . "</td>"; echo "<td>" . $data['DATE'] . "</td>"; echo "<td>" . $data['TIME'] . "</td>"; echo "<td>" . $data['BATTERY_mV'] . "</td>"; echo "</tr>"; // Close the table row } ?> </table> <div id="map" style="width: 900px; height: 600px" align="centre" > </p> </body> </html>
  • 43. 37 <mystyles.css> html { background: url(Cow.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } th,td { opacity: 1; text-align: center; border: 2px solid black; color: #000033; padding: 2px; font-size: 130%; background: #ffFFff; } td { border: 1px solid black; color: #000066; font-size: 100%; background: #ffFFff; } table, { text-align: centre; background: #FFFFFF; opacity: 0.6; } h1 { text-align: center; color: white; text-shadow: 3px 3px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000; font-size: 210%; } h2, p#p1 { text-align: center; border: 2px solid black; color: #000033; padding: 2px; background: #ffFFff; width:70%; margin-left:15%; margin-right:15% } ul { list-style-type: none; margin: 0; padding: 0; }
  • 44. 38 a:link, a:visited { display: block; font-weight: bold; color: #FFFFFF; background-color: #98bf21; width: 120px; text-align: center; padding: 4px; text-decoration: none; text-transform: uppercase; } div#googleMap { margin: 0 auto 0 auto; } a:hover, a:active { background-color: #7A991A; }
  • 45. 39 <Poling_with_basic_ftp.py> #!/usr/bin/python import serial import MySQLdb import ftplib import os node_inventory = ["Cow_1","Cow_2","Cow_3","Cow_4"] #,"Cow_2","Cow_3","Cow_4" # establish connection to MySQL. dbConn = MySQLdb.connect("localhost","root","Sheskin1","asset_tracker") print "Connecting to MYSQL database" # open a cursor to the database cursor = dbConn.cursor() Device = '/dev/ttyUSB0' ser = serial.Serial(Device, 9600, timeout=7) index = 0 retries = 10 while 1: Databuff = "" # Call out to Cow while len(Databuff) < 5: ser.write("READ " + node_inventory[index] + "n") print index print "Trying to READ " + node_inventory[index] + "...n" retries = retries - 1 if retries == 0: print "Cannot read n", index += 1 retries = 10 if index == len(node_inventory): index = 0 # Read input from Serial Port Data = ser.readline() print Data Databuff = Data print "Data Recieved!" for line in Data.splitlines(): # Process each line of code if len(line)>0: # If there is any content in the line term = line.split(",") # Split line of code into variables, Delimiter = "," # If there are 6 variables, commit terms to seperate variables if (len(term) == 6 and term[0] == node_inventory[index]): retries = 10 index += 1 if index == len(node_inventory): index = 0 tag_id = term[0] latitude = term[1] longitude = term[2] date = term[3] time = term[4] battery = term [5]
  • 46. 40 print "The Tag Number is: " ,tag_id print "The Latitude is: " ,latitude print "The Longitude is: " ,longitude print "The Date is: " ,date print "The Time is: " ,time print "The Battery Voltage is: " ,battery print "" try: cursor.execute("INSERT INTO latlong_V2(TAG_ID, LATITUDE, LONGITUDE, DATE, TIME, BATTERY_mV) VALUES(%s,%s,%s,%s,%s,%s)",(term[0],term[1],term[2],term[3],term[4],term[5])) dbConn.commit() # commit the cursor except MySQLdb.IntegrityError: print "failed to insert data" print "Creating a text file with the write() method" text_file = open("cycling_string.txt", "w") print "file created" text_file.write(tag_id +"," + latitude + "," + longitude + "," + date + "," + time + "," + battery + "n") print "written to file" text_file.close() print "close file" filename = "remote_information.txt" ftp = ftplib.FTP("ftp.donalomuiri.com") ftp.login("donalomuirieng", "Sheskin1993!") print "ftp logged in" ftp.cwd("/public_html/tracker") os.chdir(r"/home/pi/RASPBERRY_PI/python/project_files") myfile = open("cycling_string.txt", 'r') print "opened online file" ftp.storlines('STOR ' + filename, myfile) print "lines added to online file" myfile.close() print "file closed" ftp.quit() print "ftp quited" else: print "... data corrupt, RETRYING" cursor.close() # close the cursor dbConn.close()
  • 47. 41 <Poling_V1.ino> #include <SoftwareSerial.h> #include <TinyGPS++.h> // Reserve digital pins 11 and 10 for serial connection with LoRa module static const int LoRaRXPin = 11, LoRaTXPin = 10; // Reserve digital pins 4 and 3 for serial connection with GPS module static const int GPSRXPin = 4, GPSTXPin = 3; // The serial connection to the LoRa device SoftwareSerial LoRa(LoRaRXPin, LoRaTXPin); // The serial connection to the GPS device SoftwareSerial GPS(GPSRXPin, GPSTXPin); // The TinyGPS++ object TinyGPSPlus gps; String Tag_ID, command, term[10]; void parseCommand(); void processMessage(); long readVcc(); int flag = 0; void setup() { // Open serial communications: Serial.begin(9600); Tag_ID = "Cow_1"; // Start each software serial port at 9600 baud LoRa.begin(9600); GPS.begin(9600); } void loop() { // By default, the last intialized port is listening. // when you want to listen on a port, explicitly select it: LoRa.listen(); if( flag == 0) { LoRa.listen(); Serial.println("Data from port one:"); // while there is data coming in, read LoRa incoming // data and send to the hardware serial port: while(!LoRa.available()); // wait until LoRa signal is recieved while (LoRa.available()>0) { char c = LoRa.read(); // read character from LoRa command if(c == 'n') { parseCommand(command); // parse command at end of message Serial.println (command); // print command to serial monitor //If the command is "READ" and the tag matches the node in question if((term[0] == "READ") && (term[1] == &Tag_ID[0u])) { Serial.println("Process Code"); flag = 1; // read from GPS module } command = ""; } else { command += c; // add character to } } }
  • 48. 42 // blank line to separate data from the two ports: Serial.println(); if(flag ==1) { GPS.listen(); // begin listening to GPS device Serial.println("Data from port two:"); unsigned long start = millis(); while(start + 10000 > millis()) //scan for GPS for 10 seconds { if (GPS.available() > 0) { if (gps.encode(GPS.read())) displayInfo(); delayMicroseconds(2); } } Serial.println(); flag = 0; } } // Send GPS information via LoRa and SerialMonitor void displayInfo() { Serial.print(Tag_ID); LoRa.print(Tag_ID); Serial.print(F(",")); LoRa.print(F(",")); if (gps.location.isValid()) { Serial.print(gps.location.lat(), 6); LoRa.print(gps.location.lat(), 6); Serial.print(F(",")); LoRa.print(F(",")); Serial.print(gps.location.lng(), 6); LoRa.print(gps.location.lng(), 6); } else { Serial.print(F("INVALID")); LoRa.print(F("INVALID")); } if (gps.date.isValid()) { Serial.print(F(",")); LoRa.print(F(",")); Serial.print(gps.date.day()); LoRa.print(gps.date.day()); Serial.print(F("/")); LoRa.print(F("/")); Serial.print(gps.date.month()); LoRa.print(gps.date.month()); Serial.print(F("/")); LoRa.print(F("/")); Serial.print(gps.date.year()); LoRa.print(gps.date.year()); } else { Serial.print(F("INVALID")); LoRa.print(F("INVALID")); } if (gps.time.isValid()) { Serial.print(F(","));
  • 49. 43 LoRa.print(F(",")); if (gps.time.hour() < 10) {Serial.print(F("0")); LoRa.print(F("0"));} Serial.print(gps.time.hour()); LoRa.print(gps.time.hour()); Serial.print(F(":")); LoRa.print(F(":")); if (gps.time.minute() < 10) {Serial.print(F("0")); LoRa.print(F("0"));} Serial.print(gps.time.minute()); LoRa.print(gps.time.minute()); Serial.print(F(":")); LoRa.print(F(":")); if (gps.time.second() < 10) {Serial.print(F("0")); LoRa.print(F("0"));} Serial.print(gps.time.second()); LoRa.print(gps.time.second()); } else { Serial.print(F("INVALID")); LoRa.print(F("INVALID")); } LoRa.print(F(",")); Serial.print(F(",")); LoRa.print( readVcc(), DEC ); Serial.print( readVcc(), DEC ); Serial.println(); LoRa.println(); delay(2000); } void parseCommand(String com) { char delimiters[] = "!:, "; // markers that split message into terms char* valPosition; // This initializes strtok with our string to tokenize // &com[0u] turns the com string into a character array valPosition = strtok(&com[0u], delimiters); for(int i=0; i<10; i++) { if (valPosition != "") { term[i] = valPosition; //Serial.println(term[i]); valPosition = strtok(NULL, delimiters); } } } /* Read VCC: https://code.google.com/archive/p/tinkerit/wikis/SecretVoltmeter.wiki This code takes the Value of VCC in millivolts and sends it as a string via the LoRa Module. This is required to get an accurate reading of the voltage applied to VCC. */ long readVcc() { // Read 1.1V reference against AVcc // set the reference to Vcc and the measurement to the internal 1.1V reference ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); delay(2); // Wait for Vref to settle ADCSRA |= _BV(ADSC); // Start conversion while (bit_is_set(ADCSRA,ADSC)); // measuring uint8_t low = ADCL; // must read ADCL first - it then locks ADCH
  • 50. 44 uint8_t high = ADCH; // unlocks both long result = (high<<8) | low; result = (1125300L / result) + 800; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000 return result; // Vcc in millivolts }
  • 51. 45 MySQL scripting CREATE DATABASE asset_tracker; USE asset_tracker; CREATE TABLE latlong_V2 ( READING_NUM int unsigned not null auto_increment primary key, TAG_ID varchar(20), LATITUDE double, LONGITUDE double, DATE varchar(12), TIME varchar(10), BATTERY_mV int (4) ); DESCRIBE latlong_V2; INSERT INTO latlong_V2 (TAG_ID, LATITUDE, LONGITUDE, DATE, TIME, BATTERY_mV) values("Cow_12", 53.337155, -6.266823, "15/3/2016", "20:01:40", 5000); SELECT * FROM latlong_V2;
  • 52. 46 <sleep_mode_example.ino> #include <avr/sleep.h> /* Sleep Demo Serial * ----------------- * Example code to demonstrate the sleep functions in an Arduino. * * http://playground.arduino.cc/Learning/ArduinoSleepCode * * use a resistor between RX and pin2. By default RX is pulled up to 5V * therefore, we can use a sequence of Serial data forcing RX to 0, what * will make pin2 go LOW activating INT0 external interrupt, bringing * the MCU back to life * * there is also a time counter that will put the MCU to sleep after 10 secs * * NOTE: when coming back from POWER-DOWN mode, it takes a bit * until the system is functional at 100%!! (typically <1sec) * * Copyright (C) 2006 MacSimski 2006-12-30 * Copyright (C) 2007 D. Cuartielles 2007-07-08 - Mexico DF * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ int wakePin = 2; // pin used for waking up int sleepStatus = 0; // variable to store a request for sleep int count = 0; // counter void wakeUpNow() // here the interrupt is handled after wakeup { // execute code here after wake-up before returning to the loop() function // timers and code using timers (serial.print and more...) will not work here. // we don't really need to execute any special functions here, since we // just want the thing to wake up } void setup() { pinMode(wakePin, INPUT); Serial.begin(9600); /* Now it is time to enable an interrupt. In the function call * attachInterrupt(A, B, C) * A can be either 0 or 1 for interrupts on pin 2 or 3. * * B Name of a function you want to execute while in interrupt A. * * C Trigger mode of the interrupt pin. can be:
  • 53. 47 * LOW a low level trigger * CHANGE a change in level trigger * RISING a rising edge of a level trigger * FALLING a falling edge of a level trigger * * In all but the IDLE sleep modes only LOW can be used. */ attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function // wakeUpNow when pin 2 gets LOW } void sleepNow() // here we put the arduino to sleep { /* Now is the time to set the sleep mode. In the Atmega8 datasheet * http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35 * there is a list of sleep modes which explains which clocks and * wake up sources are available in which sleep mode. * * In the avr/sleep.h file, the call names of these sleep modes are to be found: * * The 5 different modes are: * SLEEP_MODE_IDLE -the least power savings * SLEEP_MODE_ADC * SLEEP_MODE_PWR_SAVE * SLEEP_MODE_STANDBY * SLEEP_MODE_PWR_DOWN -the most power savings * * For now, we want as much power savings as possible, so we * choose the according * sleep mode: SLEEP_MODE_PWR_DOWN * */ set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here sleep_enable(); // enables the sleep bit in the mcucr register // so sleep is possible. just a safety pin /* Now it is time to enable an interrupt. We do it here so an * accidentally pushed interrupt button doesn't interrupt * our running program. if you want to be able to run * interrupt code besides the sleep function, place it in * setup() for example. * * In the function call attachInterrupt(A, B, C) * A can be either 0 or 1 for interrupts on pin 2 or 3. * * B Name of a function you want to execute at interrupt for A. * * C Trigger mode of the interrupt pin. can be: * LOW a low level triggers * CHANGE a change in level triggers * RISING a rising edge of a level triggers * FALLING a falling edge of a level triggers * * In all but the IDLE sleep modes only LOW can be used. */ attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function // wakeUpNow when pin 2 gets LOW sleep_mode(); // here the device is actually put to sleep!! // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
  • 54. 48 sleep_disable(); // first thing after waking from sleep: // disable sleep... detachInterrupt(0); // disables interrupt 0 on pin 2 so the // wakeUpNow code will not be executed // during normal running time. } void loop() { // display information about the counter Serial.print("Awake for "); Serial.print(count); Serial.println("sec"); count++; delay(1000); // waits for a second // compute the serial input if (Serial.available()) { int val = Serial.read(); if (val == 'S') { Serial.println("Serial: Entering Sleep mode"); delay(100); // this delay is needed, the sleep //function will provoke a Serial error otherwise!! count = 0; sleepNow(); // sleep function called here } if (val == 'A') { Serial.println("Hola Caracola"); // classic dummy message } } // check if it should go to sleep because of time if (count >= 10) { Serial.println("Timer: Entering Sleep mode"); delay(100); // this delay is needed, the sleep //function will provoke a Serial error otherwise!! count = 0; sleepNow(); // sleep function called here } }
  • 55. 49