Upload
hj43us
View
412
Download
5
Tags:
Embed Size (px)
Citation preview
Final Year Project
“The development and implementation
of a wireless multi hop sensor
network”
By: Rasmus Thielke
Project supervisor: Dr. Miguel Sánchez
I
Table of contents
1 Introduction and motivation 1
2 Definition of a wireless sensor network 4
3 System planning and technology 6
3.1 Hardware components 7 3.1.1 Arduino Pro Mini 7 3.1.2 XBee wireless module 8
3.2 Network nodes 9
4 Applied network technology 10
4.1 IEEE 802.15.4 protocol standard 10 4.1.1 Frequencies 12 4.1.2 Addressing 12
4.1.2.1 64 bit long fixed, unique addresses 12 4.1.2.2 16 bit addresses which can be configured manually 12
4.1.3 Network setup 13 4.1.4 Topologies 13
4.1.4.1 Star topology 13 4.1.4.2 Cluster tree topology: 14
4.2 Zigbee standard: 15 4.2.1 Transfer methods 16
4.2.1.1 Asynchronous unslotted mode 16 4.2.1.2 Synchronous slotted mode 16
4.2.2 Network topology 17 4.2.2.1 Peer to peer topology 17
4.3 Structure of the sensor network 18 4.3.1 The tree network topology 19
4.4 Network communication based on the XBee module 20 4.4.1 Modes of operation 20
4.4.1.1 Transparent operation: 20 4.4.1.2 API Operation 20
4.4.1.2.1 Transmit request frame: 21 4.4.1.2.2 Receive frame 22 4.4.1.2.3 Character escaping 24
4.4.1.3 Additional features 25 4.4.1.4 XBee retries 25 4.4.1.5 CSMA/CA 25 4.4.1.6 Clear Channel Assessment (CCA) threshold 26 4.4.1.7 Packetization timeout 26 4.4.1.8 Security feature 26
5 Software development 27
5.1 Simulation of software components 27
5.2 The routing algorithm 28 5.2.1 Mode of operation of the routing algorithm 29
5.2.1.1 Finite state diagram of the routing and forwarding algorithm 31 5.2.2 Protection against routing loops 32
II
5.3 Development of additional features 34 5.3.1 Message transmission 34
5.3.1.1 Beacon messages 35 5.3.1.1.1 Structure of a beacon message 35
5.3.1.2 Data messages 38 5.3.1.2.1 Structure of a data message 38
5.3.2 Addressing of the sensor nodes 40 5.3.3 Power management 40
5.3.3.1 Power saving - radio transceiver 41 5.3.3.2 Power saving - micro controller 43
5.3.4 Coordination of sleep states 50 5.3.4.1 Route updates affected by sleep states 51 5.3.4.2 Healing mechanisms affected by the sleep states 53 5.3.4.3 Self clocking feature of the network 53
5.3.5 Remote network configuration 55 5.3.5.1 Software parameters 55 5.3.5.2 Remote configuration of the radio transmitters 56
5.3.6 Network load balancing 57 5.3.6.1 Analyzing different approaches 60
5.3.6.1.1 The round robin method: 60 5.3.6.1.2 Alternating predecessor selection 61 5.3.6.1.3 Load balancing depending on load 62
5.3.7 Data aggregation 65 5.3.8 Duplicate packet detection 69
6 Transmission reliability 70
6.1 CSMA/CA (Carrier sense media access / collision avoidance) 71
6.2 Acknowledgements 72
6.3 Checksumming 72
6.4 Flow control 75 6.4.1 Overflow due to CSMA/CA backoff 75 6.4.2 Overflow due to acknowledgements 75 6.4.3 Flow control system and data buffers 77
6.4.3.1 XBee Module 77 6.4.3.2 Atmega168 78
7 Network monitoring 79
7.1 Network visualization 79 7.1.1 The communication module: 79 7.1.2 The statistics module: 79 7.1.3 The visualization module: 79
7.1.3.1 Network map 80
8 System tests and analysis 81
8.1 Section 1 - Reliability Test 82
8.2 CSMA/CA - backoff exponent adaptation 84
8.3 Throughput test - all to one 85
8.4 Forwarding chain - throughput test 86
8.5 Tree - load balancer test 87
8.6 Reaction to node breakdowns 89
III
8.7 Energy consumption 91
9 Program code and explanations 94
9.1 The setup method 94
9.2 The sleep function 96
9.3 API frame 98
9.4 The message identification and processing 100
9.5 The predecessor candidate collection process 102
9.6 Static mode 103
9.7 Dynamic mode: 104
9.8 The predecessor selection 105
9.9 Self clocking 107
9.10 Packet aggregation 108
9.11 API frame construction 109
9.12 Flow control system 111
9.13 Unescape process of incoming characters 111
9.14 Data message assembly 113
9.15 The main loop 114
10 Setup Manual 117
11 Conclusions 118
12 Appendix 120
A) Arduino pro circuit schematic 120
B) Xbee module schematic and pin declaration 121
C) Wiring diagram - sensor node 122
13 Bibliography 123
14 Figure Index 125
1
1 Introduction and motivation In this paper the development of a wireless self-organizing multi hop network
will be addressed. The network technology will be applied on a wireless
sensor network which is built up of multiple network nodes. The aim of this
work is the implementation of an efficient algorithm that will independently
setup the infrastructure and keep the network running efficiently, moreover
providing the required features in terms of reliability and low energy
consumption. The requirements are that each network node has to be able to
transmit its data although it is not in direct range of the base station using
other neighbour nodes to forward the data.
Beside their actual work, which is the transmission of sensor data, the
wireless sensor nodes will be configured with a routing functionality. This will
allow to forward data packets that come from other nodes through the network
to their final destination. Another important topic that will be covered in this
report is energy consumption. It will be tried to run the network as energy
efficient as possible without affecting the regular reliable operation of the
network.
Nowadays the importance and need of wireless sensor networks has rapidly
increased. During past years, research in this field has become more and
more important. New innovations and the fast development of the
semiconductor industry opened new possibilities for these networks.
The areas of use of these networks cover a wide range of applications and
the operating conditions have become very different. They reach from the
monitoring of single machines to buildings or big plants, military and medical
uses, up to offshore applications in the ocean1. Additionally, in the field of
medical purposes, investigations are in progress2. Due to research and
improvements at the production side, the sensors become smaller, more
intelligent and cheaper. That is why monitoring with sensor nodes that work
1 ftp://ftp.cordis.europa.eu/pub/fp7/ict/docs/sustainable growth/workshops/workshop- 20070531-jwachter_en.pdf 2 http://www.cs.virginia.edu/papers/d2h206-health.pdf
2
wirelessly gets more attractive as the research for smart devices is
continuously in progress.
Sensor networks normally consist of several interconnected sensor nodes that
read the data from attached sensors and transmit them to a central
processing station. There the data will be analyzed and processed.
When analyzing the different working environments of a sensor node, different
factors have to be put into consideration. Many fields of operation require
transmitting the measured data over long distances, or different nodes are
positioned in a place where it is difficult to transmit radio signals without loss
over long distances. For example, underground or in buildings with thick walls.
While finding approaches to these problems, an important fact that always
has to be considered is the power consumption of the wireless sensor
transmitters. The transmitters often use batteries as a power supply and if
once installed it is difficult to maintain this devices in their working
environment in case the batteries have to be changed. Therefore there is still
a demand to develop systems that have the necessary feature set and offer
low power consumption at the same time. Although there are fields of
application where alternative power supplies like solar power could be used,
in many areas this is not always possible. To overcome a long independent
operating time, it is absolutely necessary to reduce the energy consumption
as much as possible. There are not many systems available in the market that
can be easily deployed and that offer the required functionality. Therefore the
need of a system that fulfills the requirements that are mentioned above is
definitely present.
These reasons are the motivation for this project and possible solutions for
them will be addressed following. To solve the problem of a large distance
transmission, a multi-hop network where each network node works as router
at the same time to forward the data to another node that is closer to the
destination is an interesting approach to answer that problem. Of course when
applying that feature to a system it is required that the path finding and
forwarding algorithm works efficiently and manages its route determination on
its own without the need of any outer influence.
The determination of the shortest way has to work automatically and at the
same time achieving reliable data transmission, keeping the possibility of data
3
loss as low as possible. Using a self organizing multi hop network extends the
normal feature set of a sensor node beside the normal operation. A node has
to run additional algorithms to determine the path and to forward the packets
through the network. Of course these results are on the one hand more work
for a single node, but on the other hand transmission power doesn't have to
be that high. In certain conditions, transmission power could be even lower,
because the distances between nodes that forward traffic could be less than
in a simple node-base station transmission.
The use of a mesh network architecture has additionally the advantage that if
one node that forwards traffic fails, another node in range could be used as a
redundant backup route. This approach guarantees a certain amount of
system stability. And if the routing algorithm has a load balancing feature it will
be achieved that all nodes in the network, that forward traffic are equally
charged with a regulated load of traffic. These requirements and the
interesting interaction of the different features and components is the
occasion of this project. The project goals are to develop a system that offers
the required feature set and that will be ready to be applied.
4
2 Definition of a wireless sensor network
A sensor network in general is a compound of multiple so called sensor
nodes. A sensor node consists normally of a processor unit, memory, a
communication interface, different attached sensors and a power supply.
These components are interconnected with each other and form a micro
computer unit that works as an active participant in the network. It processes
the sensor values and transmits the data through the network. The different
sensor nodes create a communication network that is similar to a regular
computer network. The sensor nodes communicate with each other to
exchange data and network control information. An example of a network like
this is shown in the figure above:
Figure 1: A wireless sensor network
The communication is carried out and controlled by several network protocols.
Some of them are specialized for the use in sensor networks, like for example
the IEE 802.15.4 standard3.
3 http://www.ieee802.org/15/pub/TG4.html
5
The interconnection of the different sensor nodes can be done through a
wired or wireless connection, but the fields of use of a sensor network
normally require a wireless communication. Sometimes it is impossible to
interconnect the nodes by cable with each other, and sometimes it is much
more comfortable to setup a wireless network. The nodes just have to be put
into their position without the need of doing additional work. There are several
possible network structures to setup a sensor network that will be presented
in this report. Some are built up simply but other more complex and efficient
setups require additional control, like routing and forwarding algorithms to
control the network.
Like in other computer networks, several communication control mechanisms
can help to reduce the risk of a possible data loss in sensor networks. This is
especially important when a shared media is used, like in the presented
wireless network. Some purposes require an exact timing to assign certain
measurements to a specific time. Therefore the synchronization of a network
like this has a significant importance. The task of such a sensor network is to
deliver the sensor data efficiently to a certain destination where the further
processing of the data is realized.
6
3 System planning and technology The first step when developing a system like this is to analyze the
requirements that the system has to fulfill. Then the possibilities to achieve
these requirements have to be theoretically analyzed and to be compared
with each other. This process has to be done for both, the hardware and the
software side to guarantee that no hardware limitations avoid the correct work
flow of the software.
The purpose of the development process in this project is to implement a
multi-hop sensor network whose infrastructure is based on several
homogenous network nodes. Each node will be able to forward data from
other nodes to the destination. This development process includes the
assembly of the hardware components and the implementation of the
software algorithms to achieve the desired functionality.
Due to the fact that this system has got a high level of complexity, it is
absolutely necessary to perform different tests in a simulator before applying it
on the real devices. In a software simulation the behavior can be studied and
it is easier to apply changes on the program code in the simulator than
performing changes in the real system. Several scenarios can be simulated
and the reaction of the system can be analyzed and optimized. When the
simulation passes all the tests and the system behaves like expected, the
implementation can be done on the hardware.
Unfortunately, also after passing all the tests in the simulation environment,
when implementing the software code on the devices errors still can occur.
Therefore all the tests have to be repeated on the real system. To see how
the system behaves after longer times of operation, also long time tests have
to be done to check for possible errors that occur after a certain uptime. When
the system works as desired, the set of functionality will be documented and a
user manual will be written to inform the end user how to setup and maintain
the system.
7
3.1 Hardware components
The hardware that is used for the sensor devices is based on the ARDUINO4
platform, whose documentation is available as open source and open
hardware project. This has got the advantage of whole sources and layouts
that are freely available for the public. Additionally this project is supported by
a big user community, this is a big advantage in case that advice is needed or
problems occur. There are several different hardware designs available. For
the realization of this project, the smallest and most energy efficient layout
has been chosen -The ARDUINO PRO MINI board, which can be seen in the
following figure.
3.1.1 Arduino Pro Mini
Figure 2: Arduino pro mini board 5
The sensor node is built up by a processor board that is equipped with an
Atmel ATMEGA1686 micro controller (black chip in the center of the circuit
board) that has 6 analog inputs and 14 digital I/O pins. Additionally to this, it
offers a set of power saving features to reduce the power consumption when
the processor is not needed. The micro controller can be easily programmed
with a C and C++ based programming language. A programming environment
which includes the possibility to upload the code via a serial connection to the
4 http://www.arduino.cc/ 5 http://arduino.cc/en/Main/ArduinoBoardProMini 6 http://www.atmel.com/dyn/resources/prod_documents/doc2545.pdf
8
board is available through the website of the ARDUINO project. A schematic
of the whole board is attached to this report in the appendix.
As data transmission unit, a Maxstream XBee7 wireless modem is used:
3.1.2 XBee wireless module
Figure 3: XBee module This device can be easily connected to the micro controller via a serial
connection. This module supports the Zigbee protocol stack that is based on
the IEEE 802.15.4 standard, which offers a sufficient set of features to
achieve an efficient data transmission. It also has got the advantage of
several sleep modes that are available to reduce power consumption while
the device is not in use. The manufacturer specifies this module with a
maximum transmission range of 100m outdoors and 30m indoors. A similar
module with a higher transmission range, the XBee pro module, is available,
too, but the higher range is at the expense of the power consumption which
would be with 227mA: definitely too high for the used power supply which is
two AA sized Alkaline batteries. The module shown above only consumes
about 50mA while transmitting. Therefore it is more attractive for this project,
which has also the aim of keeping the power consumption as low as possible.
7 http://www.digi.com/products/wireless/point-multipoint/xbee-series1-module.jsp
9
To build up a network node, both devices will be combined and
interconnected:
3.2 Network nodes
Figure 4: Prototype, powered by two 1.5 Alkaline ba tteries
Figure 5: Sensor nodes with base station in the mid dle
10
4 Applied network technology Before the development of the system will be described, an overview and the
necessary background information of the network technology will be given.
The network communication and the used standards, which are the IEEE
802.15.4 and the Zigbee standard, will be described in the following
paragraphs:
4.1 IEEE 802.15.4 protocol standard
The IEEE 802.15.4 standard describes a transfer protocol stack for wireless
personal area networks (WPAN). This standard specifies the first 2 layers of
the OSI 7 layer reference model8.
It was designed for wireless networks, where a small energy consumption has
the highest priority and where high data transfer rates are not needed. While
implementing this protocol standard, the developers were always considering
the fact that the protocol has to be able to be implemented easily and does
not require complex and powerful hardware. It was designed to run on simple,
cheap, low energy consuming devices which do not offer a high level of
performance.
The first of the two specified layers is the physical layer, it is the closest layer
to the hardware. It implements the part of the direct interaction with the radio
transceiver. It activates or deactivates the transceiver module and it is
responsible for the channel selection and ensures that the channel is not busy
before transmitting data. The next layer is the MAC layer which is responsible
for assembling and decomposing frames which will be transmitted through the
physical network link and it handles the check-summing process to assure a
certain level of data integrity.
Although the protocol is built up simply, it offers several functions that can be
found in more complex protocols, too. As an additional feature it offers an
encryption of the transmitted data and determines the link quality by
measuring the signal strength (RSSI -Radio signal strength indication). To
avoid collisions in case several senders want to transmit data at the same 8 http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=93182
11
time, it makes use of the CSMA/CA algorithm. Before sending a frame, the
transceiver eavesdrops for other transmitting devices. If another running
transmission is detected, this CSMA/CA algorithm forces the device to wait for
a randomly chosen back off time. If another transmission is detected it will
wait again, otherwise if the medium is free, the data transmission will be
started. To verify the correct reception of a data frame, acknowledgements
can be used. The standard defines three retransmission attempts in case an
acknowledgment is not received.
Figure 6: 802.15.4 Frame 9
The lowest layer, the physical layer can handle packets with a maximum
length of 127 bytes. The first field in a physical layer packet is the
synchronization header. Its task is to synchronize the transceiver with the bit
stream on the transmission media. It is followed by the physical layer header
that contains the size of the payload that is coming from upper layers. The
next layer that is set up on top of the physical layer is the MAC layer. The
MAC layer frame is carried in a physical layer packet as payload. It begins
with the so called MAC header. The MAC header contains address and
security information. It carries as data payload information from layers that are
situated above. The last field in a MAC layer frame is a 2 byte long checksum
field to verify the content of the data payload.
9 Shahin Farahani. ZigBee wireless networks and transceivers, ZigBee and IEEE 802.15.4 Networking Layer Functions, page 18
12
4.1.1 Frequencies
Data transmission can be done using three different license free frequency
bands that belong to the ISM (Industrial, Scientific and Medical) band.
In total 16 channels and 3 different data rates are available:
Frequency band [MHz] Channel Transfer rate [kBit/s]
868.0 - 868.6 0 20
902.0 - 928.0 1 - 10 40
2400.0 - 2483.5 11 - 26 250
Table 1: Overview of frequencies, bandwidths, chann els and resulting transfer rates 10
4.1.2 Addressing
The MAC layer offers the use of two different types of addresses:
4.1.2.1 64 bit long fixed, unique addresses
The distribution of these addresses is done by the IEEE11 (Institute of
Electrical and Electronics Engineers). To each manufactured device is a world
wide unique number assigned.
4.1.2.2 16 bit addresses which can be configured ma nually
Using this addressing scheme, the administrator bares the responsibility of
assigning the addresses to the different devices. A frame can be addressed to
a single destination (Unicast) or to be received by all participants of the
network (Broadcast).
10 Shahin Farahani. ZigBee wireless networks and transceivers, ZigBee and IEEE 802.15.4 Networking Frequencies of Operation and Data Rates, page 7 11 http://www.ieee.org
13
4.1.3 Network setup
A regular 802.15.4 PAN is setup of two different node types, the so called full
featured devices (FFD), also called PAN coordinators and the reduced
function devices (RFD). Each PAN has only got one coordinator node that is
responsible for the network organization. These nodes handle association and
disassociation requests and receive the data from the RFDs. The RFDs can
only communicate with an FFD. There is no multihop communication possible
between RFDs in this network structure. But, to exchange data with other
PANs the FFDs can communicate with each other.
Supported network topologies: PANs using the 802.15.4 standard can be built up in 2 different topologies12:
4.1.4 Topologies
4.1.4.1 Star topology
This is the simplest network topology, all the network nodes communicate
directly with the base station.
Figure 7: Communication in a star topology network
12 Shahin Farahani. ZigBee wireless networks and transceivers, ZigBee networking topologies, page 10
14
This topology can be easily set up and maintained. No routing or forwarding
algorithms are needed, but beside its simplicity it has got the disadvantage
that network links are not redundant. In addition, the whole network is
completely dependent on the base station. Only nodes that are in direct range
of the base station are able to participate in the network.
4.1.4.2 Cluster tree topology13:
In this topology several coordinator nodes exist. Each of them forms its own
network. These coordinator nodes can additionally communicate with each
other to exchange data between the different independent networks. The
entire network is controlled by one main network controller. The network is
divided into independent network units that can communicate with each other
through connections between the coordinator nodes. A node is connected to
exactly one of these coordinator nodes. To set up a network inthis structure,
different network devices are necessary. Beside the regular base station, that
works as coordinator for the whole network, for each cluster FFDs with a
routing capability are needed to route traffic between the different network
clusters. The clients in this network can change their membership from one
network cluster to another one. This topology can make use of redundant
network paths that can be used to balance the network load and to replace an
interrupted link.
Figure 8: Communication in a cluster tree topology network 13 Rosemount, http://www.emersonprocess.com/Rosemount/document/notes/00840-0200-4180.pdf, Page 2
15
4.2 Zigbee standard:
The ZigBee14 standard is a networking standard that is developed by a union
of several companies of different fields: The Zigbee Alliance. The protocol
stack sets up on the first two layers that are provided by the 802.15.4
standard and offers 3 more layers15 to make the Zigbee wireless networking
possible. The third layer in the conjunction of the two protocol stacks is the
Network layer. It provides routing, network and device management. The
complete function set of this layer depends on the manufacturer that
implements this layer. Hence this layer is not open source, it is quite difficult to
get information about the detailed implementation. The fourth layer in the
stack is the security layer, which provides several security features. The fifth
and last layer in the stack is the application layer. This layer is the interface for
the end user's application to the Zigbee protocol stack. The programmer
interacts directly with this layer and can adapt its programs for the required
purposes.
Figure 9: Zigbee layer on top of IEE 802.15.4 layer s
14 The ZigBee Alliance, http://www.zigbee.org 15 William C. Craig ,Zigbee: “Wireless Control That Simply Works”,http://www.zigbee.org/imwp/idms/popups/pop_download.asp?contentID=5438
16
4.2.1 Transfer methods 16
Two different transfer modes are available:
4.2.1.1 Asynchronous unslotted mode
In this mode of operation, each node can transmit at any time. The base
station has to be awake all the time, due to the fact that there is no regulation
of transmission time. Before transmitting, the CSMA/CA algorithm is applied.
Optionally acknowledgements can be used.
4.2.1.2 Synchronous slotted mode
Using this mode, the network traffic is synchronized by a coordinator node.
The coordinator transmits beacons in fixed intervals to synchronize the
network nodes. The time between two beacons, which are marked as start -
beacons and end-beacons, is called super frame. This super frame is divided
into an active phase and into an inactive phase. The active phase consists of
16 equal time slots which are partitioned into two different access periods, the
contention access period (CAP) and the contention free period (CFP). In the
CAP each node that wants to transmit can transmit using the CSMA/CA
algorithm. In the CFP the coordinator each slot is reserved for only one node
in the network, hence no collision avoidance algorithm is necessary. This
mode has got the advantage that between sending a super frame, the
coordinator can go into a sleep mode as well.
16Shahin Farahani. ZigBee wireless networks and transceivers, CSMA-CA, page 52
17
4.2.2 Network topology 17
4.2.2.1 Peer to peer topology
Additionally to the two topologies mentioned above the Zigbee protocol
standard allows one more network model which is more complex - the mesh
topology. This type of topology requires one device type more beside the
coordinator node and the end devices. To determine the path through the
network, routers are necessary. Each end devices sends its data packet to a
router which is connected to another router which takes the routing decisions
and forwards the packet to its destination. In this topology the end devices
can communicate with a router or with a coordinator. An inter-end device
communication is not possible.
Figure 10: Peer to peer network structure
17 Shahin Farahani. ZigBee wireless networks and transceivers, Mesh Topology, page 90
18
4.3 Structure of the sensor network
In a wireless sensor network it is actually not always required, that all nodes
can talk to each other. A situation that occurs more frequently is the following:
Each sensor device should deliver its data as fast as possible to a base
station that processes the measured values. To achieve this requirement is
quite easy if each node is in the range of the base station. However this is
only the case in a few cases. In many setups not every sensor node can be in
direct range of the base station because the distances are too big, the
transmission power of a device is not high enough to cover that range.
Because of its limited range of operation, a single hop network where all
nodes directly communicate with the base station is not applicable for many
purposes: a functionality to extend the range is needed. A simple solution
could be to use more powerful transmitters18, but this implicates a big
disadvantage, this solution is not very efficient regarding the power
consumption. Due to the fact that the sensor nodes are mostly battery
powered and therefore the energy is limited, this solution is not suitable.
Repeaters that amplify the signals in areas with a weak coverage could be
used but also need an appropriate energy supply.
A much more efficient solution is to build up a multi hop network and to make
use of other devices that are already available. Other nodes that are in range
can be used to forward the sensor data to the base station. Like this, nodes
can be out of range of the base station but an indirect communication with it is
still possible. Extending the functionality of existing devices has also got the
advantage that the network will be set up of homogeneous devices. This
facilitates the network setup and each node that is added to the network
extends the range without the need of additional equipment.
The presented sensor network does not follow the regular 802.15.4 standard.
In this network no special coordinator node is needed, each node has got the
same privileges. Beside the nodes which form the network, only one base
station is needed that collects the transmitted data of the sensor nodes from
18 http://www.digi.com/products/wireless/point-multipoint/xbee-pro-series1-module.jsp
19
the whole network. In this approach a tree network structure is created where
the root is the base station and the leaves are the end devices.
4.3.1 The tree network topology
Figure 11 : Tree Network structure
Each node in the tree has got its predecessor that forwards the traffic of its
successor nodes.
Performing the desired way of operation, a routing functionality will be
required to determine the shortest path through the network. In this approach
of network topology, it is possible that many nodes can listen to each other,
the routing algorithm will have the task to select out of all the neighbours the
one with the shortest distance to the base station that is the root node.
.
20
4.4 Network communication based on the XBee module
The XBee transmitters which handle the whole communication in the network
offer two communication modes:
4.4.1 Modes of operation
4.4.1.1 Transparent operation:
In this mode of operation the wireless transmitter can be used to replace a
serial line. Each character that is sent to the receiver via the serial input is
transmitted through the wireless interface. The module does not perform a
checksum calculation. To configure modem parameters AT commands can be
sent to the modem using the serial interface. In this mode this process is quite
uncomfortable to use and needs much time. Before sending the AT command
to the modem, the device has to be put into the AT command mode. Three "+"
characters have to be transmitted, afterwards during a time period of one
second no characters can be send. After this time the AT command mode is
activated and configuration parameters can be processed by the modem.
Systems that require a fast data processing time and where configuration
parameters have to be changed before a data transmission, this way of
configuring modem parameters would need too much time.
4.4.1.2 API Operation
Using this mode, all the serial data that enters the module is packed into a
frame where it is carried as payload. This mode has significant advantages in
comparison with the transparent operation. When sending an API frame, the
destination address has to be specified. Like this, the module can be
instructed to unicast a message to a certain network participant or to
broadcast the message to all other network nodes. Of course, also a unicast
message is heard by all other nodes in range, but the decision if this message
will be accepted or silently dropped will be already taken at the radio receiver.
Like this, the MAC layer does this work and the application layer does not
have to do this process additionally.
21
Furthermore an API frame contains a length field, indicating the byte length of
the data payload. This is an advantage for the message processing at the
application layer. For instance when reading the byte stream, it is already
known how many bytes have to be read after reading the length field of the
frame. Another aspect that facilitates the communication is a message
checksum field. When composing a data frame on the application layer, a
checksum of the payload has to be calculated and to be added at the end of
the frame. Each time the radio receiver receives a complete frame it
calculates the checksum of the payload and compares it with the checksum
value that is included in the frame. If the calculated checksum does not equal
the transmitted checksum value, a frame will be dropped silently. Again, this
means less work for the application layer. Only data that passes the check
summing sequence is forwarded to the application layer and can already be
considered as valid.
There are different API frames available for different purposes. To read or
modify modem parameters AT commands can be send inside a so called
command frame. This way of configuring the wireless transmitter is much
faster than doing this with the AT command mode.
As a response to an AT command a response frame is send that contains the
value of the configuration register that is affected by the AT command. For
special events like a hardware reset, a watchdog timeout or 802.15.4 network
events like the association of a coordinator node, the module sends a so
called status frame. This frame contains a status byte indicating the event that
occurred.
For the communication in the sensor network, two frame types are important:
4.4.1.2.1 Transmit request frame:
Using this frame type instructs the module to transmit a frame to a specified
address (which can also be the broadcast address). This frame can carry up
to 100 byte as data payload.
The Transmit-Request-Frame and the Receive-Frame are built up like the
following:
22
API-Transmit-Request-Frame 19
Figure 12: Transmit-Request-Frame
4.4.1.2.2 Receive frame
When the module receives data, it will be packet into a frame before it is
delivered over the serial line.
API-Receive-Frame 20
Figure 13: Figure Receive-Frame
Field explanations
Start delimiter:
To identify the beginning of a frame, the first byte is always 0x7E.
Length
The length field indicates the length beginning the from the API-ID reaching till
the last byte of the payload. The length field is two bytes long.
Frame-ID
The frame ID identifies the data frame for the host to correlate with a
subsequent acknowledgement.
19 XBee product manual v1.xAx, http://ssdl.stanford.edu/ssdl/images/stories/AA236/0708A/Lab/Rover/Parts/xbeeproproductmanual.pdf Page 55“API Types”, - TX (Transmit) Request: 16-bit address” 20 XBee product manual v1.xAx, http://ssdl.stanford.edu/ssdl/images/stories/AA236/0708A/Lab/Rover/Parts/xbeeproproductmanual.pdf Page 55“API Types - RX (Receive) Packet: 16-bit Address”
23
API-ID
With the API identifier, the module identifies the type of the command frame.
Source address
The length of this field depends on the used addressing scheme. Using the 64
bit scheme, it is 8 bytes long. Using the 16 bit scheme, it is two bytes too long.
It contains the source address of the module that has transmitted the frame.
Destination address
The length of this field depends on the used addressing scheme. Using the 64
bit scheme, it is 8 bytes long. Using the 16 bit scheme, it is 2 bytes long. If a
frame should be broadcasted the address 0x000000000000FFFF (64 bit) or
0xFFFF (16 bit) has to be used.
RSSI (Receive Signal Strength Indicator)
This field is only in the receive-frame available and indicates the signal
strength in dBm of the last received packet.
Options
Transmit-Request: Setting the options byte to 0x01 disables
acknowledgements. If it is set to 0x04 the packet will be sent as a PAN-
broadcast.
Receive-Frame: Here the options bit gives additional information about the
type of transmission: If bit 1 is set to 1, it is an address broadcast. if bit 2 is set
to 1, it is an PAN broadcast.
CHK
This field contains the checksum, in the checksum all fields beginning at the
API-ID till the last byte of the data payload are included.
24
4.4.1.2.3 Character escaping 21
The RF module uses special control characters to identify certain positions in
the byte stream. For example the beginning of a frame is identified by the
value 0x7E. But it can be that other fields in the frame also have this value.
This would result in a malfunction because the module would wrongly
recognize this character as the beginning of a new frame. To avoid these fault
recognitions of control characters, these have to be escaped. The escaping of
these characters is very simple. All characters of the frame, beginning at the
first length field will be checked for control characters. If a control character is
found, it will be escaped. The escaping process is based on a logic XOR-
operation. The control character will be XOR'd with 0x20 and the result is
written to its position. Additionally the escape identifier 0x7D will be inserted
one byte position before. This is necessary to identify an escaped character
on the receiver side. Therefore, that the XOR inverse is also XOR, the
unescape process at the application layer is as easy as the escape process. If
a 0x7D is detected in the byte stream, it will be discarded and the following
character will be XOR'd again with 0x20. The result is the original character.
Escaping example
The following not escaped byte stream extracted of the frame payload
contains the control character 0x7E.
After escaping this character the byte stream looks like the following:
0x7E XOR 0x20 = 0x5E
21 XBee product manual v1.xAx, http://ssdl.stanford.edu/ssdl/images/stories/AA236/0708A/Lab/Rover/Parts/xbeeproproductmanual.pdf Page 52,“API Operation - with Escape Characters“
25
Characters that have to be escaped
Character Description
0x7E Frame delimiter
0x7D escape indicator
0x11 XON
0x13 XOFF
4.4.1.3 Additional features
Additionally to the features of the 802.15.4 standard, the XBee modules offer
to send the data frames using the so called MaxStream header. Some
important configurable parameters a explained in the following.
4.4.1.4 XBee retries
The 802.15.4 standard defines 3 transmission retries for unacknowledged
packets. The XBee standard extends the number of retries. Additionally to the
3 retries, up to 6 additional XBee retries can be executed. For each XBee
retry, the module can execute up to three 802.15.4 MAC transmission retries.
Especially in environments with a high traffic density, this feature is helpful to
increase the transmission reliability.
4.4.1.5 CSMA/CA
When the shared transmission media is busy, a so called back off exponent
controls the delay time after a module retries the transmission. This exponent
can be changed. Possible values are 0, 1, 2 and 3. If it is set to 0, the module
will not execute the CSMA/CA algorithm in the first transmission attempt.
26
4.4.1.6 Clear Channel Assessment (CCA) threshold
When the CSMA/CA algorithm is applied, the module eavesdrop for traffic on
the media before it starts a transmission. If the measured signal strength is
above this threshold, the module declares the media as occupied and will not
transmit. This threshold can be adjusted in order to control the sensitivity.
4.4.1.7 Packetization timeout
When data arrives at the serial input of the XBee module, how many
characters should be added into an RF-packet can be controlled. The
packetization timeout value controls this behavior. If it is set to 0, each
character will be transmitted immediately in one RF-packet. Otherwise it will
be waited for the configured timeout for more characters until a packet
containing these characters will be transmitted. The timeout value depends on
the data rate.
][**][ sTNsT CharacterionTimeoutPacketizatTimeout =
TimeoutT : Resulting timeout value
N : Configured packetization timeout value
CharacterT : The time a character needs to arrive
4.4.1.8 Security feature
To guarantee a certain amount of network security the XBee modules allow
the encryption of RF-packets. The modules offer to encrypt the packets using
the AES encryption standard.
When this feature should be enabled, a 128-bit key has to be configured on
each module. As additional security feature, this key can only be written to a
register in the module. A read operation is not permitted.
27
5 Software development The software development basically consists of two parts, on the one hand
the algorithms that run on the sensor nodes and on the other hand the
program that will run on the base station to analyze the incoming data of the
sensor network.
5.1 Simulation of software components
Before the different algorithms are applied to the devices, the basic
functionality will be tested in a simulator that will be written in JAVA to control
the behavior and to detect possible problems in advance.
The developed simulator will test the correct function of the routing algorithm,
the different types of message transmission and other network features. To
simulate the wireless communication, UDP connections between threads are
used, which represent the sensor nodes. Each node has got a list of UDP
sockets which represent the connection to its neighbors.
The message transmission process is initialized by a root node thread that
represents the base station. It starts the beacon message transmission to the
nodes in its neighbor list. When the different threads receive this message via
their incoming UDP socket, an answer message is sent to the node that has
emitted the beacon. This message represents the sensor data. Then each
node that has received a beacon will retransmit this beacon message with a
received hop count.
After emitting the beacon, the nodes keep on listening for a configured
amount of time on their incoming UDP socket to forward a data message from
a successor node to the base station. This process continues until the beacon
is forwarded through the whole set of simulated network nodes and it will stop
when all data messages have arrived at the root nodes. Like this the different
message transmissions can be tested.
28
5.2 The routing algorithm
The aim of this algorithm is to build up a tree network topology that is robust,
easy to maintain and that can quickly react to changes. Also alternative path
options that can be used as a backup route in case of a breakdown are an
obligatory requirement. When considering different network topologies, the
solution has to be a topology that can contain redundant paths between the
network participants to avoid break downs when one path fails. A mesh
topology fulfils completely these requirements, but the topology that is used in
the sensor network in this paper will be a tree topology which is similar to the
mesh topology. The difference between these two topologies is that the tree
topology has only got one active connection to another node.
A typical mesh topology is not needed in this case, because a communication
with all other nodes is not required. For the network functionality it is only
important that each node has got one predecessor to forward the traffic into
direction sink.
Because of efficiency reasons, each node should reach the sink using the
smallest number of intermediate nodes as possible. This reduces additional
network traffic and guarantees that all packets reach the sink in a minimum
amount of time. Because of limited performance of the network nodes and
taking into consideration the system's energy efficiency, the routing features
must not exceed a certain degree of complexity. In the sensor network the
situation of finding a path is not so complex, like in big communication
networks, such as the Internet, where the packets of a message can use
many different paths to the destination.
Data messages containing the sensor values only have got one destination -
the base station. The path determination in this model is less complex and
can be achieved with a small amount of resources. No processing intensive
routing algorithm with a complex routing table and with the need of sending
many routing information to other routers is needed. To resolve the path-
finding problem, a slim, fast and efficient algorithm has been developed for
this network approach. The operation of this algorithm is described in the
following paragraph.
29
5.2.1 Mode of operation of the routing algorithm
The requirement for the algorithm to be able to work correctly at the initial
state is that each node is powered on and that each node can listen to at least
one node that has got a direct or indirect connection to the base station. The
algorithm takes its decisions depending on the distance after getting the
information about a new route. As a distance indicator, each node will use the
number of hops between itself and the base station.
This base station emits periodically in a preconfigured interval a beacon
message that contains as a hop count the value 1. This beacon is received by
all nodes that are in range of the base station's radio signals and will be
received and broadcasted with an increased hop count to all the direct
neighbours of these nodes. Nodes will only accept beacons that offer a
smaller distance as the value that is already known by a node by further
received beacon messages. This process assures that each node knows the
shortest way to the base station.
Repeating these steps, a beacon will be propagated through the whole
network and the data messages will be forwarded to the root node.
Figure 14: Propagation of a beacon message
30
Figure 15: Data transmission from the nodes to the sink
In case a node does not receive a beacon, due to a transmission error, the
node waits for another beacon. The beacon will only be broadcasted to the
neighbours of a node if a beacon from a predecessor has been received and
was accepted. This assures that no data will be transmitted if no connection
exists and that steps to establish a new connection can be initiated.
The algorithm should be able to fix connection problems when the determined
path is not usable anymore because of a malfunction of one intermediate
device that is used to forward the traffic coming from its successor nodes. If
one predecessor node stops sending its beacon that is advertising the route
to the sink, it is a sign that either the node is out of range or a node has got a
malfunction.
The routing algorithm will notice that no beacon from the current next hop is
received and waits then for other route offers transmitted by nodes that
advertise a path to the sink. Like this, a possible interruption of the forwarding
process can be fixed quickly and the network can reenter its normal operation
mode.
31
5.2.1.1 Finite state diagram of the routing and for warding algorithm
The following figure shows the different steps of the algorithm:
Figure 16: Mode of operation of the routing algorit hm
The start condition is fulfilled, when the node is powered on and is able to
receive its first beacon. Then it starts its regular operation. This process is an
endless cycle and is repeated each time a new beacon message is received.
32
5.2.2 Protection against routing loops
When developing a routing algorithm several conditions that can occur which
mislead messages, have to be considered. A problem that has to be tried to
be avoided is routing loops. A routing loop is caused by contradictory routing
information. When a routing loop exists, packets circle through the network
without reaching its destination. In the worst case this circling can be endless.
This incorrect forwarding of packets through the network causes a needless
usage of resources. Power will be wasted and the links could be congested.
Referring to the presented sensor network, routing loops would avoid the
correct transmission of data packets to the base station. Also the battery life
would be shortened because of the additional data transmissions.
There are several scenarios that can produce a routing loop. The following
example describes one of these conditions.
Routing loop
2
1
3
A B
C
Sink
Figure 17: Possible routing loop conditions
A loop could occur if the following conditions are met:
- Node B and C use node A to forward data to the sink.
- Now node A stops working because of a malfunction.
- Node C realizes this malfunction but B not.
- B advertises accordingly this route to C.
- B realizes now the absence of node A.
33
If now node C accepts a route offer of node B, a routing loop is created. C
forwards to B and the other way round. Data packets circle between B and C.
The possibility that a routing loop occurs in the sensor network that uses a
tree structure is almost impossible. A tree structure implies a loop free
arrangement of nodes. The critical phase is when the tree is built up, but also
here the algorithm avoids the creation of loop conditions. A node will only
advertise a route to the sink, if it has received an advertisement of a valid
predecessor. Valid in this context means that the received beacon is from its
current predecessor or from a node that offers a better connection to the sink.
Or it can be that a node has lost the connection to its predecessor that means
it did not receive a beacon from it. In this case it will accept also other
beacons from nodes, which offer a worse connection. This could be
problematic and normally result in a loop. In this network, the beacon
broadcast is triggered by the reception of valid beacon. Therefore it is
impossible that this condition can occur. A loop could only occur if one node
that has already transmitted a beacon, will accept a beacon from a deeper
network level due to a timeout of the beacon reception from its predecessor
34
5.3 Development of additional features
5.3.1 Message transmission
There are different approaches available to carry out communication. One is
to broadcast all messages, whether it is a beacon or a data message.
Following this approach, the frames will be transmitted using the 802.15.4
broadcast network address. Then the decision whether this frame will be
processed or not has to be taken at the application layer. A more efficient
solution is to use both, unicast and broadcast messages. Beacons are
messages that are determined for all nodes in the network, because each
beacon contains information about a possible better route. It has to be
received and analyzed by every node by the routing algorithm, otherwise a
data message should only be received by one node, which is the predecessor
of the node, sending the message.
Using a unicast transmission for the data message reduces the need to
process this message by every node. The decision if a message is accepted
by the wireless transceiver is already taken on the MAC layer. If a unicast
message is received by a device that is not the destination of the frame, the
frame will be dropped silently and the processor of the micro controller does
not have to waste processing power by analyzing this message.
This approach also reduces the possibility buffer overflows of the serial input
buffer of the micro controller. Fewer messages are transmitted to the micro
controller over the serial connection and this results in less work for the micro
controller.
The network uses two different message types to exchange data between
nodes. Two different types are needed, because there are basically two types
of information that is transmitted in the network. On the one hand there is the
transmission of control information and on the other hand, there is the data
that is coming from the sensor nodes.
35
5.3.1.1 Beacon messages
A beacon message travels only into one direction from the root node to all
network nodes. It contains a link advertisement with the distance to the sink.
Additionally control parameters are transmitted in the beacon message to
modify the settings of all network nodes. This beacon messages propagate
through the network until they have reached the deepest level in the network
tree. Each time a beacon message is received, the content will be extracted
and analyzed. If the contents are valid, further decisions will be taken,
otherwise the beacon will be dropped silently.
5.3.1.1.1 Structure of a beacon message
Figure 18: Beacon message structure 64 bit addressi ng
The highlighted fields are non obligatory fields.
Explanation :
Data message identifier
This identifier is used by the system to identify a message that belongs to the
sensor network. The value is for all data messages 0x40.
Message type identifier:
The message type identifier specifies the kind of message. If it is a beacon
message or if it is a data message. A beacon message is identified by the
value 0x42.
Next hop address:
The next hop address contains the address of the advertised next hop to
forward the message of the node that sends the beacon message. The length
36
of this field depends on the used addressing scheme either it is 8 or 2 bytes
long.
Distance:
This value indicates the distance the emitting node is away from the sink.
Sleep time[1] and Sleep time[2]:
These two fields are used to regulate the sleep time of each node. Two fields
are necessary, because the value is specified in seconds. To configure longer
sleep times a sufficient size of 16bit is available. This results in a maximum
value of 2¹⁶ seconds which is more than 18 hours.
Delay time:
The delay time regulates how long a node waits for a message to forward it
after broadcasting the beacon to its neighbours.
Route refresh interval:
This value specifies the number of cycles, a route refresh will be executed. A
cycle includes the sleep- and transmit time.
Configuration parameters:
This field contains configuration flags in the following order:
15[0]: Deactivate or activate acknowledgements when transmitting a data
message
15[1]: Deactivate or activate the routing functionality. If it is deactivated,
the
node will never change its predecessor.
15[2]: Deactivate or activate the hardware flow control.
15[3]: If this flag is set the node expects an AT command at the specified
positions
37
15[4]: If this flag is set, AT commands are written to the non volatile
memory. Otherwise the previous configuration can be restored by a
reboot of the XBee module.
Load indicator:
This field contains the total amount of forwarded messages and is used by the
load balancer algorithm.
Aggregation timeout:
This value specifies the percentage of the delay time after an aggregated
packet will be transmitted.
AT command char:
If the AT command flag is set, the node reads the AT command fields. The
bytes 18 and 19 contain each one character of the AT command.
AT parameter:
These two fields contain the new parameters that will be set after the
command is executed.
AT command destination:
If the values of these fields are 0XFF the command will be applied on all
nodes. To configure only one single node, the network address of that node
has to be written to these fields.
38
5.3.1.2 Data messages
Each sensor node transmits periodically data messages which contain the
values of the attached sensors, like temperature, humidity or light intensity.
The data messages are always forwarded from the sensor nodes into
direction sink. Beside the sensor information it can contain status messages
from a sensor node, like signal strength of the predecessor or a battery
voltage value to inform an administrator about a necessary battery
replacement.
5.3.1.2.1 Data message structure
Figure 19: Figure data message structure
Explanation:
Data message identifier
This identifier is used by the system to identify a message that belongs to the
sensor network. The value is for all data messages 0x40.
Message type identifier
The message type identifier specifies the kind of message. If it is a beacon
message or if it is a data message. A beacon message is identified by the
value 0x44.
Source address:
This field specifies the origin of the data message on the application layer.
This field is necessary because the source address of the MAC layer cannot
be used, because it changes on each transmission.
39
Message Id
The message Id is a counter that will be increased each time a node transmits
its data message. It is used to identify a specific message of a node. It is also
used in combination with the source address when the duplicate packet filter
algorithm is applied. If a data message is forwarded by nodes through the
network, the link layer destination- and sender address- change at each
forwarding procedure. The MAC layer frame will always carry the destination
address of the next node and the address of the sending node.
To identify at the base station from which node the currently received frame
actually is, it cannot rely only on the MAC layer addresses. The solution is to
add an address to a higher layer that is independent of the link layer
addresses. A node identifier that clearly identifies each node in the network
will be added to the frame on the application layer. Instead of creating an
additional application layer address scheme, the address that is added to the
data message is the MAC address of the node that is the origin of that
message. It can be read automatically and therefore there is no need to
configure each node manually before adding it to the network. To take routing
decisions it is not necessary to add an additional destination address to the
frame on a layer above the MAC layer (like for example in the IP protocol
stack), the destination of each frame is already known, it will be always the
root node.
A disadvantage of using a broadcast transmission for the beacons is that
these messages cannot be acknowledged and therefore no guarantee of a
successful reception can be given. But there is no other way to keep the
network working in a dynamic way without using broadcast messages. One
possibility is that each node stores a list of predecessors and transmit the
beacons in a unicast transmission. But then the node has to check
additionally if all its neighbours are still in range and refresh its list. And a
more difficult situation occurs if a new node wants to join the network.
However, using broadcast messages is not a problem in this sensor network.
The chance that a collision happens while sending a broadcast is not very
high, because if a beacon is broadcasted the nodes on deeper levels are not
40
yet transmitting, they are listening for a beacon. Additionally, before sending a
beacon the CSMA/CA algorithm will be applied.
5.3.2 Addressing of the sensor nodes
As mentioned, the 802.15.4 standard provides a MAC layer that offers two
different address schemes. The network will make use of this, and the nodes
can be configured to use either the 16 bit or the 64 bit scheme. An advantage
of the 16 bit scheme is that the frames are shorter and thus more space for
payload in a data frame is available.
5.3.3 Power management
The nodes normally are powered by a power supply that has got limited
capacities like simple AA-size batteries. Therefore it is obligatory to implement
a power management solution, which guarantees that no energy will be
wasted in order to use the limited energy resources as much efficient as
possible. The network does not require that the nodes are fully powered on
continuously. The normal sequence of different states of a sensor node is
illustrated in the following figure:
Figure 20: Cyclic communication
TXT : Time when the nodes are processing, receiving and transmitting.
IdleT : Time when the nodes are in idle state.
CycleT : Cycle time, the sum of the active time and idle time.
41
Between the transmission periods, which are generally much shorter than the
idle times, the nodes do not have any active transmissions and could be put
into a low power state.
To achieve the maximum battery life, the energy consumption has to be
reduced as much as possible, when the nodes are in idle mode.
Basically there are two main energy draws working on the sensor node. One
is the micro controller, the other is the XBee wireless modem. The power
consumption of the Atmega168 is about 7.97 mA and the XBee module
consumes additional 50mA when they are in idle mode. To put the devices
into low power consuming states, different sleep modes are available. The
basic idea of a sleep mode is that certain components of a device will be
switched off, that a lower power consumption can be achieved.
5.3.3.1 Power saving - radio transceiver
The normal working cycle in this network does not require that the radio
receiver be switched on at all times. The structure of a cycle consists in
generally of two parts, the transmission cycle and the idle cycle. In the
transmission cycle the radio transceiver serves as a communication interface
to the network medium and is responsible to send and receive data from other
nodes. In this phase it must be switched on to be able to communicate with
the other devices. In many applications this transmission time is much smaller
than the time when the network is in idle mode. In the idle mode the radio
receiver does not have to transmit any data and therefore it can be disabled
without loosing any information. The used of the ZigBee wireless transceiver
offers a set of different power save modes. On the one hand there are pin
controlled sleep modes and on the other hand there are cyclic sleep modes
available. The pin controlled sleep modes can be activated by setting one
special digital input of the module to low. The cyclic sleep modes are
controlled by an internal timer of the transceiver.
42
Cyclic sleep modes 22
The cyclic sleep modes are only applicable on networks that work with a
coordinator in the network. After waking up, the module polls the coordinator
and checks if any data is ready to transmit for that module. If this is the case,
the module receives and processes the data, if not it will enter the sleep state
for a next cycle. This process continues periodically. Another similar mode
provides the same functionality but offers additionally a pin wake up function.
This two modes are not usable for the purpose of the network that is
presented in this paper, because this network does not work with a
coordinator node.
Pin controlled sleep modes 23
More interesting for the realization of the low power states are pin controlled
modes that are supported by the wireless transmission unit. These modes
differ regarding the power consumption and the wake up time that is needed
to provide the full functionality after a sleep period. The so called Pin Doze
mode puts the XBee module into a state where it consumes less than 50 µA
and has a wake up time of only 2 msec. The last mode where the module
consumes only less than 10 µA is the pin hibernate mode and has got a
longer wake up time that is 13.2 msec. Therefore, a sensor node is normally
in a sleep time, the last sleep option is the most appropriate one to guarantee
a long battery life. The 13.2 msec wakeup time does not interfere with the
regular operation of the network. To control the pin that controls if the pin is
awake or if it sleeps can be controlled by one digital IO of the micro controller.
How the deactivation and activation of the module is realized can be found in
the code section where the program code is described.
22 XBee product manual v1.xAx, http://ssdl.stanford.edu/ssdl/images/stories/AA236/0708A/Lab/Rover/Parts/xbeeproproductmanual.pdf Page 23, “Cyclic Sleep Modes” 23 XBee product manual v1.xAx, http://ssdl.stanford.edu/ssdl/images/stories/AA236/0708A/Lab/Rover/Parts/xbeeproproductmanual.pdf Page 53 “Pin/Host-controlled Sleep Modes”
43
5.3.3.2 Power saving - micro controller
The micro controller has also got a set of sleep modes that can be applied to
disable internal components that are not needed in case the processor is not
used. To put the chip into one of this sleep states, the values of internal
control registers have to be modified. The wake-up of the controller works with
interrupt signals, either internally generated or external supplied ones.
On the sensor board there is no device that could produce this external
interrupt signal, that is why only internal interrupts can be used to wake up the
controller when it is in the sleep state. To generate the internal interrupts
several sources exist. Among others, like for example the system watch dog
or signals on the serial port, two different timers exist that can generate the
interrupt signal when they reach a certain preconfigured value or when an
overflow occurs. Among others, the Atmega168 micro controller offers two
sleep modes that could be used for the power management in the network.
Sleep mode - POWER_DOWN24
This mode offers the maximum power saving. Only very few components are
working in this mode. The external oscillator that provides the chip with the
clock signal stops working. All counters stop to work and the only possibility to
wake up the chip again is an external interrupt signal generated by the system
watchdog, serial interface or by a pin change interrupt.
Sleep mode - POWER_Safe
This mode is similar to the POWER_DOWN mode. The only difference is, that
one of the system's internal timer (Timer2) can be programmed to continue
working in this mode. This timer can generate interrupts that are activated if
the timer reaches a certain predefined value or if a timer reaches its end.
24 Atmel Atmega168 manual. http://www.atmel.com/dyn/resources/prod_documents/doc2545.pdf, “Power management and sleep modes"
44
Applying different sleep modes to the system
System behavior using Sleep mode - POWER_DOWN
Both modes have been put into consideration when designing the power
management feature.
The most attractive mode is the POWER_DOWN mode where the maximum
amount of energy can be saved. In this mode the only possible time
dependent configurable wakeup source is the system watchdog timer. The
system watchdog is normally used to reset the system if there is an error in
the program code and the system freezes. In the regular mode of operation
the system watchdog timer will be reset from the program code periodically to
avoid a system reset. If this reset does not happen because of a malfunction,
the watchdog timer reaches its maximum value and causes a system reset. It
is also possible to configure the timer in such a manner that it does not trigger
a reset but an interrupt signal instead. This option can be used to wakeup the
chip from the POWER_SAFE mode. The counting source for this timer is an
external oscillator. The time when an interrupt occurs can be configured with a
prescaler. This prescaler predevides the oscillator frequency that longer
timing periods can be achieved. The Atmega168 micro controller allows to
configure the following values for the watchdog timer prescaler:
Number of oscillator cycles Typical Time-out at 5 Volts 2048 16 ms 4096 32 ms 8192 64 ms 16384 0.125 ms 32768 0.25 ms 65536 0.5 s 131072 1.0 s 262144 2.0 s 524288 4.0 s 1048576 8.0 s
Table 2: Possible timeout times of the system watch dog timer
45
ISR Processing triggered by timer overflow interrup ts
Each time a time-out occurs, the chip processes the interrupt service routine.
(ISR) In this routine the decision is taken; if the controller goes into sleep for
another cycle or if it will continue with its regular operation. The algorithm that
runs in the ISR increases each time a software counter variable, if this
variable reaches a configured value the watchdog timer will be deactivated.
The following figure illustrates this process:
Figure 21: ISR cycle in sleep mode As illustrated in the figure above, each interrupt causes a wakeup where
program code will be executed, a software timer will be increased and the
result is compared with a predefined sleep value. If the timer value equals the
sleep value, the controller will stay awake and start its normal work, otherwise
it will sleep again until the next interrupt will be generated. This process
results in very short states where the controller is fully powered up and the
ISR is being processed. Due to the very small length of the ISR, in
comparison with the processing time, the sleep states cover a much longer
part than the time where the ISR is processed. In this time the controller is
46
fully switched on and therefore it consumes more power. It should be
achieved that the times the controller wakes up should be as low as possible.
If a bigger prescaler factor is used, less wakeup events occur. However, a
longer sleep time causes a lower time resolution affecting the timing precision
of the system. It has to be found a balance between accuracy and a low
power consumption. For this system a factor of 0.5 seconds is precise enough
to achieve the required exactness.
When applying this approach to the system, a power consumption of less then
50 micro amperes could be achieved. But it turned out that the oscillator that
generates the clock signal for the watchdog timer is very inaccurate. A
deviation of more than 10% of the configured sleep time is showing up.
Especially when using longer sleep times, the system's correct operation is
affected. The devices wake up either too early or too late to listen for an
incoming beacon message. Therefore this solution is not applicable.
System behavior using Sleep mode - POWER_SAFE
The second mode that was tested is the POWER_SAFE mode where the
timer2 is configured as a wakeup source. The timer2 uses as clock source the
CPU's internal oscillator which offers a high precision. Also for this timer exists
a prescaler to reduce the timer clock rate. Time2 has got a bit width of 8 bits,
that means that the maximum counter value is 2� reaching from 0 to 255.
Additional to an overflow interrupt that occurs when the timer reaches the
value 255, a special timer value can be configured to trigger an interrupt when
reaching a configured timer value. The prescaler can be configured with
thevalues 8, 64, 256 and 1024. Here the same fact like for the watchdog timer
is valid: A higher prescale factor results in less wakeups, where a smaller
prescaler offers a higher precision. The version of the Atmega168 that is used
for the sensor nodes runs with a clock frequency of 8 MHz. The resulting timer
count speeds are shown in the following table:
47
Table 3: Timer frequencies and overflow times depen ding of the prescale divider
prescalorff CLKTimer /=
For the system the biggest prescaler value of 1024 is chosen, it offers the
necessary exactness and at the same time the least possible amount of
wakeup times can be guaranteed.
The sleep time calculation is done like the following:
][
][
msT
msTCounter
Overflow
SleepSleep =
The resulting counter value is the value of the software counter that is
compared each ISR cycle. After performing several tests it turned out that this
solution completely fulfills the necessary timing requirements. Hence in this
sleep mode the main oscillator is running, the power consumption is higher
than in the POWER_DOWN sleep mode. While sleeping, the Atmega 168
consumes 14 mA, but this is the only solution to achieve an exact timing in
combination with a reduction of the power consumption.
Prescaler divider
Timer frequency (f_Timer)
Overflow time
0 8 MHz 32µs
8 1 MHz 256 µs
64 125 kHz 2.048 ms
256 32.5 kHz 7.877 ms
1024 7.8125 kHz 32.768 ms
48
Deactivating additional components
In the sleep mode POWER_SAVE additionally some components of the micro
controller chip are consuming power when the device is sleeping that can be
switched off.
Deactivating the AD/Converter
The Atmega168 is equipped with an Analog/Digital converter that converts
analog signals of the input pins into digital values. When this device is
disabled, 75µA can be saved additionally.
The Power consumption in active and sleep mode
XBEE
0 -
~ 60 -
MC
Sleep
mode
XBEE
MC
~ 7 -
TA TS
~ 1.15 -
I [mA]
T [s]
Active
mode
Figure 22: Total power consumption in the different modes
The total uptime of nodes depend on the ratio between the sleep time (Ts)
and the active (TA) where the sensor nodes are fully powered up and the total
available energy which depends on the used powers supply.
49
Deactivating other components of the Atmega168
Unfortunately the AD-converter is the only device of the micro controller
board, where a reduction of the energy consumption could be measured after
deactivating it. Therefore it will be the only device, that will be switched off,
while the micro controller is in sleep mode.
Calculation of the possible uptime
To calculate the total uptime, an equation can be derived:
Symbol explanation:
TotalQ : Total capacity of the batteries.
TotalT :
Total possible battery lifetime of a node.
TxT : Active time for each cycle where a node is awake.
IdleT : Sleep time each cycle where a node is in sleep mode.
MCTxI : Current of the micro controller in active mode.
XBeeTxI : Current of the XBee module in active mode
MCIdleI : Current of the micro controller in sleep mode.
XBeeIdleI : Current of the XBee module in sleep mode.
TotalN : Total number of transmission cycles
1. The total power consumption for N transmission c ycles:
))(*)*(*(*XBeeMCXBeeMC IdleIdleIdleTxTxTxTotal IITIITNQ ++=
2. The total transmission cycles
IdleTx
TotalTotal TT
TN
+=
50
3. Substitute N of formula 1 with formula 2
)(*)*(*XBeeMCXBeeMC IdleIdleIdleTxTxTx
Total
IdleTx
Total
IITIIT
Q
TT
T
++=
+
4. The total uptime
)(*)*(*
)(*
XBeeMCXBeeMC IdleIdleIdleTxTxTx
IdleTxTotalTotal IITIIT
TTQT
+++
=
In paragraph “System tests and analysis”, possible theoretical uptimes using
different calculations will be calculated.
5.3.4 Coordination of sleep states
When applying sleep states to a network, several difficulties occur. A node
that is in a sleep mode can not provide other network participants with the
required features. The device is not visible for others, the transceiver and the
processing unit are not powered on. If one or more nodes would become
unavailable for others because of an uncontrolled sleep procedure, it could
cause a breakdown or at least a limited operating functionality of the whole
network. There has to be a control mechanism that checks when and for how
long a node can enter a sleep mode. The network nodes have to be
synchronized in such a manner that it guarantees that no node tries to
transmit data while another node is not able to forward that data, because it is
in a low power state. An easy way to adjust the sleep states are the
periodically transmitted beacon messages. By using the beacons emitted by
the sink, the sleep and transmit phases of the network can be regulated.
Every time a beacon is received by a node, it extracts the beacon interval
value, which is a field in a beacon frame, will be extracted. Like this a node
knows when the next beacon will be transmitted and also knows when it has
to be available to process this next beacon message. Thus, the sleep states
of the nodes can be synchronized to avoid that a beacon is not forwarded
properly through the network due to nodes that are still not available because
51
of being in a low power mode. The sleep time after a beacon reception can be
calculated easily. The time of the beacon reception will be stored, then a node
sends its data messages and forwards incoming data packets. The resulting
work time of the node will be calculated by measuring the time when the node
has finished its forwarding activity and subsequently the time of the beacon
reception will be subtracted from it. Subtracting the work time from the beacon
interval time will have as a result the time for how long a node can remain in
the sleep mode without missing the next incoming beacon.
5.3.4.1 Route updates affected by sleep states
If once all nodes have found their predecessors, each node will know the
shortest way to the sink node. If due to position changes or after the addition
of network nodes, better routes will be available a node should automatically
be able to determine better routes. Normally, this process happens
continuously each time a beacon is transmitted, the node analyses each
beacon in order to determine a better route.
The following figure shows this situation:
Figure 23: Regular route actualization
52
At first node B is connected to node A in order to forward its packets to the
sink. Then because of a position change of node B, it gets into the range of
the sink node. It is not necessary anymore to use node A to transmit the data
packets to the sink. If no sleep mode is applied, node B updates its route to
the sink within the next beacon transmission cycle. This process is more
complicated if the sleep modes are activated. To save the maximum possible
amount of energy, a node will wake up a few microseconds before the beacon
will be transmitted by its already known predecessor.
Due to the network structure, possible better route offers are transmitted
before the node will wake up. Better routes are advertised earlier by nodes
that are located closer to the sink, therefore it is possible that nodes on
deeper levels of the tree are still sleeping, when nodes on higher levels emit
their beacon messages.
B
A B A
Position
change of
node B
Behaviour related to sleep mode
Figure 24: Route actualization influenced by sleep mode
After the position change of Node B it still has got node A as its predecessor.
When the sink sends the beacon, node B is still sleeping and it will only hear
beacons that are on the same level as node A. This situation makes it
impossible to inform nodes about better ways using nodes closer to the sink
as next hop and a solution for this has to be found. Even if the sleep mode is
activated the nodes should be able to optimize the route to forward the
53
packets. To do this, it is necessary to wake up a node after a certain period of
time, so that the network can reconfigure the routes depending on the hop
count. After a configured number of sleep cycles the node will be woken up
earlier. It will already be awake and able to listen to possible advertisements
that come from nodes closer to the sink that offer better route options.
To achieve this behavior, each node will do this route refresh after a
preconfigured number of cycles. The beacon message is used to activate this
behavior of a node, it contains a value that specifies after how many cycles a
node will leave the sleep state earlier. The regular sleep time will be
shortened by a parameter that is transmitted with the beacon message.
In a network where the positions of the node change more often, this value
should be smaller as in networks where the positions of the sensor devices
are fixed. A higher route update interval comes a long with a higher energy
consumption caused by longer idle times to wait for beacons. The adjustment
of these values depends on the network. For example, if all nodes are always
at the same position the route update rate can be configured with a low value
to achieve maximum power saving.
5.3.4.2 Healing mechanisms affected by the sleep st ates
Another situation that has to be considered is: what would happen if a node
that forwards packets for other clients has got a malfunction and is not
available anymore? The self healing mechanisms are not affected by the
sleep mode. If a node does not receive the expected beacon message of its
predecessor, the node will stay awake until it receives a new route offer. The
worst situation that can occur is, that a node will be switched on for one sleep
period. This causes a higher energy consumption and shortens the battery
live.
5.3.4.3 Self clocking feature of the network
Especially when the sleep mode is applied to the network it is required, that
the network is highly synchronized. That means, that a node that is in sleep
mode, must wake up shortly before a beacon message reaches the node. If a
54
node would miss a beacon message, this could cause in a loss of data,
because the node itself cannot forward the beacon to its successors. There
are several ways to achieve a synchronization of the network. One solution
would be to send periodically synchronization messages to adjust the internal
clocks of each node. Then the nodes could rely on the internal clock to
calculate sleep times and the time to send the data and beacon messages.
This solution has got the disadvantage that it is not very exact and it is
complicated to apply. A less complicated approach is to use an event driven
beacon transmission. That means that the beacon transmission of each node
is triggered by a valid beacon reception.
Figure 25: Beacon forwarding process
This procedure can be perfectly used to solve the timing issues of the
network. The node synchronizes itself each time of a beacon reception. When
a beacon is received then the exact wakeup time can be calculated. The
beacon contains the value for the beacon transmission interval. Knowing this
value, the precise wakeup time can be calculated as the following.
WorkrvalBeaconInteSleep TTT −=
After receiving the beacon, the node can enter the sleep mode for a time of
T_Sleep. This value is obtained by subtracting the work time of the node of
the beacon interval time. The work time is the time the node was busy after
receiver the beacon. When applying this formula, all nodes at the same level
55
of the network tree will wake up and transmit a beacon synchronously, even if
they enter the sleep state at a different time. In case an error occurs the
network will also be more resistant against malfunctions and will correct timing
issues itself. For instance, if the sleep time is not determined correctly, it could
result in two different scenarios: either a node wakes up earlier and will stay
awake until the next beacon message is received or it will sleep too long and
the beacon message will be missed.
The first case is less problematic, the node will just listen for the next beacon.
Here the only problem is that the wake-up time is longer than planned and
more energy is wasted. The second case has got additional negative side
effects. If a beacon is missed, it won't be forwarded to the neighbours of a
node. Accordingly, no transmission of a data message will be triggered by any
node that did not receive a beacon. The result is, that at least for one cycle
data messages from this branch of the network tree will not be transmitted to
the sink. In both cases the network is able to heal and resynchronize itself.
The node will receive the next beacon message and will be able to calculate
the sleep time correctly. Like this it is also impossible, that time differences
that could occur by mistake on different devices, propagate through the
network and accumulate in resulting that the whole system will be in an
unstable state. The self clocking functionality improves significantly the timing
of the network. In this way, sleep times can be very precisely calculated. This
exact calculation and predetermination of the sleep time reduces unnecessary
idle times where the devices consume a high amount of energy waiting for a
beacon. The device will wake up on time when a beacon is transmitted by its
predecessor.
5.3.5 Remote network configuration
5.3.5.1 Software parameters
In certain cases it is necessary to adjust the configuration of the network.
Several parameters of the software that is running on the sensor nodes
should be adaptable to certain conditions. One parameter that should be
56
adjustable is for example the beacon transmission interval. To change this
parameter at least two steps are necessary. To transmit the beacon in
different time periods, modifications at the program that runs at the base
station are required. Additionally each node needs to be configured with the
new time value. An independent configuration on each node would be quite
inefficient and not applicable in any case. A much more efficient way to
configure parameters for the whole network would be a solution to inform all
nodes at once about modified configuration remotely.
The beacon messages that propagate through the whole network can serve
perfectly as a carrier to deliver different control values to each node. Beside
the routing parameters, like the hop count value, more information can be
added to a beacon and each time a node in the network can apply the
parameters extracted from a beacon message. This solution keeps from
sending special control messages to the nodes. All parameters will be
configured at the base station and will reach each node without the need of
changing program code on each node. This is a very comfortable solution to
adapt the behavior of the whole network from one place.
5.3.5.2 Remote configuration of the radio transmi tters
Additionally to the configuration of software parameters, the radio receiver's
settings should be adjustable as well. The normal procedure is to directly
connect the XBee module with the serial port of a computer and configure the
parameters with the manufacturer's software suite. To avoid this process,
which is very time consuming especially in networks that consist of many
nodes, the possibility to modify this parameters remotely has been added to
the system. The wireless transmission unit can be configured with so called
AT modem commands. Al parameters of the XBee modem can be changed
with this command set. An AT command consists of a two character long
command followed by the configuration parameter. These instructions can be
included into the beacon message, too. This makes the adaptation of the
transmitter's behavior very comfortable. The whole configuration will be
broadcasted through the network and will be immediately applied. After
receiving a beacon frame that contains AT commands, the micro controller
57
will extract these commands and sends them to its modem unit before
forwarding this beacon message.
It is not always wanted to apply parameters to all nodes in the network. Some
parameters depend on certain conditions and should not be applied to all
devices. This could be for example a node that is located in an area where a
lot of interfering noise causes a packet loss. To increase the chance of a
correct packet transmission, the retransmission attempts of the modem
should be increased for this particular node. Or in some cases it could be
desired to change the address of a node. To achieve a delivery of the
parameters which are determined for a certain node, additionally to the AT
command a destination address can be specified. The parameters will be still
broadcasted through the network, but they will only be applied on the node
which matches the specified address. When the beacon message with the
configuration instructions reaches the destination node, this node will apply
the parameters and will remove them before it broadcasts the beacon.
The following table gives a list of some example commands:
AT - Command
Effect
RR Adjust additional retransmission attempts
RN Change the address of a node
MY Read the address of a node
RO Configure the packet RF length Figure 26: Example AT modem commands
5.3.6 Network load balancing
In this network communication is based on different nodes that act as traffic
forwarder for other nodes in the network. Furthermore, due to processing and
memory limits, a node can only handle a certain amount of traffic at the same
time. In order to reduce a bottleneck situation due to an overloaded node,
additional nodes that equilibrate this traffic concentration need to be added as
additional forwarders. This avoids congestion and a resulting data loss. To
use this additional forwarding nodes effectively, a so called load balancing
algorithm is needed. This algorithm tries to avoid the occurrence a of partial
58
load concentration, in case more forwarding nodes are available. The aim is
to distribute the traffic to all possible predecessors equally.
A big amount of forwarding activity always means a higher power
consumption due to a higher amount of receive and transmit actions. A load
balancer is of additional insurance due to the equilibrated usage of the
predecessor nodes that an earlier breakdown which helps avoid a power loss
of a single node. Different approaches to resolve the load distribution will be
discussed and analyzed in the following.
An example problem situation:
SINK
A B C
D E F G H I
Figure 27: Unbalanced network setup
The scenario illustrated in the figure above shows a network setup where the
load is not balanced. Node B has to process the traffic of 5 nodes, whereas
Node A only has got one successor and node C does not have to forward any
message. This situation could provoke that node B can not handle all
messages from its successors. The result is a bottleneck at node B and a
possible network congestion. Additionally the packets of the successors of B
are unnecessarily delayed, because they will be queued in the input buffer of
B before they can be processed. The chances that node B will be the node
that will run out of power at first are very high. If this would happen and for
instance the nodes F and G are only in the range of B. they could not forward
their data any more and would be isolated from the rest of the network.
59
A load balancing algorithm tries to avoid this situation mentioned before to
occur. It will try to setup the network like the following:
Figure 28: Balanced network setup
In this setup every node of the same level has to process the same amount of
data. This avoids the risk that one node is overloaded resulting in an early
breakdown. The nodes A, B and C that forward the network traffic, all forward
for the same number of predecessors. The load balancer is only able to
equilibrate the traffic on one node level of the tree. Because on the first level
there are only three nodes and on the second there are 6 nodes, it can not be
avoided that the nodes A, B and C have to do more work than the others.
When designing an algorithm to balance the load of forwarding nodes,
different solutions exist.
60
5.3.6.1 Analyzing different approaches
5.3.6.1.1 The round robin method:
This method distributes the traffic randomly to a set of predecessor nodes.
For instance in the figure node X would randomly choose the node A, B or C
to forward its traffic. This solution requires that node X is aware of the Nodes
A, B and C to be able to select one of them. It would require that node X waits
for all the incoming beacons from the nodes of the next level in the tree.
X
A B C
Figure 29: Round robin load balancing In the figure, node X has got the choice to select randomly one of its
predecessor nodes every time it transmits a data packet.
61
5.3.6.1.2 Alternating predecessor selection
A similar approach to the round robin solution is to continuously iterate over
all the predecessors. This guarantees that all predecessors of a node are
used equally. But unfortunately if the sequence of the predecessor selection is
repeated equally, a problem situation could occur:
Figure 30: Alternating load balancing
The figure above shows a problem that can occur using this approach. It
could be, that one or more successor nodes X run the same sequence to
select the predecessor. In sum the nodes A, B and C are used equally, but
during one transmission cycle the whole or a big amount of traffic is forwarded
by one single node.
62
5.3.6.1.3 Load balancing depending on load
A better solution to regulate the load distribution in the network is to analyze
the load of a node, before it will be accepted by another node as predecessor
to forward the data packets. for one cycle. To use this approach, the
successor nodes have to be aware of the traffic statistics of all the possible
predecessors. Nodes with a lower previous load are better candidates than
nodes that have already forwarded more packets. In this network the
realization of this approach is done as described in the following paragraph.
Each node forwards a message a counter will be increased. In the next
transmission cycle, this value will be broadcasted with the beacon message to
all nodes that are in direct range. All nodes collect the beacon messages of all
possible predecessors and analyze beside the distance indicator value, the
message counter of these candidate nodes. If this set of candidates contains
nodes that have a too large deviation of the message counter in comparison
to the others, these nodes will be removed from the set. After doing this a
predecessor is chosen randomly out of the remaining set of candidates. The
advantage of this algorithm in comparison with the simple round robin method
is, that this solution offers additional control. If a node has been loaded more
than other ones, this algorithm will detect this and unburdens this node until
the traffic situation is rebalanced again.
63
The following figure shows an example of the load balancer:
Figure 31: Example situation load balancer - balanc ed
In the figure, the load values under the nodes indicate a well balanced
network load. All nodes from A till E are seen as possible forwarders for node
X. All will be added to the set of candidates before the final predecessor will
be chosen randomly.
The control algorithm will act if the situation will look like this:
A EDCB
X
2 2 2 3 8
SINK
Figure 32: Example situation load balancer - unbala nced
This situation occurs, if the random algorithm has chosen more times node E
than the other nodes. The control algorithm will remove now temporarily the
64
node E from the set of possible forwarders until the situation is equilibrated
again. This will be the case when the difference between the load value of
node E and the smallest load value of a node in the set will be under a
configured limit. This algorithm combines the advantages of a random
selection with additional supervising functionality of the load distribution.
This selection process also includes the nodes that had an overflow at their
load indicator.
The processing steps of the load balancer are shown in the following flow
chart.
Figure 33: Load balancer flow chart
65
5.3.7 Data aggregation
When a node forwards the packets during one transmission cycle, it forwards
all packets to the same predecessor node. When forwarding a packet, for
each packet several processing steps have to be repeated each time. Each
incoming data packet has to be unpacked and repacked into a new frame
containing the correct addresses and other fields like the checksum which has
to be recalculated. Furthermore for each message that is forwarded,
additional bytes that are required by the API frame structure have to be
transmitted. Regarding this network, when using the 64 bit addressing
scheme, 15 bytes will be transmitted for each outgoing packet that are
required by the API-frame structure:
1 Delimiter 1 byte
2 1st length field 1 byte
3 2nd length field 1 byte
4 API - ID 1 byte
5 Frame - ID 1 byte
6 - 13 Destination Address 8 byte
14 Options 1 byte
15 Checksum 1 byte
Sum 15 byte
Table 4: Bytes of an API frame that have are transm itted beside the payload
On the modem side, each single data transmission costs additional energy.
Therefore it should be tried to keep the number of necessary data
transmissions as low as possible. Normally the data messages only contain a
small amount of bytes of sensor data which is far away of the maximum
packet size of 100 bytes. Not only the additional data overhead of each
packet has to be taken into account, more transmitted packets also produce a
higher amount acknowledgements. Reducing the transmitted packets results
in a higher throughput. Therefore it would be a good solution to pack several
messages into one data frame in order to save these additional 15 bytes for
each forwarded packet. Doing this, the data transmission is more efficient,
because fewer frames have to be transmitted by the modem.
66
When applying this feature to the network, several additional aspects have to
be considered especially the correct timing is important not affect the network
synchronization. .
After broadcasting a beacon message to the neighbour nodes, the emitting
node will wait for a limited amount of time to forward packets coming from
other nodes.
Therefore the time a node waits to aggregate incoming data packets has to be
smaller than the time a node waits for packets in order to forward the packets.
Not all messages can be aggregated, the own data message will be the first
message, a node sends after the beacon reception. The own data message,
containing the sensor data has to be send without using aggregation. This
process is necessary to avoid an increase of the waiting time of a node
depending on the maximum depth level of its successor nodes. This scenario
is shown in the following figure:
Figure 34: Figure exponential increase of the waiti ng time
This figure shows the time, that each node has to wait for a data message, if
all packets would be aggregated. For the sake of clarity, the processing times
of a frame are not included. It will be assumed, that each transmission
process takes one time period t. As illustrated, node A has to wait 6t , node B
4t and node C 2t to forward the data and do send its own data message in an
aggregated data packet. That means that the waiting time of node A depends
on the maximum depth of the whole tree and increases for each additional
depth level.
67
Each node has to be aware of the maximum depth level of its successor
nodes to be able to calculate the time it has to wait for a data packet to
forward it. Especially in a network with a dynamically changing network
structure, this approach is complicated to realize.
To avoid the scenario of a level dependent waiting time, the own data
messages will be sent in their own data frame. This results in the following
situation:
Figure 35: Homogeneous time forwarding intervals
The data messages reach a node in the same time intervals. This is not
affected by the maximum depth of the tree or the depth of a node. This
situation is used to trigger after each received frame a new waiting period for
another incoming frame to be forwarded.
The time periods when packets arrive at a node of a lower level are almost
the same for all packets coming from the nodes of the same level. Here a
packet aggregation can be applied.
The packet aggregation algorithm will only aggregate packets, which are
coming from the same level. This avoids the illustrated increasing of the
waiting time:
68
Figure 36: Data aggregation of data coming from the same level
As shown in the graphic, Node A forwards the packets of node B0, B1 and
B2Node . Therefore, that these Nodes are all on the same level, they will also
transmit almost all at the same time. The resulting delay is insignificant and
will not affect the normal forwarding operation.
A will wait for a limited amount of time for incoming packets to aggregate and
forward them. The messages themselves are not divided into parts. The
algorithm will put as much as possible messages into a frame. If 100 bytes of
payload are exceeded, a new frame will be used.
The time a node will wait until an aggregated packet will be transmitted is
linked to the main time out value for the packet reception. If this main time out
value expires, a node will enter the sleep mode. Therefore it is obligatory that
the aggregated packet will be transmitted before the main time out of the
predecessor expires to avoid that this one enters the sleep state before the
successor node has transmitted its packet.
69
Buffer packet
Wait for an
incoming data
message
Data message
arrives
Send
aggregated
packet
Buffer full or
timeout
No timeout
Stop
Timeout
Still space in
buffer
Figure 37: Packet aggregation algorithm
5.3.8 Duplicate packet detection
The when the modules are configured to use the MaxStream header, a
feature to identify doubly received packets is available. When configuring a
large number of retries, the possibility of duplicate packets increases: (1) a
duplicate packet is sent, (2) said packet is correctly received, (3) but the
acknowledgement got lost due to a collision. This scenario happens often,
because when an acknowledgement is transmitted, the module does not
apply the CSMA/CA algorithm and acknowledgements themselves are not
acknowledged. When performing system tests, duplicate packets where
received even if the modules should avoid this scenario. Then, an additional
duplicate packet filter on the application layer had to be implemented. Each
data message that is transmitted from a module contains an identification
number that is different for each message. When a node receives a message,
it stores the message number and the address of the original sender of that
message into a ring buffer, then, before a node forwards a message, it checks
if the combination of source address and package number already has been
forwarded. The following figure illustrates this process:
70
Figure 38: Duplicate message detection
6 Transmission reliability While transmitting to a shared media, like the wireless link that the network
uses to communicate, transmission errors can occur due to collisions of
packets. These collisions happen if two or more nodes that are in range
transmit at the same time. The receiver in this case is notable to determine
anymore who is the emitter of the current signals and the message will
become unusable. Another possibility of data getting lost while transmitting is
the presence of other noise on the transmission channel. Specially on the
license free frequency bands which uses the transmitters, there is more noise.
On these channels many other different devices can transmit and interfere
with the sensor network's signals. To achieve a certain amount of
transmission reliability and avoid collisions, two technologies are used:
- The CSMA / CA algorithm
- Acknowledgements
71
6.1 CSMA/CA (Carrier sense media access / collision avoidance) 25
This feature tries to avoid collisions by reducing the probability that more than
one end device transmit data at the same time. Before starting a transmission,
it will be checked if there is already one node transmitting. This is realized by
measuring the signal strength on the media before sending a radio packet. If
the signal strength is above a determined threshold, the modem will wait for a
randomly chosen back-off time and will retry to transmit. If after several
transmission retries the shared media is still busy, the transmission will be
stopped and the frame will be dropped. Unfortunately this technology can not
avoid collisions completely, there are two different scenarios where this
algorithm will fail. The first happens if two nodes transmit exactly at the same
time. Both will apply the CSMA/CA algorithm and will consider the channel as
free. This will cause that both nodes will start their transmission that results in
a collision.
Another possibility where the algorithm fails is the hidden terminal problem.
This scenario occurs when there are at least three nodes that want to
transmit. Node A wants to transmit to node B, therefore it runs the CSMA/CA
procedure and senses that the channel is free. At the same time a third node
C that cannot be heard by node A transmits to node B. Node A is not able to
sense this traffic and starts its transmission to node B. The result is that at
node B occurs a collision caused by the signals of node A and C transmitting
at the same time. Unfortunately it is not possible to detect a collision on the
transmitter side while transmitting like the CSMA/CD (Carrier Sense Media
Access/Collision Detection) algorithm does. The wireless transmitter does not
support a duplex transmission functionality and therefore it cannot receive and
transmit at the same time. In a wireless network additional mechanisms like
acknowledgement messages have to be applied to check if the message was
transmitted correctly or if it was destroyed by a collision.
25 Shahin Farahani. ZigBee wireless networks and transceivers, “CSMA-CA channel access, page 90
72
6.2 Acknowledgements
Additionally to the CSMA/CA algorithm the acknowledgement feature that
provides the 802.15.4 standard can be used to increase the reliability of the
data transmission. Each MAC layer frame that is transmitted has to be
acknowledged by the receiver. An acknowledgement message is a short
message that will be sent as an answer to the sender after receiving a
message correctly. If the sender does not receive the acknowledgement for a
frame, it will retransmit the same frame again. The 802.15.4 standard defines
three transmission attempts. But this approach is also not completely reliable.
The following failures can occur.
It may be that the frame is received by the receiver correctly, but an
acknowledgement is affected by a collision and hence not received by the
sender of the frame. This is quite possible, because acknowledgements are
not acknowledged, and when an acknowledgement is sent, the CSMA
algorithm is not applied. If the CSMA/CA back-off time would be applied, a
possible ACK timeout could occur at the sender of the frame. This would
cause another retransmission. If a frame has been received correctly but the
acknowledgement is not received, an unnecessary retransmission will occur.
Therefore, the same frame will be received by the destination device two
times. If applying this feature, the destination has to check for double received
frames and discard them. Due to a limited number of retransmissions this
algorithm can't guarantee a completely reliable data transmission, but it highly
increases the reliability.
6.3 Checksumming
The two processes mentioned above only try to increase the possibility that a
frame will be successfully transmitted. To work regardless of reliably with the
acknowledgement process, a feature to check the data integrity of the
message is needed. This is done by using a checksum algorithm. The aim of
a checksum algorithm is that the obtained checksum can only be generated
by the originally transmitted content, but it has to be mentioned that this
process is not as reliable like for a example a hash algorithm like for example
73
SHA1 or MD5. Like the other mentioned algorithms, this one can fail as well.
but the chance of it failing is very small. The algorithm calculates the sum of
the content of a data packet and therefore it is not completely reliable. The
original checksum could have a certain value and the checksum of the
content after the transmission of the packet at the receiver side could be
equal but calculated of a changed content. However this scenario is very
improbable and for the sensor network it provides a sufficient amount of
reliability.
Each time before a message is transmitted, a checksum of the message is
calculated and added to the data packet. On the receiver side the checksum
is extracted from the frame and the same checksum algorithm is applied over
the content of the frame. If the result equals the checksum that was generated
before transmitting the frame, the data is treated as correct and can be
acknowledged and be processed by upper layers.
The checksum algorithm26 that is used in this system works as following:
The sum of all bytes of the data payload is calculated. From this sum only the
lowest 8 bits are kept. The resulting value will be subtracted from 0xFF. To
verify the checksum, all bytes of the content are added and again the last 8
bits are kept. If an addition of the result and the checksum produce the value
0xFF, the checksum is correct. The following paragraph shows an example
calculation to obtain and to verify the checksum
Example calculation:
Given the following data payload:
The highlighted field indicates the checksum field at the end of a frame.
26 XBee product manual v1.xAx, http://ssdl.stanford.edu/ssdl/images/stories/AA236/0708A/Lab/Rover/Parts/xbeeproproductmanual.pdf Page 53 “Checksum”
74
1. Calculating the sum of the payload:
∑=
=9
0
490n
n CxByte
2. Keeping the last 8 bits:
CcbbbCx 4901100.100101111.111101100.1001.01000490 ==∧=
3. Subtracting result from 0xFF results in checksum
630900 xCxxFF =−
4. Verification:
630900 xCxxFF =−
The result 0xFF confirms at the receiver side, that the frame was successfully transmitted.
75
6.4 Flow control
Both devices that buffer data messages, the micro controller and the wireless
transmitter, have got a limited serial buffer capacity. When the buffers reach
their capacity, a possible buffer overflow could occur that results in a packet
loss. The buffer of the wireless modem has got a fixed capacity limited by
hardware. A buffer can occur if the following conditions are met:
6.4.1 Overflow due to CSMA/CA backoff
When there is a high traffic density on the shared media and the CSMA/CA
algorithm causes that the module has to wait for a transmission possibility, the
continuous data flow is interrupted. The wireless module cannot transmit as
fast as the data arrives and cannot buffer the data that is determined for the
transmission over the air.
6.4.2 Overflow due to acknowledgements
The module hast o wait for an acknowledgement until the module can remove
the transmitted frame out of the buffer. When more retransmission retries are
needed because of unacknowledged packets, the result can be a congestion
of the serial incoming buffer of the XBee module and results in a packet loss.
This scenario occurs when there is a lot of interfering traffic on the media or if
the hidden terminal problem causes the CSMA/CA algorithm to fail. The
hidden terminal problem occurs if two stations (A and B) want to transmit to
the same station (C).Station A and B cannot listen to each other because they
are too far away from each other. The CSMA/CA algorithm at node A and B
declares the media as free and the transmission to node C starts at both
nodes. The result is a collision at node C where the packets of A and B
collide.
To avoid a buffer overflow of the XBee wireless transmitter, it offers a
hardware controlled flow control system. If the input buffer of the modem is 17
bytes away of being full, it will de-assert the CTS pin (operating in negative
logic) which results in a logic 1. The CTS pin is connected to a digital input of
76
the micro controller. Before sending a byte to the wireless modem, the CTS
signal will be checked. If the micro controller detects that the CTS signal on
this pin is high, it stops the serial transmission until the CTS signal changes
again to logic 0. This is the case when at least 34 bytes in the memory of the
XBee module are free again. Like this, a buffer overflow of the input buffer of
the wireless transmitter can be avoided.
The serial input buffer of the ARDUINO micro controller is by default 128
bytes. On the micro controller side, an overflow of the input buffer can occur,
because the micro controller uses the main memory to store the incoming
serial data, the size can be adapted by software. The reading process of
incoming serial data is controlled by an interrupt service routine that is
processed each time serial data arrives on the serial line. The ISR reads the
available serial data and stores it into a ring buffer. The size of this buffer is
defined in one of the ARDUINO library files and can easily be modified.
(/hardware/lib/cores/arduino/HardwareSerial.cpp).
Several tests showed that a change from 128 bytes to 256 bytes completely
avoid buffer overflows. Hence no flow control for the data stream from the
wireless transmitter to the micro controller is necessary when operating at the
maximum possible serial transmission rate of 38400 bps.
The risk of a buffer overflow of the input buffer at the modem side can be
avoided if the serial line speed is kept lower than the radio transmission rate,
fixed at 250.000bps. But on the other hand the whole network performance is
reduced and the input buffer of the modem that buffers received data, coming
from the wireless interface can be overflowed. And the serial buffer of the
micro controller has to be increased to store the incoming serial data that will
wait longer to be processed due to a reduced transmission speed of the
connection between the micro controller and the radio transmitter. A bottle
neck situation would be the result.
77
6.4.3 Flow control system and data buffers 27
Figure 39: Figure Flow control system and data buff ers
The figure shown above gives an overview of the different buffers that are
available on the two components.
6.4.3.1 XBee Module
Radio buffers
TX-buffer
This buffer keeps packets until they are successfully acknowledged.
RX-buffer
The RX buffer stores the bytes of an incoming packet until the full packet has
arrived. If the checksum process is passed with a positive result, the packet is
passed to the DO buffer.
Serial buffers
DI-buffer
This is the serial input buffer of the XBee module where the serial coming
from the micro controller is stored. When the maximum size of 100 bytes of
payload is reached or when a packetization timeout occurs it will be passed to
the TX buffer, in case it is free. This buffer causes the CTS pin to be activated
if it runs in danger to be overflowed. 27 XBee product manual v1.xAx, http://ssdl.stanford.edu/ssdl/images/stories/AA236/0708A/Lab/Rover/Parts/xbeeproproductmanual.pdf Page 11, “Flow Control “
78
DO-buffer
The data is passed to this buffer after a frame has been received correctly by
the wireless interface. If data enters into this buffer it will be transmitted
immediately over the serial line.
6.4.3.2 Atmega168
DI-buffer
The micro controller works only with a serial input buffer. Incoming serial data
causes an interrupt which activates the reading from the serial line and the
data will be stored into the DI buffer. Outgoing data that is sent over the serial
line and is written immediately to the line without buffering it.
79
7 Network monitoring 7.1 Network visualization
In order to get information how the network organizes itself and in which
structure the nodes arrange themselves, a network visualization tool is
required.
A tool like this generates a graphical overview of the network showing all
significant data. A map which shows which nodes are used by others to
forward the messages is shown on a map.
There are several products available to simulate certain scenarios. But to
show the actual situation of the real network, an own tool in the programming
language JAVA, specially adapted to this network was developed.
The requirements of this application are a live monitoring with graphical output
of the network setup.
This program consists of three modules:
7.1.1 The communication module:
The communication module handles the communication with the network. The
framing, beacon transmission, frame parsing and the data reception are
processed by this module.
7.1.2 The statistics module:
To calculate network statistics, like packet loss rates and round trip times, this
module offers the necessary features to log the whole network traffic and to
generate a statistics summary.
7.1.3 The visualization module:
This module handles the whole visualization processes like adding nodes to
the network tree map and dynamically redraw the network map.
The following figures show some typical network maps that have been drawn
by the visualization tool.
80
7.1.3.1 Network map
Each red dot represents a network node and its address, the green lines show
which nodes are interconnected witch each other.
Figure 40: Network maps drawn by the visualization t ool
To visualize the tree structure in JAVA, a library called PREFUSE28 is used. It
offers several visualization possibilities and offers different graph drawing
features. Additionally it is available as free ware and can be adapted to the
user's requirements.
To generate the network map and especially to know which nodes forward the
packets of other nodes, the packets that are traveling through the network
have to be traced. Each time a node forwards a message, it stamps the
message with its own address.
28 http://www.prefuse.org
81
Like this, when a message arrives at the base station, the whole route a
message has taken can be backtracked. The notes are equipped with a so
called trace mode that activates the message stamping process. Additionally
to the address stamping feature, different values can be written to the data
message at the source node. Like for instance it is possible to add the value
of the signal strength of the last received beacon message to the data
message.
8 System tests and analysis To analyze the reliability of the system, different tests using different setups
will be executed. It will be analyzed how many messages will get lost in order
to test the reliability of the system. Additionally will be tested how different
modem parameters will affect the link quality.
The first setup will test the throughput of a single node. The tests will be
executed with an application that transmits in the predefined interval a beacon
message. The messages that are received by the base station will be
analyzed. The amount of transmitted messages will be compared with the
received messages from every node. The result is the percentage of the
packets that got lost during the transmission.
The tests that are based on a certain network structure are realized with the
disabled routing functionality to guarantee, that the nodes do not rearrange
themselves in the network.
Tests that analyze the structure adaptation depending on certain conditions
are done with the enabled routing functionality.
82
8.1 Section 1 - Reliability Test
All nodes directly connected
Beacon transmission: every 5 seconds
Total beacons transmitted : 1000
CSMA/CA Back-off exponent : 2
Route optimization: off
Description:
In this test all nodes want to transmit at the same time. This test is optimal to
adjust the modem parameters. Different configurations will be tested, the
values which will be adapted are:
- Additional transmission attempts
- CSMA/CA back off time
The aim is to find a configuration with the lowest possible packet loss.
Network structure:
Figure 41: Networks structure - all nodes directly connected
83
Results :
Figure 42: Packet loss against XBee retries
Additional XBee transmission retries Packet loss
0 56.38 %
1 2.72 %
2 0 %
Interpretation :
When analyzing these results, it points out that when 8 devices want to start
the transmission at the same time, the 3 retransmission attempts which are
defined by default by the 802.15.4 standard are not enough. For each XBee
retry, the MAC layer can execute up to 3 retransmissions. That means, in a
situation with a high traffic load, up to 9 transmissions are necessary to
successfully transmit an acknowledged frame. This test was done with using 3
as value for the back-off exponent of the CSMA/CA algorithm. Also it is
interesting to see what will happen when modifying this value.
84
8.2 CSMA/CA - backoff exponent adaptation
Results:
Figure 43: Packet loss against CSMA/CA backoff expo nent
CSMA/CA back-off exponent Packet loss
0 1.72 %
1 1.15 %
2 0 % Interpretation:
As seen in the diagram and in the table the packet loss rate is decreasing with
a higher back-off exponent. This exponent is part of the formula that
calculates the random back-off time that the module waits for the next
transmission attempt. When the value is set to 0, the module does not use the
CSMA/CA algorithm at the first transmission attempt. This explains the higher
loss rate of 1.72%, because the modules all transmit at the same time without
sensing the carrier. When configuring a higher exponent, the maximum total
backoff time will be longer. The resulting larger domain of possible backoff
values causes that different carrier access times of the nodes vary more from
each other. This explains a reduction of the packet loss with increasing
backoff exponent.
85
8.3 Throughput test – all to one
Beacon transmission: every 5 seconds
Total beacons transmitted: 1000
CSMA/CA backoff-exponent : 2
XBee retries: 2
Route optimization: off
Description:
This test is similar to the previously described test. The only difference is, that
now one node has to forward the traffic of all the other nodes. If the package
aggregation functionality is enabled, node 1 should at first buffer all incoming
packets and then forward them using just one frame.
Network structure:
Figure 44: Network structure - All to one
The test resulted with a success rate of 98%.This is not surprising, because
the risk of a collision is even smaller than in the setup shown before. In this
setup 7 nodes are transmitting at the same time, this is one node less than
before. Node 1 does not have to expect any collision at all. When node 1
transmits, all other nodes have already finished their transmission.
86
8.4 Forwarding chain - throughput test
Beacon transmission : every 5 seconds
Total beacons transmitted: 1000
CSMA/CA backoff-exponent : 2
XBee retries: 2
Route optimization: off
Description:
This test analyzes the reliability of the forwarding chain. Here the
synchronization is very important and will be tested. An imprecise timing could
cause, that a node will sleep too long and overhears the beacon. Additionally
can be tested if the timing of the packet aggregation algorithm works correctly
and if this delay affects the regular network operation.
Network structure:
Figure 45: Network structure - Chain setup
Results
This test results in a reliability of 98,7% using the values that were previously
determined in the first test. If a high timeout for the packet aggregation
algorithm is chosen. It turns out that the whole forwarding speed is
significantly reduced, because a packet won’t be forwarded until a timeout
occurs. But it turns out, that also if a big timeout is chosen (90% of the whole
message timeout) the whole message flow wont be interrupted. This confirms
that the timer2 and the algorithm running on the nodes offer the necessary
exactness.
87
8.5 Tree - load balancer test
Beacon transmission: every 5 seconds
Total beacons transmitted: 1000
Description:
This is a typical structure the network could form in reality. In the test
environment the nodes of level 2 which are 4,5,6,7 and 8 will have the
possibility to choose between the nodes 1, 2 and 3. At the end the load of
these two nodes should be equilibrated. Also for this test the routing algorithm
had to be modified, to achieve that the sink will be excluded from the set of
possible predecessors. The test will be realized using two different settings.
The first test cycle will run with the additional correction of the random
predecessor selection. That means that each node of the nodes 1, 2 and 3
will always be in the set of possible predecessor candidates.
The second cycle will run with the additional correction function. If one node
exceeds the forwarding limit, it will be excluded from the set of forwarders until
the situation is equilibrated again.
Network structure:
Figure 46: Network structure load balancer test
88
Results:
Figure 47: Uncontrolled- against controlled load ba lancing
Explanation:
The chart compares the results of the two different tests with each other. The
black bars show the number of forwarded packets of the nodes 1, 2 and 3
without the additional correction of the random values. The values differ from
312 to 350 forwarded packets, which shows an un balanced forwarding
activity. Node 2 forwarded almost 40 packets more than node1.
The bars in blue show the results with the enabled control function, here
points out that the maximum difference of forwarded packets is only 7. Node 3
forwarded the maximum number with 335 packets and Node 1 forwarded 328
packets. The obtained results definitely show that the additional control
function can help to equilibrate the usage of nodes that are used as
forwarders.
89
8.6 Reaction to node breakdowns
This test simulates a malfunction of a predecessor node in order to analyze
the reaction of the nodes that used this node as forwarder.
In a tree structure, like in the load balancer test, each node can choose out of
a set of predecessors. A breakdown of a node would have as result, that the
in the set of possible forwarders would be one node less. A node breakdown
should not be a problem for the network if there is more than one
predecessor.
If there does not exist a predecessor candidate to forward the packets using
the shortest way, a node will have to search for another forwarding possibility
taking into account that this new route is not the shortest one. The node
should select of all other possibilities the one that offers the shortest distance
to the sink.
Network structure: Situation before the node breakdown:
Figure 48: Network situation without broken links
90
Node E forwards the traffic of F and has got the predecessor candidates C
and D. Node C can only listen to A, E and F. Node D is in range of B, E and F.
Now a breakdown will be simulated at Node A. After this, node C will have the
choice to select node E or node F. Hence node F advertises a longer route to
the sink, node E should be chosen as a predecessor.
Situation after the node breakdown of node A:
Figure 49: Network setup with a broken link Observations:
After switching off node A, wakes up and does not receive the expected
beacon from node A. Because of this, node C waits for other route offers to
arrive with a beacon message. In the next transmission cycle, node C first
receives the beacon of E and accepts it. A short time afterwards, it receives
the beacon message of node F. This message is discarded correctly, because
of the longer route to the sink. The resulting network structure is shownin the
figure above. The network has successfully reorganized itself.
91
8.7 Energy consumption
As described in the paragraph “power saving”, several sleep modes have
been applied to the system to reduce the power consumption when the
system is in idle.
In the following test it will be analyzed, how much power in total can be saved
by activating the sleep modes and by disabling additional components of the
micro controller.
It will be assumed, that the test node is powered by 2 AA sized alkaline
batteries.
Power consumption:
XBee module – idle Arduino board Total
49,5 mA 7,2 mA 56,7 mA
Power savings:
XBee module – hibernated Reduction factor Power sav ing [%]
10 µA x 4950 99,98
Atmega 168 – power_down mode Reduction factor Power saving [%]
0,26 mA x 27,69 93,39
0,16 mA (AD-converter off) x 45,00 97,78
Atmega 168 – power_save mode Reduction factor Power saving [%]
1,24 mA x 5,65 82,78
1,14 mA x 6,30 84,17
Unfortunately the power_down mode cannot be used in this system because
of the already mentioned inaccuracy of the watchdog timer (Refer to
paragraph:” System behavior using Sleep mode - POWER_DOWN “).
92
Forecast of the possible system uptimes
The calculations are based on the formulas mentioned in paragraph “Power
saving - Calculation of the possible uptime”:
)(*)*(*
)(*
XBeeMCXBeeMC IdleIdleIdleTxTxTx
IdleTxTotalTotal IITIIT
TTQT
+++
=
TotalQ : Total capacity of the batteries.
TotalT :
Total possible battery lifetime of a node.
TxT : Active time for each cycle where a node is awake.
IdleT : Sleep time each cycle where a node is in sleep mode.
MCTxI : Current of the micro controller in active mode.
XBeeTxI : Current of the XBee module in active mode
MCIdleI : Current of the micro controller in sleep mode.
XBeeIdleI : Current of the XBee module in sleep mode.
TotalN : Total number of transmission cycles
XBee module: Sleep mode pin_hibernate. Power supply: 2 x 1.5 alkaline batteries in series with a capacity of 2000mAh Uptime each cycle: 4s Sleep time: 30 s
Example calculation for sleep mode power_save:
)01.014.1(*30)507(*4
)304(60*60*2000
mAmAsmAmAs
ssTTotal +++
++=
This results in a total uptime of 259 h. By increasing the sleep time, the
battery duration increases significantly.
93
The following figure shows the theoretical uptime of a node, in both available
sleep modes of the micro controller:
Uptime each cycle: 4s
Figure 50: Total possible uptime of a node
Interpretation:
The graph above shows clearly, that the only applicable sleep mode for this
network, the power save mode, definitely still consumes much more power
compared to the power save mode. Especially when applying longer sleep
times, in the range of 600 seconds, the expected battery life is almost three
times higher in the power down mode.
This confirms, that there is definitely a demand to find a less energy
consuming wakeup source for the micro controller.
94
9 Program code and explanations In this section important code parts and algorithms will be explained.
9.1 The setup method
This method will be executed each time the controller starts up after a reset or
after powered on.
001 002 003 004 005 006 007 008 009 010 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028
void setup() { pinMode(PIN_LED, OUTPUT); pinMode(PIN_MODEM, OUTPUT); pinMode(PIN_CTS, INPUT); digitalWrite(PIN_MODEM,LOW); //switch on modem Serial.begin(9600); //initialize serial interface delay(500); Serial.flush(); //16 bit address detection byte my[2] = {(byte)'M',(byte)'Y'}; sendApiFrame(my,my,4, 0x08, 0); // request mac delay(20); //wait for the parameters to arrive readAPIFrame(); //read answer for(int i=0;i<(ADR_LENGTH);i++) //store answer mac[i]=msg[i]. Serial.flush(); //prepare the processor for the sleep mode TCCR2B|= (1<<CS22)|(1<<CS21)|(1<<CS20); //Prescaler TCCR2A = 0b00000000; //normal mode TCNT2= 0; //reset timer 2 counter value sei(); //global interrupt enable bit //initialize the random function randomSeed(analogRead(1) + analogRead(2) + ___ ______________ analogRead(3); return; }
Pin declaration
In this method it will be specified which IO pins are used and if they are used
as input or output. When connecting a sensor to one of the digital pins, it must
be listed in the setup routine.
The initialization is done with the pinMode function. This function accepts two
parameters, the first one is the pin number and the second is the direction.
95
For example if pin 7 should be set as digital input and 12 as output, the
following parameters have to be specified (lines 2-4):
The pin setup is only necessary for digital pins, the analog pins cannot be
used as input.
Serial line setup
Before the serial line can be used, it has to be initialized using the correct line
speed.
This is done by calling the function Serial.begin(), the maximum operating
speed is 38400, the default speed of the devices is 9600 (line 6).
Setting the timer registers
To activate the timer2 interrupts that wakeup the controller from sleep mode,
beside the interrupt service routine, some processor registers have to be set:
The TCCR2B - Timer/Counter Control Register B defines the used timer
prescaler to predevide the processor frequency in order to reduce the counter
speed. Setting the bits CS22, CS21, CS20 to one sets the prescale factor to
1024 (line 020). Setting the TCCR2A - Timer/Counter Control Register2A sets
the timer mode to normal mode, that means after an overflow it starts again to
count from zero (line 021).
Initialize the random algorithm
To achieve that the random function on each node generates different random
values, it has to be initialized with different start values (line 024). The analog
inputs can be used to obtain different values on each node.
This solution provides the randomSeed() function which is responsible for the
initialization of the random function with different start values on each device.
96
Sleep Control
The sleep control is implemented using two functions, the sleep function, that
activates the sleep mode and the interrupt service routine (ISR) that wakes
the controller up again.
The interrupt service routine
The interrupt service routine will be executed when a timer2 overflow interrupt
occurs.
The compiler identifies the ISR with the argument TIMER2_OVF_vect (Timer2
overflow vector) which specifies the vector that triggers the execution of this
routine.
If the software counter (sleepcounter) reaches the configured sleep time
(sleepValue), the timer will be switched off. This is done by setting the Timer
Interrupt
Mask Register2 TIMSK to zero. This stops the interrupt generation of timer2.
001 002 003 004 005 006 007 008 009 010 012 013 014
ISR(TIMER2_OVF_vect) { sleepCounter ++; //if the sleep counter reaches the timer value, the //timer will be swithched off if (sleepCounter == sleepValue) { TIMSK2=0; sleepCounter=0; timerEnabled=false; //switch off the timer } }
9.2The sleep function
When all transmitting actions are done, the doze function will be called. The
timer2 overflow interrupt will be enabled and the sleep mode on the micro
controller will be enabled.
001 002 003 004 005
void doze() { TCNT2 = 0; //enable timer2 overflow interrupt TIMSK2 |= (1 << TOIE2);
97
006 007 008 009 010 012 013 014 015 016 017 018 019 020 021
//set the leep mode set_sleep_mode(SLEEP_MODE_PWR_SAVE); sleep_enable(); //enable sleep mode sleep_mode(); //put the controller to sleep // here the controller will continue after wakin g up sleep_disable (); //disable the sleep mode if(timerEnabled==false) { //enable components ADCSRA |= bit(ADEN ); //enable adc digitalWrite(PIN_MODEM, LOW); //switch on modem delay(12); } return; }
The steps to start the sleep mode are the following:
Line 3: Resetting the timer2 counter value.
Line 5: In the timer interrupt status control register TIMSK2 is the timer
overflow interrupt bit set to 1. This will produce an overflow
interrupt that wakes the controller up
Line 7: Here will be defined which sleep mode the controller should enter.
Line 8: This function enables the global sleep bit of the Atmega168 which
causes the controller to enter the specified sleep mode.
Line 12: The code as this line will be executed when the controller has
woken up again. This function resets the global sleep control bit.
Line 13: If the timerEnabled variable has been reset in the ISR all the
deactivated devices will be enabled again
Line 16: Enables the analog digital converter by setting the AD-enabled bit
(ADEN) in the ADC status register A (ADCSRA).
Line 17: By setting the digital output, specified by the variable
PIN_MODEM, to logic zero, the modem will wake up from the pin
hibernate sleep mode. The wake up time of the XBee module is
specified with 12 msec. The delay function call in line 14 realizes
this waiting time.
98
9.3 API frame
This function Read an incoming identifies and parses and incoming API
frame. It can be divided into three different parts. In the first part the serial
data stream will be read until a frame delimiter is detected. If this is the case,
the global parameters like the length and the API identifier will be extracted. In
the third step, depending on the API identifier further frame fields will be red
and depending on the content different process functions will be called.
001 002 003 004 005 006 007 008 009 010 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048
void readAPIFrame() { int i=0; /*INIT VARS*/ delimiter= 0; length = 0; apiID =0; for(i=0;i<MSG_LENGTH;i++) msg[i]=0; for (i=0;i<ADR_LENGTH;i++) saddr[i]=0; i=0; /******BEGIN READ PROCESS*******/ /*READ FRAME DELIMITER*/ while(delimiter != DELIMITER && Serial.available() > 0) delimiter=Serial.read(); //when a delimter has been found if(delimiter == DELIMITER ) { /****READ LENGTH AND API-IDENTIFIER****/ while(Serial.available() < 3){} if(Serial.available() >= 3) { Serial.read(); length = Serial.read(); apiID = Serial.read(); //take a decision for the processing of th e //frame depending on the API Identifier switch(apiID) { case(0x81): //incoming frame with data //payload 16bit - addressed //wait until all bytes of the message a rrive while(Serial.available()<length){} /****READ RSSI, OPTIONS, PAYLOAD AND CHECKSUM****/ if(Serial.available() >= lengt) { // read the source address for(i=0;i<ADR_LENGTH;i++) saddr[i]=Serial.read(); rssi = Serial.read(); options = Serial.read(); i=0; // determine the length of the
99
049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091
// incoming payload inMsgLength=length-5; // reading message while( i< (inMsgLength)) msg[i++]=Serial.read(); // reading checksum chkSum = Serial.read(); // process the beacon // or datamessage processMessage(); break; case 0x89: //transmission status while(Serial.available()<3){} if(Serial.available() >= 3) { for(i=0;i<3;i++) Serial.read(); } break; case 0x88: //AT command response while(Serial.available()<length){} if(Serial.available()>= length) { for(i=0;i<4;i++) Serial.read(); i=0; //reading message while( i< (length-4)) msg[i++]=Serial.read(); } break; default: break; } //END -> switch(apiId) } //END -> if(Serial.available() >= 3) } //END -> if(delimiter == DELIMITER ) return; }
Line 16: In this loop, each cycle one byte of the serial ring buffer will be
extracted and check if it is the beginning of a new API frame.
Line 20: If a delimiter has been found the processing of the frame starts.
Otherwise the function will be left.
Line 31: After reading the global frame information parameters, the further
processing depends on the API identifier.
Line 33: If the API id equals 0x81 the incoming frame contains a message
payload and a 16 bit source address.
Line 42: The source address is parsed
100
Line 44: When receiving a data packet, the local modem ads the signal
strength of the last received packet as a field to the frame, the so
called RSSI (Radio Signal Strength Indicator).
Line 45: The options byte contains additional control information that are
not needed and therefore not considered.
Line 51: Here the payload of the frame is extracted. In this system this
could be a beacon message or a data message containing the
sensor data.
Line 58: After storing the message in the global message buffer, the
message processing routine will be called, (See paragraph:
Message processing)
Line 61: After sending an API frame, the local modem sends a status
message containing transmission information. This information
wont be analyzed and is dropped. A modem status frame is
identified by the API id 0x89.
Line 71: In order to configure the local modem, API frames containing the
AT commands are send to the XBee module. This configuration
requests are confirmed with a at command status frame. Also this
frame will be dropped. This frame is identified by the API id 0x88.
The function continues until the serial input buffer is empty. In combination
with the sendApiFrame() function, it is the interface to the mac layer and
handles the whole communication with other network devices.
9.4 The message identification and processing
The message processing is a core part of the whole communication in the
network. This network uses two kind of messages: Beacon messaged and
data messages. They will be identified by a message control sequence at the
beginning of a message.
101
001 002 003 004 005 006 007 008 009 010 012 013 014 015 016 017 018 019 020 021
void processMessage() { int i=0; if(msg[i++]== 0x40 )//reading the message prefix { prfx=msg[i++]; switch(prfx) { case 0x42: //the incoming packet is a beacon readAndStoreBcn(); break; case(0x44): //else if is a data message if(hasNextHop==true) aggregate(); //buffer the message brake; default: break; } } return; }
Line 4: Here the global network message identifier will be check, a
message will be accepted only, if it begins with 0x40.
Line 9: If the message sub identifier is 0x42, it is a beacon that will be
further processed.
Line 13: The identifier 0x44 identifies a data message. If the current node
has got a next hop to forward the message, it will store the
message in order to aggregate the message with other incoming
messages in one single data frame.
102
9.5 The predecessor candidate collection process
The task of the following function is to collect all incoming beacon message
and to filter out the beacons that do not advertise an attractive route.
The function is divided into two parts, one part that is active if the network is in
dynamic mode (line 34 - 62)and the other part controls the behavior using the
static mode (line 9 - 32).
001 002 003 004 005 006 007 008 009 010 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048
void readAndStoreBcn() { int j=0; int i=0; byte newHc=0; //start after beacon prefix @B //read the address of the advertised next-hop for(i=2;i<ADR_LENGTH+2;i++) advNextHopAdr[j++]=msg[i]; //read hopcount of the incoming beacon message newHc=msg[i++]; //if the routing is disable if (routing == false ) { //compare if the beacon is from the curre //predecessor //saddr is a global variable that contains the //sender address of the received last packet if(linked==false || (compareAdr(localNextHopAdr,saddr)==true)) { //take the time of the beacon reception bcnReception = millis(); //extract the global configuration //parameters of the beacon message extractGlobalConfigParams(); //check if at command has been received if(getFlag(POSSC_AT) == true) applyATC(); //the first beacon after wakeup indicator waitingForFirstBeacon=false; hopUpdated=true; if(linked==false) { for(i=0; i<ADR_LENGTH; i++) localNextHopAdr[i]=saddr[i]; //set the linked flag linked = true; //add the beacon into the buffer storeBeaconInformation(); } setNextHop(); } } else if (routing == true) { //prefilter the beacon, check if it is a valid
103
049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084
//candidate for this node if( ( ((newHc == localHc-1) && !compareAdr(advNextHopAdr,mac) ) ) ||hasNextHop == false ) { extractGlobalConfigParams(); //check if at command has been received if( rtcc0!=0 && rtcc1!=0 ) applyATC(); //if it is the first beacon after wakeup if( waitingForFirstBeacon == true ) { bcnReception = millis(); waitingForFirstBeacon = false; //for the moment the new beaconHC is the //smallest newHC smallestHc = newHc ; } //if a beacon with a lower hopcount was //received as the currently smallest kno wn //value else if( (newHc < smallestHc) ) { //update the smallest known hopcount smallestHc=newHc; //and clear all hops that are bigger //than the new smallest hc cleanUpBeaconBuffer(smallestHc);} bcnCount++; //add the beacon into the buffer storeBeaconInformation();} } return; }
9.6 Static mode
Line 14: Here is checked if the routing enabled flag is set.
Line 20: In this line will be checked, if the node is not already statically
inked to a predecessor or if a beacon from the predecessor is
received. These are the two necessary conditions that have to be
fulfilled to accept a beacon using the static mode.
Line 24: The time of the incoming beacon is measured. Refer to paragraph
"Self clocking"
Line 27: The global configuration parameters which are transmitted by the
base station are extracted.
104
Line 29: The AT command flag is checked in order to know if the local
radio transceiver should be reconfigured by sending an AT
command.
Line 30: Refer to paragraph "Remote AT command execution."
Line 34: The node will be linked statically to a predecessor node.
Line 41: Dynamic beacon parameters are extracted, like hop count and
load value.
Line 43: The address of the next hop to forward packets is written to the
next hop address register.
9.7 Dynamic mode:
Line 50: The criteria to accept a beacon message is that the advertised
distance to the sink is smaller or equal than the already known
distance and that the advertised nexthop is not the local node
itself.
Line 60: Accept the first incoming beacon after waking up
Line 66: The distance value of the beacon will be set as the current
smallest one.
Line 72: If a beacon with a smaller hop counter value arrives, all
candidates of the buffer with a bigger distance will be removed.
Line 82: Each incoming beacon that fulfils the criteria of line 50 will be
stored in a buffer.
105
9.8 The predecessor selection
After the timeout occurs the following function selects from the set of possible
predecessor candidates the optimal one. The function will return the index of
the slot of the candidates list that contains the information of the selected
predecessor node.
001 002 003 004 005 006 007 008 009 010 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045
int getNextHopIndex() { byte smallest=0; int i=0; int j=0; boolean run=true; //initialize indexes of the candidates index a rray for(i=0;i<BCN_MAX;i++) nextHopCandidates[i]=BCN_MAX+1; i=0; j=0; //find the first used slot while(i< BCN_MAX && run == true) { if(beacons[i].used== true ) { run=false; smallest = beacons[i].loadValue; } else i++; } //finding the smallest value for( ; i<BCN_MAX;i++) if(beacons[i].used == true && beacons[i].loadValue < smallest ) smallest = beacons[i].loadValue; //finding all candidates //that are below the allowed limit j=0; for( i=0 ; i<BCN_MAX; i++) { byte a= (beacons[i].loadValue - smallest); byte b=(smallest-beacons[i].loadValue ); if(beacons[i].used == true && (a < loadLimit || b < loadLimit)) { //store all indexes of the possible candidates nextHopCandidates[j++]=i; } } return random(0,j); }
106
Line 15: The first slot that contains a candidate is determined.
Line 26: The candidate with the smallest load indicator is determined.
Line 27: Now all candidates that are below the maximum derivation of the
load indicator are determined and their indexes are stored into a
buffer.
Line 36: If the load value of the current candidate minus the smallest value
is below the maximum derivation, this node will be accepted.
Line 38: This condition is needed to correctly determine the deviation after
an overflow of the load indicator which has got a maximum of
255.
Line 45: Out of all accepted candidates one will be chosen randomly.
107
9.9 Self clocking
The self clocking algorithm is based on time measurements and calculations
at different key points in the code:
In the function readAndStoreBcn():
Line 018/053: bcnReception = millis(); When the first beacon in static or dynamic mode is accepted the time is
measured and stored. The millis() function returns the time in milliseconds of
the uptime of the micro controller after switching on the board. Knowing this
time, it is possible to calculate the arrival of the next beacon with the help of
the sleep time that is transmitted by the base station as value in the beacon
message. This is done in the main loop. Before the node enters the sleep
mode, the possible sleep time is calculated:
At first the time, the node has worked is calculated:
workTime =((millis()-bcnReception));
The current time is taken and the time of the beacon reception will be
subtracted. The result is the uptime after the node has received the first
beacon.
The sleep time in milliseconds is obtained by the following equation:
sleepValue=((sleepValue- workTime ))/34;
The sleepValue is the value that is transmitted in the beacon message, from
this value the previously calculated work time is subtracted. The result is the
possible time a node can sleep to be able to wake up early enough to receive
the next beacon message. The last step is to divide the result by 34 to adapt
to the sleep value to the overlfow62 frequency of timer2 which is configured to
62.5 Hz.
108
9.10 Packet aggregation
The packet aggregation algorithm works with a buffer that stores all incoming
packets until a timeout occurs which causes the transmission of all stored
packets. The transmission is also triggered if the buffer gets full.
001 002 003 004 005 006 007 008 009 010 012 013 014 015 016 017 018 019 020 021 022 023 024
void aggregate() { inti= inMsgLenth; if(duplicatePacket() == false) { //BEGIN STAMPING msg[i++]=0x5B; for(j=0; j<ADR_LENGTH;j++) msg[i++]=mac[j]; msg[i++]=0x5D; //END STAMPING //check if message fits into buffer if( i <= (AGR_BUFFER_SIZE-agrIndex) ) bufferMessage(i); else //send the aggregated packets { sendAggregatedPacket(); bufferMessage(i); } storeForwardedMsgInfo(); } return; }
Line 3: The variable i is initialized with the message length.
Line 4: If the message passes the duplicate packet check, it will be
accepted.
Line 6: The message will be stamped. The local address will be attached
to the end of the message between brackets (’[’ (0x5B) and ‘]’
(0x5D)).
Line 14: If there is space in the buffer for the message, then it will be
stored. The variable agrIndex points to the current position in the
buffer array.
Line 28: If the message did not fit into the buffer anymore, all aggregated
packets will be sent and the message is written into the buffer.
Line 21: The address of the message origin in combination with the
message number will be stored to identify duplicate packets.
109
9.11 API frame construction
Before a message of any content can be transmitted, it has to be packet into
an API frame. This frame is generated with the following function:
001 002 003 004 005 006 007 008 009 010 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057
void sendApiFrame(const byte destAddr[], byte content[],int length, byte apiID, const byte opt) { //--init variables int i=0; int j=0; for(i=0;i<MSG_LENGTH+11;i++) p[i]=0; /***PACKET ASSEMBLY***/ i=0; p[i++]=DELIMITER; //frame delimiter p[i++]=0x00; //first length field i++; //second length field will be written later on p[i++]=apiID; //--api id p[i++]=++frameID; //frameId switch(apiID) { //16 bit address transmit request case 0x00 : //write destination address to packet case 0x01: { for(j=0; j < ADR_LENGTH ;j++) p[i++]=destAddr[j]; p[i++]=opt; //options p[3]=length+5; //length recalculation break; //AT command transmit request case 0x08: p[3]=length+2; //length recalculation break; default: break; } //writing the data payload for(j=0; j<length;j++ ) p[i++] = content[j]; p[i++]=calcChkSum(p,i); //adding the checksum /***FRAME TRANSMISSION***/ j=0; while(j<i) { // character escaping if((p[j]==0x7E || p[j]==0x7D || p[j]==0x11 || p[j]==0x13) && j!= 0 ) { transmit(0x7D); transmit(p[j]^0x20); } else transmit(p[j]); j++; } return; }
110
Line 21: Depending on the type of frame, different fields are written to the
data packet p which will contain the data frame that will be
transmitted.
Line 28: To transmit a message over the network, the destination address
is an obligatory field that has to be added.
Line 31: The length will be increased by 5, because 5 fields, the API id, the
frame ID, the destination address and the options bytes have
been added additionally to the packet.
Line 35: In case an AT command will be transmitted, the length will be
increased by 2. Only the API identifier and the frame ID are
added as length affecting fields.
Line 42: The data payload, which can be a network message or an AT
command, are added to the packet.
Line 50: If the content, except the first byte (delimiter), contains a byte
value that has to be escaped, it will be XOR’d with 0x20 before it
will be sent through the serial line to the XBee module.
111
9.12 Flow control system
The flow control function controls the serial transmission and prevents the
serial input buffer of the XBee module from being overflowed.
001 002 003 004 005 006 007
void transmit(byte in) { if(getFlag(POSC_FLOW_CONTROL)== true) while(digitalRead(PIN_CTS) == HIGH){} Serial.write(in); return; }
Line1: As argument, the byte that should be transmitted has to be
passed.
Line3: If the flow control flag is set, the algorithm will wait while the
controller receives a signal on the digital input that is connected
to the clear to send pin of the modem. This prevents an overflow
of the modem’s serial input buffer.
Line5: The serial.write() function finally writes the byte to the serial line.
9.13 Unescape process of incoming characters
To unescape characters that are received by the XBee module, a function in
the serial line access control class of the ARDUINO library has to be modified
in order to prevent that escaped characters will be written into the serial input
buffer of the micro controller. It would cause malfunctions of the
readAPIFrame() function, because the waiting routines which stop the reading
process are not aware of the content of the serial buffer. These routines just
wait until a the required number of bytes are available. If escaped characters
would be included into this set of bytes, this solution would not work correctly.
The class that has to be modified is the “HardwareSerial” class. There the
function store_char has to be modified.
112
001 002 003 004 005 006 007 008 009 010 012 013 014 015 016 017 018 019 020
inline void store_char( unsigned char c, ring_buffer *rx_buffer) { if(c == 0x7D) //check for an escape identifier escapeNextChar=1; else { if(escapeNextChar) { c=c^0x20; escapeNextChar=0; } int i = (rx_buffer->head + 1) % RX_BUFFER_SIZE; if (i != rx_buffer->tail) { rx_buffer->buffer[rx_buffer->head] = c; rx_buffer->head = i; } }
Line4: If an escape identifier is detected the ecapeNextChar flag will be
set.
Line8: If the escapeNextChar flag is set the incoming character will be
unescaped before it will be stored into the serial ring buffer.
113
9.14 Data message assembly 001 002 003 004 005 006 007 008 009 010 012 013 014 015 016 017 018 019 020 021 022
void sendDtaMsg() { int j=0; int i=0; //building data message //first bytes identifies a network message msg[j++]=0x40; //second byte specifies message type msg[j++]=0x44; //adding own source address for(i=0;i<ADR_LENGTH;i++) msg[j++]=mac[i]; msg[j++]=msgcnt++; /******ADD HERE OWN PAYLOAD*********/ sendApiFrame(localNextHopAdr, msg, j, 0x01, getFlag(POSC_TX_OP T)); return; }
Line 7: The network message identifier will be written as first byte of the
message
Line 9: The data message identifier informs all devices that process this
message, that the message contains data which has to be
forwarded to the base station
Line 13: The own source address is added.
Line 12: Each message has an identifier which is used in the duplicate
packet detection algorithm.
Line 14: Here the sensor data can be added to a data message.
Line 19: Before leaving the function, the data message will be transmitted.
114
9.15 The main loop 001 002 003 004 005 006 007 008 009 010 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060
void loop() { unsigned long count =0, bcnInterval=0; if(timerEnabled==true) goToSleep(); else { Serial.flush(); messageForwarded=false; hopUpdated=false; beaconTransmitted=false; waitingForFirstBeacon=true; //clear the buffer that //stores the incoming beacons if(getFlag(POSC_ROUTING)==true) resetBeaconBuffer(); digitalWrite(13,HIGH); //switch on the LED // wait for beacon recepetion while( ((millis() - bcnReception) < BCN_TIMEOUT && getFlag(POSC_ROUTING)== true) || waitingForFirstBeacon == true ) readAPIFrame(); //read incoming frame //if the routing is enabled, chose now t he //nexthop if(getFlag(POSC_ROUTING) == true) setNextHop(); //wait for a datamessage while((count< ((delayTime)*1000))) { //read incoming data message readAPIFrame(); if((count==(((delayTime)*100*aggTout)))) sendAggregatedPacket(); //*FRAME PROCESSING*/ if(messageForwarded == true) { messageForwarded = false; count=0; } count++; } if(hopUpdated==true) { routeUpdateCnt++; workTime=((millis()-bcnReception)); sleepValue= ( (idleTime0<<8) | idleTime1) *1000; //if it is time for a route update if(routeUpdateCnt==routeUpdateInterval) { sleepValue= ((sleepValue-workTime )) /68; routeUpdateCnt=0;
115
061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090
} else sleepValue= (sleepValue- workTime )/ 34; if(sleepValue<=((((idleTime0<<8)) | idleTime1))*1000 /34) { digitalWrite(PIN_LED,LOW); //switch off modem digitalWrite(PIN_MODEM,HIGH); Serial.flush(); //disable adc converter ADCSRA &= ~bit(ADEN); PRR &= ~bit(PRADC); hopUpdated=false; timerEnabled=true; } } else //if next hop was not updated { hasNextHop=false; bcnReception=0; routeUpdateCnt=0; } } return; }
Line 4: If the timer variable is set to enabled, the device enters the sleep
mode.
Line 17: If the nodes operate in dynamic mode, the candidates list will be
reset.
Line 23: BCN_TIMEOUT is the time in milliseconds that a node will collect
incoming beacons. Until this timeout is not reached, this loop will
continue and read incoming API frames.
Line 33: If the predecessor determination has finished, the node waits for
incoming data messages.
Line 37: Each cycle of the while loop, a counter will be increased. If this
counter reaches the value of the aggregation timeout, all
temporarily stored packets will be sent in one frame.
Line 41: Each time a message is received and stored into the aggregation
buffer, the counter will be reset and the node waits again for a
new incoming data message.
116
Line 49: The variable hopUpdated controls if a beacon message was
received. If this variable is not set, the node will stay awake until it
receives a beacon.
Line 53: The uptime for this cycle is calculated.
Both time fields of the beacon message a combined by a bit shift
operation to obtain the resulting beacon transmission interval.
Line 56: It will be checked if a route update should be executed. In this
case the nodes will sleep only the half of the calculated sleep
time.
Line 66: In case a node has worked the whole sleep period, it will not enter
the sleep mode.
Line 74: If all conditions to enter the sleep mode are fulfilled, the AD
converter will be disabled and the XBee module will enter the
hibernation mode before the micro controller itself enters the
sleep state in line 4 in the next cycle of the main loop.
117
10 Setup Manual This manual will give an overview over the basic installation of the system. It
will be explained how to assemble the hardware and how to configure the
software.
Pin Arduino Board Pin XBee module Description
RX 2 Serial line 0
TX 3 Serial line 1
7 9 XBEE sleep control
10 12 XBEE flow control
Different sensor nodes can be attached to the remaining digital or analog
inputs of the ARDUINO board.
After the hardware has been setup correctly the program code has to be
loaded into the micro controller. An easy way to do this is to use the
ARDUINO programmer software which is available on the ARDUINO project
website.
The connection of the micro controller and a computer is done with a serial
connection. A comfortable way is to use an USB cable with a serial converter.
After the connection is established, the Arduino software can be started. To
poll values from different analog or digital inputs, the program code has to be
modified. To see the parts of the source code that have to be modified refer to
the code section - paragraph “data message assembly”.
The program code can be loaded in the menu (File -> Sketchbook -> Open). It
is very important that before uploading the program code, the correct
ARDUINO board is selected. In the menu (Tools -> Board) the board "Arduino
Pro or Pro mini (3.3, 8MHz), Atmega 168" has to be selected.
The correct comport has to be selected (Tools -> Serial port).
If all this is done, the code can be uploaded to the micro controller. This is
done by pressing "CTRL + U". This will start the compilation process and
upload the code into the controller’s memory.
118
11 Conclusions Wireless technology applications are being used throughout the world in a
manner that grows more complex by the hour. The uses of wireless
communication has grown far simpler and the necessary components are
becoming smaller, cheaper, easier to handle, easier to program, and easier to
maintain. In the field of sensor networks this development comes along with a
huge amount of benefits.
This project bears a light into applications that transfer information without the
hassle of installation and maintenance of sensors that require constant
monitoring.
After the realization of this project, a new, easily deployable, and open source
based sensor network system has been generated. The multi hop
functionality, in combination with the other developed network features, such
as the power management, network load distribution and reliability features,
increase the possible fields of application drastically.
Now that a set of sensor nodes can be placed anywhere regardless of the
location or the distance from the base station, automation and control of
machinery and other industrial and commercial applications that require
constant monitoring is safer, easier, cheaper and more productive. A big
advantage is that all nodes are built up homogeneously. Therefore the
network setup is quite simple, because no special routing nodes have to be
additionally integrated into the network. Of course, industry would be an
interesting field of application that came to mind during the development of
this project. But this sensor network can easily be deployed in many different
fields of applications.
Implementing this network as open source and hardware project opens the
possibilities to freely adapt the software and devices to individual
requirements. There is still a lot of space for additional features that can be
added to this system. An interesting field for further developments could be
the reduction of the power consumption to achieve very low power states,
when the nodes are in sleep mode. Or instead of using two devices with their
119
own processors, it could be an effective solution to combine both systems, the
communication device and the micro controller, to one single unit.
The combination of easily accessible components and free software platforms
are widely distributed and a certain amount of human creativity has spawned
a new generation of easily deployable measurement components and
communication facilitators. Concluding, this project has been an interesting
opportunity to obtain an insight into the implementation of micro controller
based networks and into software development at a level close to the
hardware. The first prototypes of the network are already working and can
already be used for different measurement purposes.
120
12 Appendix A) Arduino pro circuit schematic
Figure 51: Arduino pro mini circuit schematics 29
29 http://arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf
121
B) Xbee module schematic and pin declaration
Pin 1
Pin 10
Pin 11
Pin 12 Figure 52: XBee pin positions – top view 30
Table 5: XBee pin declaration 31
30 XBee product manual v1.xAx, http://ssdl.stanford.edu/ssdl/images/stories/AA236/0708A/Lab/Rover/Parts/xbeeproproductmanual.pdf Page 10 “PIN Signals”
122
C) Wiring diagram – sensor node
Figure 53: Wiring diagram
123
13 Bibliography [1] ftp://ftp.cordis.europa.eu/pub/fp7/ict/docs/sustainable growth/workshops/workshop-
20070531-jwachter_en.pdf
[2] http://www.cs.virginia.edu/papers/d2h206-health .pdf
[3] http://www.ieee802.org/15/pub/TG4.html
[4] http://www.arduino.cc/
[5] http://arduino.cc/en/Main/ArduinoBoardProMini
[6] http://www.atmel.com/dyn/resources/prod_documen ts/doc2545.pdf
[7] http://www.digi.com/products/wireless/point-mul tipoint/xbee-series1-module.jsp
[8] http://ieeexplore.ieee.org/xpl/freeabs_all.jsp? arnumber=93182
[9] Shahin Farahani. ZigBee wireless networks and t ransceivers, ZigBee and IEEE
802.15.4 Networking Layer Functions, page 18
[10] Shahin Farahani. ZigBee wireless networks and transceivers, ZigBee and IEEE
802.15.4 Networking Frequencies of Operation and Da ta Rates, page 7
[11] http://www.ieee.org
[12] Shahin Farahani. ZigBee wireless networks and transceivers, ZigBee networking
topologies, page 10
[13] Rosemount,
http://www.emersonprocess.com/Rosemount/document/no tes/00840-0200-
4180.pdf, Page 2
[14] The ZigBee Alliance, http://www.zigbee.org
[15] William C. Craig ,Zigbee: “Wireless Control Tha t Simply
Works”,http://www.zigbee.org/imwp/idms/popups/pop_do wnload.asp?contentID
=5438
[16] Shahin Farahani. ZigBee wireless networks and transceivers, CSMA-CA, page
52
[17] Shahin Farahani. ZigBee wireless networks and transceivers, Mesh Topology,
page 90
[18] http://www.digi.com/products/wireless/point-mu ltipoint/xbee-pro-series1-
module.jsp
[19] XBee product manual v1.xAx,
http://ssdl.stanford.edu/ssdl/images/stories/AA236/ 0708A/Lab/Rover/Parts/xbee
proproductmanual.pdf Page 55“API Types”, - TX (Tran smit) Request: 16-bit
address”
[20] XBee product manual v1.xAx,
http://ssdl.stanford.edu/ssdl/images/stories/AA236/ 0708A/Lab/Rover/Parts/xbee
proproductmanual.pdf Page 55“API Types - RX (Receiv e) Packet: 16-bit
Address”
124
[21] XBee product manual v1.xAx,
http://ssdl.stanford.edu/ssdl/images/stories/AA236/ 0708A/Lab/Rover/Parts/xbee
proproductmanual.pdf Page 52,“API Operation - with Escape Characters“
[22] XBee product manual v1.xAx,
http://ssdl.stanford.edu/ssdl/images/stories/AA236/ 0708A/Lab/Rover/Parts/xbee
proproductmanual.pdf Page 23, “Cyclic Sleep Modes”
[23] XBee product manual v1.xAx,
http://ssdl.stanford.edu/ssdl/images/stories/AA236/ 0708A/Lab/Rover/Parts/xbee
proproductmanual.pdf Page 53 “Pin/Host-controlled Sl eep Modes”
[24] Atmel Atmega168 manual.
http://www.atmel.com/dyn/resources/prod_documents/d oc2545.pdf, “Power
management and sleep modes"
[25] Shahin Farahani. ZigBee wireless networks and transceivers, “CSMA-CA
channel access, page 90
[26] XBee product manual v1.xAx,
http://ssdl.stanford.edu/ssdl/images/stories/AA236/ 0708A/Lab/Rover/Parts/xbee
proproductmanual.pdf Page 53 “Checksum”
[27] XBee product manual v1.xAx,
http://ssdl.stanford.edu/ssdl/images/stories/AA236/ 0708A/Lab/Rover/Parts/xbee
proproductmanual.pdf Page 11, “Flow Control “
[28] http://www.prefuse.org
[29] http://arduino.cc/en/uploads/Main/Arduino-Pro- Mini-schematic.pdf
[29] XBee product manual v1.xAx,
http://ssdl.stanford.edu/ssdl/images/stories/AA236/ 0708A/Lab/Rover/Parts/xbee
proproductmanual.pdf Page 10 “PIN Signals”
125
14 Figure Index FIGURE 1: A WIRELESS SENSOR NETWORK 4 FIGURE 2: ARDUINO PRO MINI BOARD 7 FIGURE 3: XBEE MODULE 8 FIGURE 4: PROTOTYPE, POWERED BY TWO 1.5 ALKALINE BATTERIES 9 FIGURE 5: SENSOR NODES WITH BASE STATION IN THE MIDDLE 9 FIGURE 6: 802.15.4 FRAME 11 FIGURE 7: COMMUNICATION IN A STAR TOPOLOGY NETWORK 13 FIGURE 8: COMMUNICATION IN A CLUSTER TREE TOPOLOGY NETWORK 14 FIGURE 9: ZIGBEE LAYER ON TOP OF IEE 802.15.4 LAYERS 15 FIGURE 10: PEEER TO PEER NETWORK STRUCTURE 17 FIGURE 11 : TREE NETWORK STRUCTURE 19 FIGURE 12: POSSIBLE ROUTING LOOP CONDITIONS 32 FIGURE 13: TRANSMIT-REQUEST-FRAME 22 FIGURE 14: FIGURE RECEIVE-FRAME 22 FIGURE 15: PROPAGATION OF A BEACON MESSAGE 29 FIGURE 16: DATA TRANSMISSION FROM THE NODES TO THE SINK 30 FIGURE 17: MODE OF OPERATION OF THE ROUTING ALGORITHM 31 FIGURE 18: BEACON MESSAGE STRUCTURE 64 BIT ADDRESSING 35 FIGURE 19: FIGURE DATA MESSAGE STRUCTURE 38 FIGURE 20: CYCLIC COMMUNICATION 40 FIGURE 21: ISR CYCLE IN SLEEP MODE 45 FIGURE 22: TOTAL POWER CONSUMPTION IN THE DIFFERENT MODES 48 FIGURE 23: REGULAR ROUTE ACTUALIZATION 51 FIGURE 24: ROUTE ACTUALIZATION INFLUENCED BY SLEEP MODE 52 FIGURE 25: BEACON FORWARDING PROCESS 54 FIGURE 26: EXAMPLE AT MODEM COMMANDS 57 FIGURE 27: UNBALANCED NETWORK SETUP 58 FIGURE 28: BALANCED NETWORK SETUP 59 FIGURE 29: ROUND ROBIN LOAD BALANCING 60 FIGURE 30: ALTERNATING LOAD BALANCING 61 FIGURE 31: EXAMPLE SITUATION LOAD BALANCER - BALANCED 63 FIGURE 32: EXAMPLE SITUATION LOAD BALANCER - UNBALANCED 63 FIGURE 33: LOAD BALANCER FLOW CHART 64 FIGURE 34: FIGURE EXPONENTIAL INCREASE OF THE WAITING TIME 66 FIGURE 35: HOMOGENEOUS TIME FORWARDING INTERVALS 67 FIGURE 36: DATA AGGREGATION OF DATA COMING FROM THE SAME LEVEL 68 FIGURE 37: PACKET AGGREGATION ALGORITHM 69 FIGURE 38: DUPLICATE MESSAGE DETECTION 70 FIGURE 39: FIGURE FLOW CONTROL SYSTEM AND DATA BUFFERS 77 FIGURE 40: NETWORK MAPS DRAWN BY THE VISUALIZATION TOOL 80 FIGURE 41: NETWORKS STRUCTURE - ALL NODES DIRECTLY CONNECTED 82 FIGURE 42: PACKET LOSS AGAINST XBEE RETRIES 83 FIGURE 43: PACKET LOSS AGAINST CSMA/CA BACKOFF EXPONENT 84 FIGURE 44: NETWORK STRUCTURE - ALL TO ONE 85 FIGURE 45: NETWORK STRUCTURE - CHAIN SETUP 86 FIGURE 46: NETWORK STRUCTURE LOAD BALANCER TEST 87 FIGURE 47: UNCONTROLLED- AGAINST CONTROLLED LOAD BALANCING 88 FIGURE 48: NETWORK SITUATION WITHOUT BROKEN LINKS 89 FIGURE 49: NETWORK SETUP WITH A BROKEN LINK 90 FIGURE 50: TOTAL POSSIBLE UPTIME OF A NODE 93 FIGURE 51: ARDUINO PRO MINI CIRCUIT SCHEMATICS 120 FIGURE 52: XBEE PIN POSITIONS – TOP VIEW 121 FIGURE 53: WIRING DIAGRAM 122