Fast response search and rescue robot, assisted low power wsn net for navigation and detection

43
Texas Instruments India Analog Design Challenge 2012-2013 Team 46-1 Wireless Sensor Net Assisted Remote Surveillance System Proposed Title: Fast Response Search and Rescue Robot, Assisted Low Power WSN Net for Navigation and Detection Siddhartha Kumar, Varun Reddy, Preejit Prakash National Institute of Technology Karnataka Surathkal

description

Our project is a remotely controlled robot capable of surveying disaster situations or act as a security countermeasure. It utilizes a stationary network of passive infrared sensor nodes interconnected through a multi-hop Zigbee network. The sensors are motion sensitive and using regional localization can be used for identifying the location of survivors or intruders based on the situation. The robot is used for investigating the area where the motion sensors were triggered. It also acts as relay for the sensor data. The robot is controlled via a Wi-fi link which streams real time video back to the base station. The main processor is a TI Sitara AM335x ARM processor. Each node consists of three passive infrared detection circuits each covering a sector of 120 degrees and connects via the TI CC2530 ZNP chip. The raw PIR data is signal conditioned using TI's LM324 Op-amp. The nodes can be deployed easily due to their compact size. Their low power consumption and low cost makes them ideal for remote areas and can be deployed in large numbers.

Transcript of Fast response search and rescue robot, assisted low power wsn net for navigation and detection

Page 1: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

Texas Instruments India

Analog Design Challenge

2012-2013

Team 46-1

Wireless Sensor Net Assisted Remote Surveillance System

Proposed Title:

Fast Response Search and Rescue Robot, Assisted Low Power WSN

Net for Navigation and Detection

Siddhartha Kumar, Varun Reddy, Preejit Prakash

National Institute of Technology Karnataka

Surathkal

Page 2: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

TI India Analog Design Contest 2012-2013 PAGE 1 - SELF ASSESSMENT

1. Include the following statement and place the signatures of all team members:- “We, authors of the report entitled Wireless Sensor Net Assisted Remote Surveillance

System, confirm that this report has not been submitted to any other forum such as another contest or conference for publication. We hereby state that we will not submit the same work for any other contest in the future. We understand that Texas Instruments has the right to use this report in its conferences/publications. We will seek TI’s permission before we submit the report for publication in an external forum.”

2. Comment on the originality of your idea. Did you derive inspiration from any other work?

Provide the appropriate references. We derived inspiration from previous tracking systems which use other methods to locate their bogeys. For example some systems, such as reference [2] use prior infrastructure to track movement but this method isn’t feasible in all situations and these systems are not flexible and hence we aimed to create a more robust system. In accordance to these goals we aimed at creating deployable, cheap and modular infrastructure and a network capable of multiple clients from off the shelf devices

3. List any persons who helped you in the course of the project and explain their contribution. Our mentor, Dr Aparna provided guidance without which we would not have been able to complete the project. We are indebted to Dr Muralidhar Kulakarni, HOD, Departments of Electronics and Communication Engineering, NITK for providing the labs and other resources required for completion of this project. We would also like to thank Dr. Ashwini Chaturvedi, Electrical and Electronics department for providing valuable inputs.

4. Highlight at least two technical challenges you faced and how you overcame them.

The technical challenges we faced were as follows. Video streaming was very difficult to implement in Windows and hence we used Ubuntu Linux to set up and receive the video stream on the computer side of the system. Another challenge was the low voltage provided by the AAA batteries used by the Zigbee Mini-Kit modules, as this was insufficient to cause the sensor circuit to trigger a hardware interrupt on the MSP430G2553. We overcame this problem, by using 3.3V regulated power supplies running off 9V batteries

5. Please highlight at least two non-technical challenges you faced and how you overcame them. The non-technical challenges faced by us were, we could not work for most of the holidays due to prior engagements and as our residences were far apart. We remedied this problem by finishing most of the ground work before vacations and leaving only simulation and software related work to be done. Another problem was the non-availability of components in the vicinity of our campus in Surathkal. We overcame this by buying the bulk of our components, prior to the end of our vacations, in Bangalore. Another problem that we faced was limited funds to buy Li-Po batteries for the Beaglebone platform; we worked around this problem by using a SMPS AC Adapter

6. Explain how the experience of the TI India Analog Design Contest helped you. The TI India Analog Design Contest helped us by taking us through the ins and outs of the development process, from the time we visualized the idea through to its completion. Also it gave us an experience of the hardships involved in testing and troubleshooting the problems that plague every new product. It helped prepare us for procedures and methods that will become a part of everyday life in the near future for most of us who will be employed in large corporations.

Page 3: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

7. List two things that could have added further value to your project. Two things that could have added further value are as follows. Firstly, more sensors and more Zigbee nodes would have increased the accuracy of detection and allowed us to cover a larger area through multi-hop topology. Secondly, using batteries to power the Beaglebone would have allowed us make the MoSP platform completely wireless and standalone from the base station. This would have allowed us to test the system in more diverse environments where a plug point will not be always available.

8. Please tick all aspects of your project that you believe are now complete.

Paper design of hardware

Algorithm/software design

Hardware implementation on breadboard

System-level testing with examples

Hardware implementation on PCB

Benchmarking/Performance Analysis

Hardware Testing

Short Video on Project

Link of Youtube Video: Names and signatures of student team members [Preejit Prakash] [Siddhartha Kumar] [Varun Reddy] Name and signature of the mentor [Dr Aparna P]

Page 4: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

Wireless Sensor Net Assisted Remote Surveillance System

Siddhartha Kumar, Varun Reddy, Preejit Prakash

Mentor: Dr Aparna P, Department of ECE National Institute of Technology Karnataka

PO Srinivasnagar -575025, Mangalore, Karnataka, India [email protected]

Abstract

Our project is a remotely controlled robot capable of surveying disaster situations or act as a security countermeasure. It utilizes a stationary network of passive infrared sensor nodes interconnected through a multi-hop Zigbee network. The sensors are motion sensitive and using regional localization can be used for identifying the location of survivors or intruders based on the situation. The robot is used for investigating the area where the motion sensors were triggered. It also acts as relay for the sensor data. The robot is controlled via a Wi-fi link which streams real time video back to the base station. The main processor is a TI Sitara AM335x ARM processor. Each node consists of three passive infrared detection circuits each covering a sector of 120 degrees and connects via the TI CC2530 ZNP chip. The raw PIR data is signal conditioned using an LM324 Op-amp. The nodes can be deployed easily due to their compact size. Their low power consumption and low cost makes them ideal for remote areas and can be deployed in large numbers.

1. Introduction 1.1 Motivation

Non-cooperative localization and tracking of an individual has been a long standing problem and the reason for it being so important is the vast number of applications that it can be used for. Most systems require prior infrastructure in the environment and our motivation was to be able to design a system that is deployable and adaptable to changing situations. The devastation due to the earthquake at Fukushima and the many different innovations that were implemented in the rescue effort, prompted us to think of ways

to implement search and rescue systems in disaster situations. A net of wireless sensors that are cheap and compact can be deployed immediately on a massive scale in such cases to help in detect those that are trapped. A remotely controlled vehicle can then be sent to investigate these areas. This system can also be used for intruder detection and remote surveillance with minimal changes in the basic framework. The multi-hop capability of the nodes ensures low transmission power and hence longevity. 1.2 Technical Background

Pyroelectric Infrared Sensors PIR sensors consist of two IR sensitive elements, each element having an opposite polarity. Therefore for a constant value of IR both elements provide an equal and opposite polarity hence resulting in a zero voltage output. Only when an IR emitting body is introduced into the field of view, one element will receive a higher amount of IR radiation than the other, hence causing a non-zero voltage level. If this body remains stationary then both elements reach equilibrium again. Therefore the PIRs are ideal for detecting motion of hot bodies.

Fig 1. Functional diagram of PIR sensor taken

from [3]

Page 5: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

Fig 2. Graph of analog output of PIR sensor circuit

The peaks shown in the figure are obtained by a person walking across a sensor as one can see there is a positive peak corresponding to the triggering of positive polarity element and a negative peak corresponding to the triggering of the negative polarity element. Hence by conditioning this signal we can detect motion in the field of view of a single PIR.[1],[3] Localization and Regional detection In paper [2], the authors have used each PIR sensors field of view as a region of interest and depending on the intersection regions they are able to identify the location of the person depending on the nodes that trigger. This type of region based location is used frequently in Non-Cooperative localization and tracking. As mentioned in paper [2] the approximate field of view of a PIR sensor can be modeled as a sector of a circle an angle of around 90 degrees. Using this approximation they were able to divide the area under surveillance in to sectors based on the intersection areas of each sector. 1.3 Organization of the report The paper is organized into the following sections:

1. Introduction

2. Problem Statement

3. Proposed Solution

4. Implementation 4.1. Hardware Implementation 4.2. Software Implementation

5. Results

6. Conclusions

2. Problem Statement The main aim of our project was to create an effective and robust method for non-

cooperative localization and tracking with minimal prior infrastructure. The system has many applications but our focus was on detection of survivors in disaster situations. With regard to this situation, we had to develop a rugged mobile platform running a server and an easily reconfigurable sensor system. Also, we needed to develop a front end that was easy to extract the required information and present it in a graphical manner, to make it user friendly.

3. Proposed Solution The flow of data takes place as shown in fig 3. The analog output of the PIR sensor is filtered and amplified by the signal conditioning circuit. This is compared with a preset threshold value, which triggers an interrupt in the onboard MSP430. The MSP430 send the node and triggered sensor index through the Zigbee module to the network coordinator located on the mobile platform. The data transmission can be single-hop or multi-hop through the sensor mesh via multiple nodes that also function as routers. On the robot the data from the nodes along with the real time video stream from the on board camera is relayed by the Beaglebone through Wi-fi to the Computer.

Fig 3. Block diagram of complete system

MOBILE PLATFORM

BASE STATION COMPUTER

Page 6: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

Some of the constraints that had to be considered were:

1. the nodes must be low cost and easily adaptable as they have to be deployed in large numbers and diverse situations.

2. Their power consumption must be low to increase longevity.

3. The robot must be able traverse rough terrains and have power control to allow for long operations without a need for recharge.

4. The algorithm implemented should not be prone to false triggers at the sensor end.

5. Communication link should have reduced latency and robust links to prevent loss of data and delays in transmission.

6. The range of communication between the base station and the wireless sensor network should be large to increase the extent of the network.

7. The data should be able to be acquired by any off the shelf device therefore the wireless protocol should be widely utilized like WiFi and also be capable for multiple device connections.

4. Implementation

4.1 Theory 4.1.1 Tracking Algorithm The tracking algorithm uses a region based detection system, implemented similar to the method in, Surveillance Tracking System Using Passive Infrared Motion Sensors in WSN [2]. The system in the mentioned paper uses the sector shaped regions of detection for each PIR sensor. This makes correlating the detected location difficult to correspond to grid coordinate systems. Therefore we have forced our region of detection to fit into a grid system with each grid of 0.3m x 0.3m.

Fig 4(a) Field of view of a sector

As shown in Fig 4(a), the arc shows the actual field of view as a sector region and the colored portion shows us the region forced into our 8x8 grid. Using a unique region based 8x8 matrixes for each sensor we define a weight to each cell depending on the field of view and placement of the sensor. These weight matrices can easily be derived by dividing the area into a matrix of desired size and match the intersecting field of view areas with the cells of the grid. Once the weight grids are obtained depending on the triggering of each node we add the respective weight matrices hence allowing us to identify intersection regions that will have larger weights as they add up (as shown in Fig 4(b). Therefore depending on the maximum weightage of a certain region within the grid allows us to locate the motion of the individual within the grid. To track the individual we refresh the summed weight matrix after a predetermined amount of time, and plot the derived location, from the maximum intersections, at the end of each refresh cycle. Hence interpolating these locations can give us a fair idea of the path traversed by the individual in our grid. The refresh rate is optimally set based on the latency of the communication network and MATLAB frontend processing. Also it takes into factor the delay sometimes inherent in the triggering of the PIR circuit. But the value shouldn’t cause the algorithm to give an erroneous location.

Page 7: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

Fig 4(b) Depiction of intersecting regions, colors corresponding to weights: yellow-2, blue -1 and

white -0

Localization and Tracking Algorithm: Step 1: Detect unique node(x) and PIR(y) is triggered Step 2: Add weight Matrix (Nodexpy) to current state matrix Step 3: Check for Timer Interrupt If True

Check for maximum grid weight Highlight the grid in location matrix and add to tracking matrix

Refresh current state matrix for next detection cycle Step 4: Send “ack” and wait for data from sensor network and repeat from Step 1. 4.1.2 Communication Network We have aimed for a completely wireless system to allow for easy deployment and large range. Using the Zigbee network for the Sensor Network, allows for a multi-hop hierarchical based network [4]. That has an extended range due to the evenly distributed nature of the sensors hence allowing the router devices to make a successful connection to the Coordinator device within the minimum 7 hops. A unique trait of our Wireless Networking system is the use of WiFi TCP/IP server running on a mobile platform. This server, running on the Beaglebone, hosts the Zigbee Coordinator and hence being mobile further extends the range of the entire system.

Fig 5. Network topology

The Beaglebone relays all the Zigbee data to the multiple clients that are connected to its server. The ability of the Zigbee network to interface with WiFi allows us to use commonly available devices like Laptops, Android phones, Tablet PCs, etc with no extra hardware to connect and be fed the data obtained from the sensor nodes. Also the same WiFi network allows for the Video feed from the Mobile Surveillance Platform [MoSP]

4.1 Hardware Implementation The hardware present in this project can be divided into two broad sections, the ZiPIRs and the MoSP. The ZiPIRs consist of three to a maximum of five PIR sensor modules, each with its own signal conditioning circuit, and an MSP430G2553 microcontroller. The board can be easily reconfigured to accommodate more or lesser number of PIRs based on geometry of the network, as each PIR can plugged in and out of a board without needing any reconfiguration on the software side. Each board also has a Zigbee module (TI CC2530 ZNP Mini-Kit)[4] and the whole system is powered by by 2 AAA batteries. Due to the low voltage of the AAA batteries we were faced with issues of missed GPIO interrupts on the MSP430G2553, that is why we switched to using the TI LM317KTTR to supply a regulated 3.3V from a 9V battery, hence improving the longevity and performance of signal conditioning circuit. The signal conditioning circuit is as shown below.

Page 8: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

Fig. 6 PIR Signal Conditioning Circuit

The filter circuit is a dual stage band pass filter with a maximum gain of 30dB derived from [1]. The operational amplifier used is TI’s LM324 quad op-amp [8]. The signal from the PIR is filtered and then passed through two comparators which are calibrated using presets to obtain an accurate output when movement is detected by the sensor. The outputs of the sensor are connected to two individual pins of the MSP430. The MSP430 communicates with the Zigbee module through its hardware UART pins. An LED is provided to indicate when the pin interrupt is triggered on detection of motion. One of the sensors has a resistor in series with the supply to enable measurement of power consumption by the circuit.

Fig 6. Zigbee PIR Sensor (ZiPIRs)

The MoSP consists of a prebuilt tracked chassis with an Arduino Duemilanove based controller board. It consists of two DC motors, each running a tank track. This arrangement gives the MoSP very good maneuverability and zero turning radius. The motors are driven by an L293B (ST Microelectronics) motor driver, which is in

turn controlled by the onboard Arduino. This system was chosen as it had scope for expansion and was easily available off the shelf. The Beaglebone, an ARM based single board computer with the TI Sitara AM335X microprocessor, is located above the Arduino board and is connected through a USB hub to a Wifi dongle, USB webcam and the Arduino board. The Arduino receives commands through serial via USB to control the MoSP. The Zigbee coordinator module is connected through UART to the Beaglebone. This system is modular as none of the components were modified and plug and play capability of the different components ensures that the load out can be changed easily and quickly with minimal hardware changes. The tracked chassis is powered by 4 AA batteries. For testing purposes, the Beaglebone is powered by a 5V 2A AC SMPS, but in the field can be powered by high capacity lithium ion batteries with an 5V SMPS Regulator. Cost constraints limited us from using batteries in our prototype.

Fig 7. Mobile Surveillance Platform (MoSP)

4.2 Software Implementation 4.2.1 Sensor data Network: As shown in Fig. 5, the sensor node consists of three layers. The application level layer consists of a simple hardware interrupt based trigger process. The MSP430G2553 [6] waits in low power mode for an edge triggered interrupt. The pin number tagged with the node number is sent to the Zigbee transceiver’s processor (MSP430F2274). This consists of the middleware that has a timer interrupt, UART interrupt and a State

Page 9: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

machine running. The state machine starts on power up sending a hand shake message to the Coordinator device. The UART interrupt handles a simple acknowledgement based communication between it and the MSP430G2553. It enqueues the data into their respective variables and raises a flag to ready the state machine to send a message via the CC2530 [5]. The CC2530 handles all the network layer and lower level processing. It is running the prebuilt Zigbee protocol and each device is initialized as a Router to allow a multihop network. A unique characteristic of using this layer formed of software is to allow us flexibility in interchanging the Zigbee transceivers and having each nodes unique identification tag hardcoded into the lower cost microcontroller embedded in each node. The data from the Sensor node is received by the coordinator device that is hosted on the MoSP platform. The Zigbee coordinator after setting up the network waits for a message receive signal from the CC2530 using the spipoll() method.

Fig 8 Sensor data network block diagram

After unpacking the message the MSP430F2274 communicates with the Beaglebone’s AM335x via UART [9] hence “printing” out the entire message to the processor. The processor that hosts a TCP server via its WiFi dongle, runs a simple serial port read function to obtain the message from the coordinator. This message is processed for extraction of required information like LQI and Node ID

for further use by the MoSP, and the entire message is repacked and transmitted via WiFi to all clients that are connected to the server. The PC Client runs a MATLAB program that connects to the server and upon sending an “ack” it receives the message the Node ID and Pin number is extracted and matched to the corresponding weight matrix to be used on the region based tracking algorithm. 4.2.2 MoSP Video and Control Network Alongside hosting a server for relay of the sensor network data the Beaglebone hosts a gstreamer [10] pipeline that pipes the live stream from the camera (/dev/videox) to the TCP server. This port once connected to by any client in the network can run a gstreamer TCP client to view the video. To reduce load on the network we use a jpeg encoding API to encode each frame as a jpeg and transmit it, also the frame rate of the entire stream is reduced 6 frames per second. This though reduces load on the network increases load on the CPU, hence in the encoding is then shifted onto the GPU (PowerVR SGX) on the AM335x [7] processor.

Fig 9 Video and Control network block diagram

The control server on the Beaglebone accepts a connection from any client on the pre specified port and accepts the control words in a predetermined format that is handled by the client. The control words are then serial transmitted to the Atmel device via USB or ttySerial. The Arduino running Atmel uses the inbuilt APIs of Serial communication, PWM generation and GPIO

Page 10: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

control, to accept the command words and turn on the respective motors with speed control. 5. Results

Fig 8(a) Graph depicting amplification by circuit at frequency 0.8Hz

The filter used was to have very high gain at frequencies lower than 5Hz as the signal generated by the PIR due to movement is of very low frequency.

Fig 8(b) Graph showing comparator output and output waveform of the filter

Fig 8(c) Bode plot of two stage filter at low frequencies

The above graphs show the behavior of the filter got by simulation on TINA-TI and LTSPICE. Fig 8(a) shows the input waveform (pk-pk 10mV)[11] and the amplified output signal (pk-pk 800mV) at a frequency of 0.8Hz. Fig 8(b) shows the output of the comparator stage for an input sine wave. Fig 8(c) is the frequency domain magnitude (in dB) and phase response of

the amplifier circuit, illustrating that maximum gain is got below a frequency of 1Hz. Fig 2. shows the graph obtained by the filter circuit during testing on the detection of motion. The analog reading was taken through the ADC of the MSP430 Launchpad and graphed in MATLAB. This conformed with our theouretical predictions. On the MATLAB side of the system, we were able to obtain graphs such as the ones shown in Fig 9(a) and 9(b) which help us locate the path of motion and the present location of the body through a weighted matrix method. Fig (a) uses a weighted matrix of sensor triggers based on our region detection algorithm. Fig 9(b) is the graph obtained after a full refresh cycle, which is used to obtain the present or past static location of the body.

Fig 9(a) Present weighted graph

Fig.9(b) Final location after one cycle

Page 11: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

Fig 10. Detection of one person

Fig 11. Detection of two people

We were also able to obtain a correlation between Link Quality Information (LQI) and distance from Zigbee node. Through curve fitting, as shown below, we inferred that it follows a quadratic approximation. Linear model Poly2:

( ) Coefficients (with 95% confidence bounds): p1 = 1.846 (1.16, 2.531) p2 = -28.71 (-35.1, -22.33) p3 = 117.6 (105.1, 130) Goodness of fit: SSE: 4018 R-square: 0.9022 Adjusted R-square: 0.8952 RMSE: 11.98

Fig 12 Graph of LQI vs Distance

This information can be used by the MoSP to home in on the location of any particular node it is directly connected to.

6. Conclusions From the obtained results, we are able to infer that our location algorithm worked successfully in most situations with an accuracy of 0.6m. The system was less prone to false detections by using a debounce on the sensor side as well as a regional weightage algorithm on the MATLAB side. The MoSP proved to be a versatile mobile server as well rugged surveillance platform. The vast computing power of the Beaglebone enabled us to attach a number of peripherals, with the only limit imposed being the current drawn by the entire system. The processing power of the Beaglebone can be utilized for purposes such as autonomous control or realtime image processing. The complete algorithm can also be run on it. Hence we were able to build a system which was cheap yet flexible to aid in human tracking in a variety of situations.

References [1]Emin Birey Soyer, Pyroelectric Infrared Sensor Based Event Detection,Dept.of EEE of The Institute of Engineering and Sciences of Bilkent University [2]Byunghun Song, Haksoo Choi, Hyung Su Lee, Surveillance Tracking System Using Passive Infrared Motion Sensors in Wireless Sensor Network, Korea Electronics and Technology Institute [3]Piero Zappi, Elisabetta Farella, and Luca Benini, Tracking Motion Direction and Distance With Pyroelectric IR Sensors, IEEE Sensors Journal,2010 [4]CC2530 ZDK-ZNP-Mini , processors.wiki.ti.com/index.php/CC2530ZDK-ZNP-MINI [5] Texas Instruments, CC2530 ZNP Datasheet, [6] Texas Instruments,MSP430G2x53 Datasheet [7] Texas Instruments, Sitara AM335x Datasheet [8] Texas Instruments, LM324N Quad-Opamp Datasheet [9] Beagleboard.org, Beaglebone RevA5 Reference Manual [10] Gstreamer Open Multimedia Framework, gstreamer.freedesktop.org [11] Murata, Dual Type Pyroelectric Infrared Sensors IRA-E700

Page 12: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

APPENDIX A-PCB DESIGN

The sensor board PCB design is shown below:

Signal Conditioning Circuit :

Page 13: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

APPENDIX B

Matlab (PC Client):

% load weight matrices for 8x8 grid load TIADC % Color Maps h=[ 1 1 1; 0.3 0.1 0.9; 0.6 0.9 0.1;0.9 0.3 0.1]; k=[ 1 1 1; 1 0 0]; % Make connection to Beaglebone Server tcp_con=tcpip('192.168.43.106',5001) fopen(tcp_con) %intialization current_state = zeros(8,8); MSG=0; track =zeros(8,8); loc = zeros(8,8); fail = 0;chk = 0;cnt=1; %Array to store pin trigger per refresh cycle np=zeros(5,4); %Timer Intialization time_t = timer('TimerFcn','flag=1', 'Period', 20,'ExecutionMode','fixedRate','Busymode','Drop'); max_array=zeros(7,40); start(time_t); while(1) if(fail==0) %Send ACK to allow server to send next message fwrite(tcp_con,'ack'); else if(fail ==1) %Send NACK to allow server to resend previous message fwrite(tcp_con,'nack'); end chk=1; while (get(tcp_con, 'BytesAvailable') > 0) % Store all data in Recieved Buffer in MSG MSG = fscanf(tcp_con); chk=0; end if (chk==1) fail =1; continue; end t=findstr(MSG,'LQI='); if(size(t)~=0) %Store LQI Value LQI=MSG(t+4:t+5); else %Error in link if no LQI value disp('Error in Recived Message'); fail =1; continue end end disp(MSG); %Extracting Required Information t=findstr(MSG,'Cause='); if(size(t)~=0) Cause=MSG(t+6:t+9); switch(Cause) case{'Time'}

Page 14: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

t=findstr(MSG,'Node='); if(size(t)~=0) Node=MSG(t+5); else Node='Unknown'; end disp(sprintf('Timer Interrupt from Node=%s',Node)); continue; case{'Star'} disp(sprintf('A Node Started')); continue; case{'UART'} t=findstr(MSG,'Node='); if(size(t)~=0) Node=MSG(t+5); else disp('Error UART msg with no Node'); continue; end t=findstr(MSG,'Pin='); if(size(t)~=0) Pin=MSG(t+4); else disp('Error UART msg with no Pin'); continue; end disp(sprintf('Node=%s, Pin=%s Triggered',Node,Pin)); %Depending on Node and Pin Trigger Weight Matrix is added %to current state switch(Node) case{'1'} switch(Pin) case{'1','2'} %checking for unique trigger for one refresh %cycle if(np(1,1)==0) current_state = current_state + node1p12; np(1,1)=1; end case{'5','6'} if(np(1,2)==0) current_state = current_state + node1p56; np(1,2)=1; end end case{'2'} switch(Pin) case{'1','2'} if(np(2,1)==0) current_state = current_state + node2p12; np(2,1)=1; end case{'5','6'} if(np(2,2)==0) current_state = current_state + node2p56; np(2,2)=1; end end case{'3'} switch(Pin) case{'1','2'}

Page 15: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

if(np(3,1)==0) current_state = current_state + node3p12; np(3,1)=1; end case{'5','6'} if(np(3,2)==0) current_state = current_state + node3p56; np(3,2)=1; end end case{'4'} switch(Pin) case{'1','2'} if(np(4,1)==0) current_state = current_state + node4p12; np(4,1)=1; end case{'5','6'} if(np(4,2)==0) current_state = current_state + node4p56; np(4,2)=1; end end case{'5'} switch(Pin) case{'1','2'} if(np(5,1)==0) current_state = current_state + newnode5p12; np(5,1)=1; end case{'3','4'} if(np(5,2)==0) current_state = current_state + newnode5p34; np(5,2)=1; end case{'5','6'} if(np(5,3)==0) current_state = current_state + newnode5p56; np(5,3)=1; end case{'7','8'} if(np(5,4)==0) current_state = current_state + newnode5p78; np(5,4)=1; end end end figure(1); %Plotting Current State Matrice surf(zeros(9,9),current_state); axis ij; axis([1 9 1 9 0 1]);colormap(h);colorbar; if (flag==1) %checking for timer interrupt flag max_val =max(max(current_state)); %clearing flag flag =0; if(max_val>=2) % check for Unique intersecting regions % and chose maximum intersect region [x,y] =size(max_array(4,:)); %right shifting history and clearing old tracked data

Page 16: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

for i=1:y if(max_array(4,i)~=0) track(max_array(4,i))=0; end end for i=1:3 max_array(i+1,:)=max_array(i,:); end %store max current state grid values in tracking %matrix temp_array = find(current_state==max_val); for i=1:size(temp_array) max_array(1,i)=temp_array(i); track(temp_array)=1; loc(temp_array)=1; end figure(2); %Tracking Matix is plotted surf(zeros(9,9),track); axis ij; axis([1 9 1 9 0 1]);

colormap(k); colorbar; end %clear current state and pin trigger history after every %refresh cycle current_state=zeros(8,8); np=zeros(5,4); end end end end

Page 17: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Node.c 25 January 2013 18:41

#include "msp430g2553.h"

// Hard Coding NODE ID into the G2553

#define NODE '3'

// Global variables defined

unsigned char rxBuffer ; // Received UART character

char ch_pin ,msg[5];

unsigned int sec =0;

unsigned int pin1 =0,pin2 =0,pin3 =0,pin4 =0,pin5 =0,pin6 =0,pin7 =0,pin8 =0,pin9 =0,pin0 =0;pin =0;

int t =0, start =0;

//------------------------------------------------- -----------------------------

// Function prototypes

//------------------------------------------------- -----------------------------

void UART_init (void );

void TimerA_UART_tx (unsigned char byte );

void TimerA_UART_print (char *string );

void TimerA_init ();

void msg_UART_print (char *string );

void convert (unsigned int val );

void wait (int delay )

{

int tdelay ;

tdelay = sec ;

while ((sec - tdelay )== delay );

}

void ConfigureAdc (void )

{

/* Configure ADC Channel*/

ADC10CTL1 = INCH_5 + ADC10DIV_3 ; // Channel 5, ADC10CLK/4

ADC10CTL0 = SREF_0 + ADC10SHT_3 + ADC10ON+ ADC10IE; //Vcc & Vss as reference

ADC10AE0 |= BIT5 ; //P1.5 ADC option

}

void TimerA_init ()

{

CCTL0 = CCIE; // CCR0 interrupt enabled

CCR0 = 50000 ;

TACTL = TASSEL_2 + MC_1; // SMCLK, contmode

}

void convert (unsigned int val )

{int i =0;

ch_pin =(48 + (i ));

}

//------------------------------------------------- -----------------------------

// main()

//------------------------------------------------- -----------------------------

void main (void )

{

WDTCTL= WDTPW+ WDTHOLD; // Stop watchdog timer

P1DIR |= BIT6 +BIT0 ; // P1.6 output, else input

P2DIR = 0x00 ;

// P1DIR &= ~(BIT5+BIT4);

// P1OUT &= ~(BIT5+BIT4);

-1-

Page 18: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Node.c 25 January 2013 18:41

P1OUT |= BIT6 ;

P1OUT &= ~BIT0 ;

P2OUT = 0x00 ; // P1 Cleared

// P1REN |= BIT5+BIT4;

P2REN |= 0x3F; // P2 pulldown

// P1IE |= BIT5+BIT4;

P2IE |= 0x3F; // P1.4 interrupt enabled

// P1IES |= BIT5+BIT4;

P2IES |= 0x3F; // P1.4 lo/Hi edge

P2IFG &= ~0x3F; // P1.4 IFG cleared

// P1IFG &= ~(BIT5+BIT4);

DCOCTL= 0x00 ; // Set DCOCLK to 1MHz

BCSCTL1 = CALBC1_1MHZ;

DCOCTL= CALDCO_1MHZ;

TimerA_init ();

UART_init ();

__enable_interrupt ();

for (;;)

{//__bis_SR_register(LPM0_bits + GIE); // Ente r LPM0, interrupts enabled

// TimerA_UART_print("Time:");

if (pin !=0)

{

TimerA_UART_tx ('N' );

TimerA_UART_tx (NODE);

TimerA_UART_tx ('P' );

TimerA_UART_tx (pin );

pin =0;

}

}

// _BIS_SR(LPM0_bits + GIE); // Ent er LPM4 w/interrupt

}

void UART_init (void )

{

P1SEL = BIT1 + BIT2 ; // P1.1 = RXD, P1.2=TXD

P1SEL2 = BIT1 + BIT2 ; // P1.1 = RXD, P1.2=TXD

UCA0CTL1 |= UCSSEL_2; // SMCLK

UCA0BR0 = 104; // 1MHz 9600

UCA0BR1 = 0; // 1MHz 9600

UCA0MCTL= UCBRS0; // Modulation UCBRSx = 1

UCA0CTL1 &= ~UCSWRST; // **Initialize USCI state machine**

}

// Outputs one byte using the UART

void TimerA_UART_tx (unsigned char byte )

{

rxBuffer = 0;

while(rxBuffer != byte ) // Send Byte and wait for echo

{

while (!(IFG2&UCA0TXIFG)); // USCI_A0 TX buffer ready?

UCA0TXBUF= byte ; // TX -> byte

IE2 |= UCA0RXIE; // Enable USCI_A0 RX interrupt

-2-

Page 19: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Node.c 25 January 2013 18:41

}

while(rxBuffer != 'x' ) // Send intermediate character to prevent loss of d upicate

data

{ // and wait for echo

while (!(IFG2&UCA0TXIFG)); // USCI_A0 TX buffer ready?

UCA0TXBUF= 'x' ; // TX -> byte

IE2 |= UCA0RXIE; // Enable USCI_A0 RX interrupt

}

IE2 &= ~UCA0RXIE;

P1OUT &= ~BIT0 ;

}

// Prints a string over using the Timer_A UART

void TimerA_UART_print (char *string ) // String Print

{

while (*string )

{

TimerA_UART_tx (*string ++);

}

}

//------------------------------------------------- -----------------------------

// Timer_A UART - Transmit Interrupt Handler

//------------------------------------------------- -----------------------------

#pragma vector = TIMER0_A0_VECTOR

__interrupt void Timer_A0_ISR (void )

{

sec ++;

CCR0 += 50000 ; // Add Offset to CCR0

}

#pragma vector=ADC10_VECTOR

__interrupt void ADC10_ISR(void )

{

t ++;

__bic_SR_register_on_exit (CPUOFF); // Clear CPUOFF bit from 0(SR)

}

// store RXed character

#pragma vector=USCIAB0RX_VECTOR

__interrupt void USCI0RX_ISR(void )

{

rxBuffer = UCA0RXBUF; //rxBuffer

}

// Port 1 interrupt service routine

#pragma vector=PORT1_VECTOR

__interrupt void Port_1 (void )

//On interrupt checks flag raised and stores pin va lue

{

P1OUT |= BIT6 ; // P1.6 = blink

__delay_cycles (10000 );

P1OUT &= ~BIT6 ;

if (P1IFG & BIT4 )

{

P1IFG &= ~BIT4 ; // P1.4 IFG cleared

-3-

Page 20: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Node.c 25 January 2013 18:41

if(pin7 ==0) // Check if Debounce is cleared

{ pin = '7' ;

pin7 = sec ;

}

else if((sec -pin7 ) >= 140)

{

pin7 =0; //Clear debounce

}

}

if (P1IFG & BIT5 )

{

P1IFG &= ~BIT5 ; // P1.5 IFG cleared

if(pin8 ==0) // Check if Debounce is cleared

{ pin = '8' ;

pin8 = sec ;

}

else if((sec -pin8 ) >= 140)

{

pin8 =0; //Clear debounce

}

}

if (P1IFG & BIT3 )

{

P1IFG &= ~BIT3 ; // P1.3 IFG cleared

if(pin9 ==0) // Check if Debounce is cleared

{ pin = '9' ;

pin9 = sec ;

}

else if((sec -pin9 ) >= 140)

{

pin9 =0; //Clear debounce

}

}

if (P1IFG & BIT0 )

{

P1IFG &= ~BIT0 ; // P1.0 IFG cleared

if(pin0 ==0) // Check if Debounce is cleared

{ pin = '0' ;

pin0 = sec ;

}

else if((sec -pin0 ) >= 140)

{

pin0 =0; //Clear debounce

}

}

}

#pragma vector=PORT2_VECTOR

__interrupt void Port_2 (void )

{

P1OUT |= BIT6 ; // P1.6 = blink

__delay_cycles (10000 );

P1OUT &= ~BIT6 ;

if (P2IFG & BIT0 )

{

P2IFG &= ~BIT0 ; // P2.0 IFG cleared

if(pin1 ==0) // Check if Debounce is cleared

{ pin = '1' ;

-4-

Page 21: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Node.c 25 January 2013 18:41

pin1 = sec ;

}

else if((sec -pin1 ) >= 140)

{

pin1 =0; //Clear debounce

}

}

if (P2IFG & BIT1 )

{

P2IFG &= ~BIT1 ; // P2.1 IFG cleared

if(pin2 ==0) // Check if Debounce is cleared

{ pin = '2' ;

pin2 = sec ;

}

else if((sec -pin2 ) >= 140)

{

pin2 =0;

}

}

if (P2IFG & BIT2 )

{

P2IFG &= ~BIT2 ; // P2.2 IFG cleared

if(pin3 ==0) // Check if Debounce is cleared

{ pin = '3' ;

pin3 = sec ;

}

else if((sec -pin3 ) >= 140)

{

pin3 =0; //Clear debounce

}

}

if (P2IFG & BIT3 )

{

P2IFG &= ~BIT3 ; // P2.3 IFG cleared

if(pin4 ==0)

{ pin = '4' ;

pin4 = sec ;

}

else if((sec -pin4 ) >= 140)

{

pin4 =0; //Clear debounce

}

}

if (P2IFG & BIT4 )

{

P2IFG &= ~BIT4 ; // P2.4 IFG cleared

if(pin5 ==0) // Check if Debounce is cleared

{

pin = '5' ;

pin5 = sec ;

}

else if((sec -pin5 ) >= 140)

{

pin5 =0;

}

}

if (P2IFG & BIT5 )

-5-

Page 22: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Node.c 25 January 2013 18:41

{

P2IFG &= ~BIT5 ; // P2.5 IFG cleared

if(pin6 ==0) // Check if Debounce is cleared

{ pin = '6' ;

pin6 = sec ;

}

else if((sec -pin6 ) >= 140)

{

pin6 =0; //Clear debounce

}

}

}

-6-

Page 23: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Router.c 25 January 2013 18:42

#include "../HAL/hal.h"

#include "../ZNP/znp_interface.h"

#include "../ZNP/application_configuration.h"

#include "../ZNP/af_zdo.h"

#include "znp_simple_app_utils.h"

#include "../ZNP/znp_interface_spi.h"

#include "Messages/infoMessage.h"

#include <string.h>

//an application-level sequence number to track ack nowledgements from server

unsigned int sequenceNumber = 0;

//from znp_interface shows a gives information of s uccesful connection and transmission

extern signed int znpResult ;

/** function pointer (in hal file) for the function that gets called when the timer and UART

generate an interrupt*/

extern void (*timerIsr )(void );

extern void (*debugConsoleIsr )(char );

/** This is the current state of the state machine

* Gets changed by other states, or Interrpupts */

unsigned int state = STATE_ZNP_STARTUP;

/** The main application state machine */

void stateMachine ();

/** Various flags between states */

unsigned int stateFlags = 0;

//Can define different flags to perform vaious task s

#define STATE_FLAG_SEND_INFO_MESSAGE 0x01

/** Handles timer interrupt */

void handleTimer ();

/** Handles UART inerrupts*/

void handlerUART ();

/** Variable to track the cause of the Info Message ; whether it be CAUSE_SCHEDULED or

CAUSE_MOTION etc.*/

unsigned char infoMessageCause = CAUSE_STARTUP;

/*Infomessage structure*/

struct infoMessage im ;

struct header hdr ;

#define SEND_MESSAGE_ON_UART

#define SEND_MESSAGE_ON_TIMER

char prev =0;

int time =0;

char node,pin ;

int node_flag = 0, pin_flag = 0;

// Function that checks data recieved from Node

// and stores the required data in appropriate vari ables

int enqueue (char temp)

{

if (temp =='N' )

-1-

Page 24: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Router.c 25 January 2013 18:42

{

node_flag = 1;

}

else if (node_flag == 1)

{

node = temp;

node_flag =0;

}

else if ( temp =='P' )

{

pin_flag = 1;

}

else if ( pin_flag == 1)

{

pin = temp;

pin_flag =0;

// the information message cause is UART

infoMessageCause = CAUSE_UART;

// State flag set to trigger State_Send_Info_Messag e

stateFlags |= STATE_FLAG_SEND_INFO_MESSAGE;

}

else

return 0;

return 1;

}

//UART ISR

void handlerUart (char temp)

{ //Indicate communication with node

toggleLed (0);

putchar (temp);

if (prev !=temp)

{if (temp == 'x' )

{ if (enqueue (prev )== 0)

{

return;

}

}

prev =temp;

}

}

int main ( void )

{

// Hardware Intialization

halInit ();

unsigned int vlo = calibrateVlo ();

//Isr function pointers intialized

timerIsr = &handleTimer ;

debugConsoleIsr = &handlerUart ;

//Enable Interrupts

HAL_ENABLE_INTERRUPTS();

//create the infoMessage. Most of these fields are the same, so we can create most of

-2-

Page 25: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Router.c 25 January 2013 18:42

the message ahead of time.

//this will be incremented each message

hdr .sequence = 0;

hdr .version = INFO_MESSAGE_VERSION;

hdr .flags = INFO_MESSAGE_FLAGS_NONE;

im.header = &hdr ;

im.deviceType = DEVICETYPE_SMITH_ELECTRONCS_ROUTER_DEMO;

im.deviceSubType = DEVICESUBTYPE_SMITH_ELECTRONCS_ROUTER_DEMO;

im.numParameters = 3;

//run the state machine

stateMachine ();

}

void stateMachine ()

{

while (1)

{

switch (state )

{

case STATE_IDLE:

{

//if there is a pending info message to be sent

if (stateFlags & STATE_FLAG_SEND_INFO_MESSAGE)

{

state = STATE_SEND_INFO_MESSAGE;

//then send the message and clear the flag

stateFlags &= ~STATE_FLAG_SEND_INFO_MESSAGE;

}

break;

}

case STATE_ZNP_STARTUP:

{

#define ZNP_START_DELAY_IF_FAIL_MS 5000

signed int startResult ;

while ((startResult = startZnp (ROUTER)) != ZNP_SUCCESS)

{

// Retry Till Succesfully joining the network

printf ("FAILED. Error Code %i, ZNP Result %i. Retrying...\ r\n" ,

startResult , znpResult );

delayMs (ZNP_START_DELAY_IF_FAIL_MS);

}

// printf("Success\r\n");

//ZNP Initialized so store MAC Address

memcpy(hdr .mac, getMacAddress (), 8);

//Now safe to enable message timer:

signed int timerResult = initTimer (4, NO_WAKEUP);

if (timerResult != 0)

{

printf ("timerResult Error %i, STOPPING\r\n" , timerResult );

while (1);

}

-3-

Page 26: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Router.c 25 January 2013 18:42

state = STATE_DISPLAY_NETWORK_INFORMATION;

break;

}

case STATE_DISPLAY_NETWORK_INFORMATION:

{

//Display Network parameters used for debugging pur poses

// getNetworkConfigurationParameters();

// getDeviceInformation();

//Sends Successful Start up message

state = STATE_SEND_INFO_MESSAGE;

break;

}

case STATE_SEND_INFO_MESSAGE:

{

//Sends Info message

setLed (1); // Indicate Messages being sent

im.header ->sequence = sequenceNumber ++;

im.cause = infoMessageCause ;

unsigned char * sa = getDeviceInformationProperty (DIP_PANID);

im.parameters [0] = CONVERT_TO_INT(*sa, *(sa+1));

if (im.cause != CAUSE_SCHEDULE)

{

im.parameters [1] = node;

im.parameters [2] = pin ;

}

int i = 0;

#define ZNP_RESTART_DELAY_IF_MESSAGE_FAIL_MS 5000

unsigned char msgBuf [100];

serializeInfoMessage (&im, msgBuf );

do

{

// Retry upto 10 times till a successful transmissi on is made

afSendData (DEFAULT_ENDPOINT,DEFAULT_ENDPOINT,ALL_DEVICES,

INFO_MESSAGE_CLUSTER, msgBuf , getSizeOfInfoMessage (&im));

delayMs (1000); //allow enough time for coordinator to fully restar t, if

that caused our problem

i ++;

}

while((znpResult != ZNP_SUCCESS) && i <10); //check for successful transmission

if (znpResult != ZNP_SUCCESS)

{

//printf("afSendData error %i; restarting...\r\n", znpResult); for

Debugging

delayMs (ZNP_RESTART_DELAY_IF_MESSAGE_FAIL_MS);

state = STATE_ZNP_STARTUP;

}

else

{

state = STATE_IDLE;

clearLeds ();

HAL_SLEEP();

}

break;

}

default: //should never happen

{

// printf("UNKNOWN STATE\r\n");

-4-

Page 27: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Router.c 25 January 2013 18:42

state = STATE_ZNP_STARTUP;

}

break;

}

}

}

/** Handles timer interrupt */

void handleTimer ()

{

printf ("$" );

// Keeps a constant count of the number of seconds

time ++;

if(time %5 ==0)

{ //Sends data every 5 seconds

infoMessageCause = CAUSE_SCHEDULED;

stateFlags |= STATE_FLAG_SEND_INFO_MESSAGE;

}

}

-5-

Page 28: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Coordinator.c 25 January 2013 18:42

#include "../HAL/hal.h"

#include "../ZNP/znp_interface.h"

#include "../ZNP/application_configuration.h"

#include "../ZNP/af_zdo.h"

#include "../ZNP/znp_interface_spi.h"

#include "Messages/infoMessage.h"

#include "znp_simple_app_utils.h"

#include "znp_example_utils.h"

#define Restart_delay 5000

//Function Prototype

void displayMessages();

//ZnpBuffer array to store recieved data from CC2530 intialized

extern unsigned char znpBuf[100];

int main( void )

{

// hardware intialization

halInit();

// Enable Interrupts

HAL_ENABLE_INTERRUPTS();

//Start Module in Coordinator Mode

startZnp(COORDINATOR);

// Check for Successful Network Setup

while(startZnp!=0)

{

delayMs(Restart_delay);

//Restart Module in Coordinator Mode

startZnp(COORDINATOR);

}

//Show Led(0) after Succesful Network setup

setLed(0);

while (1)

{

//wait until SRDY goes low indicating a message has been received.

while (SRDY_IS_HIGH());

//Display recieved meesage

displayMessages();

}

}

//Checks if Message is in INFO message Format

#define IS_INFO_MESSAGE_CLUSTER() {

(CONVERT_TO_INT(znpBuf[AF_INCOMING_MESSAGE_CLUSTER_LSB_FIELD],znpBuf[

AF_INCOMING_MESSAGE_CLUSTER_MSB_FIELD]) == INFO_MESSAGE_CLUSTER)

}

void displayMessages()

{ //Polls the ZNP for data. This is used to receive data from the ZNP

spiPoll();

if (znpBuf[SRSP_LENGTH_FIELD] > 0)

{

if (IS_AF_INCOMING_MESSAGE())

{

//LED will blink to indicate a message was received successfully

setLed(1);

-1-

Page 29: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\Coordinator.c 25 January 2013 18:42

if (IS_INFO_MESSAGE_CLUSTER())

{

//Unpack znpBuf into human readable format

struct infoMessage im = deserializeInfoMessage(znpBuf+20);

if (im.numParameters > 0)

{

//Check cause of message trigger at sensor end

// Timer interrupt is Schedule Message

switch (im.cause)

{

case CAUSE_SCHEDULED: printf("Cause=Timer");printf(",Node=%u", im.

parameters[1]-48);

//LQI Value sent for relative positioning of

MoSP from nodes

printf("LQI=%d,", znpBuf[SRSP_HEADER_SIZE+9]);

break;

case CAUSE_UART: printf("Cause=UART");

if (im.numParameters == 3) //panId, Node, Pin

{

printf(",Node=%u,Pin=%u", im.parameters[1]-48, im.parameters[2]-

48);

}; break;

case CAUSE_STARTUP: printf("Cause=Startup"); break;

}

printf("\r\n");

}

}

clearLed(1);

}

znpBuf[SRSP_LENGTH_FIELD] = 0;

}

}

}

/*Improvements to be made , Using Lowpower mode on Coordinator along with Edge triggered

interrupts for SRDY*/

-2-

Page 30: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\bb_server.c 25 January 2013 18:48

Beaglebone Server :

Serial Communication APIS

TCP Server Setup

For both Zigbee Relay and MoSP control

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <stdio.h>

#include <signal.h>

#include <sys/time.h>

#include <stdlib.h>

#include <unistd.h>

#include <errno.h>

#include <string.h>

//Incude the Serial port Communication APIs

#include "msp_serial.cpp"

char sig [1024];

int stop_sig = 0;

int main ()

{

int sock , connected , bytes_recieved , true1 = 1,cls = 0;

char recv_data [1024], send_data [1024] , cmd[1024];

struct sockaddr_in server_addr ,client_addr ;

unsigned int sin_size ;

//Intialize sock

if ((sock = socket (AF_INET, SOCK_STREAM, 0)) == -1) {

perror ("\nSocket\n" );

exit (1);

}

if (setsockopt (sock ,SOL_SOCKET,SO_REUSEADDR,&true1 ,sizeof(int )) == -1) {

perror ("\nSetsockopt\n" );

exit (1);

}

server_addr .sin_family = AF_INET;

// Start Server on port 5000

server_addr .sin_port = htons (5000);

// Port 5001 for zigbee server

//server_addr.sin_port = htons(5001);

server_addr .sin_addr .s_addr = INADDR_ANY;

bzero (&(server_addr .sin_zero ),8);

// Bind to Port

if (bind (sock , (struct sockaddr *)&server_addr , sizeof(struct sockaddr ))== -1)

{

perror ("\nUnable to bind\n" );

exit (1);

}

//Listen for connection

if (listen (sock , 5) == -1) {

perror ("\nListen\n" );

-1-

Page 31: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\bb_server.c 25 January 2013 18:48

exit (1);

}

printf ("\nTCPServer Waiting for client on port 5000" );

//printf("\nTCPServer Waiting for client on port 50 01");

fflush (stdout );

while(1)

{

sin_size = sizeof(struct sockaddr_in );

// Accept Connection &client_addr

connected = accept (sock , (struct sockaddr *)&client_addr ,&sin_size );

printf ("\n I got a connection from (%s , %d)" ,

inet_ntoa (client_addr .sin_addr ),ntohs (client_addr .sin_port ));

while (1)

{

bytes_recieved =recv (connected ,recv_data ,1024,0);

recv_data [bytes_recieved ] = '\0' ;

//printf("\n %s \n",recv_data);

if (strcmp (recv_data , "nack" ) == 0)

{

printf ("\n Failed Acknowledgment recieved" );

if(send (connected ,send_data ,strlen (send_data ), 0) == -1)

{

printf ("\nError in sending!!\n" );

break;

}

else

{

printf ("\nSent\n" );

continue;

}

}

else if(strcmp (recv_data , "ack" ) == 0)

{

printf ("\nAcknowledgement Recieved " );

}

if (strcmp (recv_data , "quit" ) == 0)

{

close (connected );

cls =1;

break;

}

else

{

//printf("\n RECIEVED DATA = %s " , recv_data);

/* For MoSP Server*/

switch(recv_data [0])

{

case 'x' :printf ("\nExecuting MSP\n" );

if(strcmp (recv_data ,msp_serial (2,recv_data )))

{

printf ("\nError: in Execution of msp_serial\n" );

-2-

Page 32: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\bb_server.c 25 January 2013 18:48

return(1);

};

break;

default:printf ("\nInvalid input" );break;

}

//For Sensor Network Server

/*

c=msp_serial(1,"read");

strcpy(send_data,c);

while(send(connected,send_data,strlen(send_data), 0 ) == -1)

{

printf("\nError in sending!!\n");

send(connected,send_data,strlen(send_data), 0) == - 1

}

*/

}

fflush (stdout );

if (cls =1)

{

break;

}

}

}

printf ("\nConnection Closed!!\n" );

close (sock );

return 0;

}

-3-

Page 33: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\msp_serial.cpp 25 January 2013 18:48

#include<iostream>

#include <cstdio>

#include "SerialPort.h"

#define NR_BYTES 1000

#define PI 3.14159265

#include "SerialPort.cpp"

using namespace std ;

SerialPort serialPort ;

//void little_to_big_endianess(unsigned char *,unsi gned int);

void format (char * );

char * msp_serial (int argc , char * argv )

{

long i ,nbytes ;

int n,in ;

char red [5]={'r' },green [5]={'g' },ack [5],c;

char * signal ;

FILE *fp ;

// Writing to MoSP platform to control Movement

if(argc ==2)

{

if (serialPort .open() != true)

{printf ("\nerror\n" );}

else

{printf ("\nopened\n" );}

serialPort .configure (SerialPort ::NoParity );

format (argv );

serialPort .write (argv ,1);

}

// Reading Data from the Zigbee transciever

else if (argc ==1)

{

while (serialPort .readTill (argv ,1000) == 1)

{int i =0;

serialPort .flush ();

return (serialPort .data );

}

}

serialPort .flush ();

return argv ;

}

void format (char * temp)

{

for (int i =1;i <=strlen (temp);i ++)

{

temp[i -1]=temp[i ];

}

}

-1-

Page 34: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\SerialPort.cpp 25 January 2013 18:46

#include "SerialPort.h"

#include<iostream>

#include <stdio.h>

#include <fcntl.h> /* File control definitions */

#include <errno.h> /* Error number definitions */

#include <termios.h> /* POSIX terminal control definitions */

#include <string.h>

Serial Port Constructor

SerialPort ::SerialPort ()

{

strcpy (deviceName ,serialDeviceNames [TTYUSB0]);

//strcpy(deviceName,serialDeviceNames[TTYO1]);

state =Closed ;

}

bool SerialPort ::open()

{

// open tty Device for Serial Communication

//for Zigbee

fd = ::open(serialDeviceName [TTYO1], O_RDWR| O_NOCTTY| O_NDELAY);

//for Robot Platform

//fd = ::open(serialDeviceName[TTYUSB0], O_RDWR | O _NOCTTY | O_NDELAY);

if (!fd )

{

perror ("Opening Serial Port: Unable to open Device" );

return false;

}

fcntl (fd , F_SETFL, 0);

state =Open;

printf ("open %d\n" ,state );

return true;

}

void SerialPort ::configure (int argParity )

{

termios settings ;

//Get the current settings for the port...

tcgetattr (fd , &settings );

//Set local mode

settings .c_cflag |= CLOCAL;

//Set the port to read incoming data

settings .c_cflag |= CREAD;

//Set raw input

settings .c_lflag &= ~ICANON;

//Disable SIGINTR, SIGSUSUP, SIGDSUSP, and SIGQUIT signals

settings .c_lflag &= ~ISIG ;

//Disable echoing of input

settings .c_lflag &= ~ECHO;

//Disable echoing of erase characters

settings .c_lflag &= ~ECHOE;

//Disable outgoing software flow control

settings .c_iflag &= ~IXON;

//Disable incoming software flow control

settings .c_iflag &= ~IXOFF;

//Disable flow start control by any character

-1-

Page 35: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\SerialPort.cpp 25 January 2013 18:46

settings .c_iflag &= ~IXANY;

//Don't map NL to CR

settings .c_iflag &= ~INLCR;

//Don't map CR to NL

settings .c_iflag &= ~ICRNL;

//Don't map uppercase to lower case

settings .c_iflag &= ~IUCLC;

//Set raw output (no processing of output)

settings .c_oflag &= ~OPOST;

//Set the baud rates to 9600

cfsetispeed (&settings , B9600);

cfsetospeed (&settings , B9600);

if(argParity ==NoParity )

{

//No Parity

settings .c_cflag &= ~PARENB;

settings .c_cflag &= ~CSTOPB;

settings .c_cflag &= ~CSIZE;

settings .c_cflag |= CS8;

}

else if(argParity ==EvenParity )

{

//Even Parity

settings .c_cflag |= PARENB;

settings .c_cflag &= ~PARODD;

settings .c_cflag &= ~CSTOPB;

settings .c_cflag &= ~CSIZE;

settings .c_cflag |= CS7;

//Input parity check and strip

settings .c_iflag |= (INPCK | ISTRIP );

}

else if(argParity ==OddParity )

{

//Odd Parity

settings .c_cflag |= PARENB;

settings .c_cflag |= PARODD;

settings .c_cflag &= ~CSTOPB;

settings .c_cflag &= ~CSIZE;

settings .c_cflag |= CS7;

//Input parity check and strip

settings .c_iflag |= (INPCK | ISTRIP );

}

//Apply settings for the port

tcsetattr (fd , TCSANOW, &settings );

}

int SerialPort ::getState ()

{

return state ;

}

// Can be used for Multiple UART devices

char SerialPort ::serialDeviceNames [][20] =

{

"/dev/ttyO0" ,

-2-

Page 36: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\SerialPort.cpp 25 January 2013 18:46

"/dev/ttyO1" ,

"/dev/ttyO2" ,

"/dev/ttyO3" ,

"/dev/ttyUSB0" ,

"/dev/ttyUSB1" ,

"/dev/ttyUSB2" ,

"/dev/ttyUSB3" ,

"/dev/ttyACM0" ,

"/dev/ttyACM1"

};

// Can be used for varying Baudrate connections

char SerialPort ::baudRates [][20] =

{

"B9600" ,

"B19200" ,

"B38400" ,

"B57600" ,

"B76800" ,

"B115200"

};

void SerialPort ::close ()

{

state =Closed ;

::close (fd );

}

bool SerialPort :: flush ()

{

if(tcflush (fd ,TCIOFLUSH)==-1)

{

printf ("Flush operation failed\n" );

return false;

}

return true;

}

int SerialPort ::read (char * str ,int len )

{int inl ;

inl =::read (fd ,str ,len ) ;

return inl ;

}

// Returns Bytes

int SerialPort ::readTill (char *str ,int len )

{

int bytesRead =0;

while(len )

{

if(::read (fd ,str ,1)==-1)

return 0;

data [byteRead ]=*str ;

if(*str =='\n' )

{

-3-

Page 37: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\SerialPort.cpp 25 January 2013 18:46

bytesRead ++;

data [bytesRead ]='\0' ;

return 1;

}

str ++;

len --;

bytesRead ++;

}

return bytesRead ;

}

int SerialPort ::write (char *str ,int len )

{ int inl ;

inl =::write (fd ,str ,len );

return inl ;

}

SerialPort ::~SerialPort ()

{

if(state !=Closed )

close ();

}

-4-

Page 38: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\SerialPort.h 25 January 2013 18:46

#ifndef SERIALPORT_H

#define SERIALPORT_H

#include <string>

class SerialPort{

public:

SerialPort();

bool open();

void configure(int);

void close();

int getState();

bool flush();

int read( char*,int);

int bytesToBeRead();

int readTill(char *str,int len,char ch);

int write(char*,int);

bool writeCompulsory(const char*,int);

bool readCompulsory(char*,int);

~SerialPort();

enum SerialDevice{TTYO0,TTYO1,TTYO2,TTYO3,TTYUSB0,TTYUSB1,TTYUSB2,TTYUSB3,TTYACM0};

enum parity{NoParity,EvenParity,OddParity,SpaceParity};

enum deviceState{Open,Closed};

static char serialDeviceNames[][20];

static char baudRates[][20];

char data[1024];

private:

int fd;

char deviceName[20];

int state;

};

#endif

-1-

Page 39: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\tcpclient.c 25 January 2013 18:50

Client Side Program :

Control of MoSP using Keyboard

#include <sys/socket.h>

#include <sys/types.h>

#include <netinet/in.h>

#include <netdb.h>

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <unistd.h>

#include <errno.h>

#include <termios.h>

#include <unistd.h>

#define END_FILE_CHARACTER 0x04 /* ctrl-d is unix-style eof input key*/

// Watches the Keyboard for a new keypress on the a ctive window

// Can be used on any gtk or qml based GUI to contr ol the MoSP via the keyboard

int linux_getch (void )

{

struct termios oldstuff ;

struct termios newstuff ;

int inch ;

tcgetattr (STDIN_FILENO, &oldstuff ); //reads the standard I/O files of linux

newstuff = oldstuff ; /* save old attributes */

newstuff .c_lflag &= ~(ICANON | ECHO); /* reset "canonical" and "echo" flags*/

tcsetattr (STDIN_FILENO, TCSANOW, &newstuff ); /* set new attributes */

inch = getchar ();

tcsetattr (STDIN_FILENO, TCSANOW, &oldstuff ); /* restore old attributes */

if (inch == END_FILE_CHARACTER) {

inch = EOF;

}

return inch ;

}

int main (int argc , char ** argv ) // Accepts arguments Via bash script

// function call "$ client 192.168.43.106 " where 1 92.168.43.106 is the IP address

{

int sock , bytes_recieved ,chk =0;

char send_data [1024],recv_data [1024],c;

struct hostent *host ;

struct sockaddr_in server_addr ;

// Resolves the IP address fed to the program

host = gethostbyname (argv [1]);

if ((sock = socket (AF_INET, SOCK_STREAM, 0)) == -1) {

perror ("Socket" );

exit (1);

}

-1-

Page 40: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\tcpclient.c 25 January 2013 18:50

server_addr .sin_family = AF_INET;

server_addr .sin_port = htons (5000);

server_addr .sin_addr = *((struct in_addr *)host ->h_addr );

bzero (&(server_addr .sin_zero ),8);

// Connects to server if ready

if (connect (sock , (struct sockaddr *)&server_addr ,sizeof(struct sockaddr )) == -1)

{

perror ("\nConnect\n" );

exit (1);

}

while(1)

{

printf ("\nSending ACK\n" );

strcpy (send_data ,"ack" );

send (connected , send_data ,strlen (send_data ), 0);

printf ("\nSent ACK\n" );

bytes_recieved =recv (sock ,recv_data ,1024,0);

recv_data [bytes_recieved ] = '\0' ;

printf ("\n RECIEVED DATA = %s \n " , recv_data );

while(1) //Required for robot control

{

c=linux_getch (); // waits for key presses

switch(c)

{ case 'w' :strcpy (send_data ,"xw" );chk =1;break;

case 's' :strcpy (send_data ,"xs" );chk =1;break;

case 'a' :strcpy (send_data ,"xa" );chk =1;break;

case 'd' :strcpy (send_data ,"xd" );chk =1;break;

case 'e' :strcpy (send_data ,"xe" );chk =1;break;

case 'q' :strcpy (send_data ,"quit" );chk =1;break;

case 'j' :strcpy (send_data ,"xj" );chk =1;break;

case 'l' :strcpy (send_data ,"xl" );chk =1;break;

case 'k' :strcpy (send_data ,"xk" );chk =1;break;

case 'i' :strcpy (send_data ,"xi" );chk =1;break;

case 'm' :strcpy (send_data ,"xm" );chk =1;break;

case 'x' :strcpy (send_data ,"xx" );chk =1;break;

default :printf ("\nInvalid input\n" );strcpy (send_data ,"error" );break;

}

if(chk =1)

{ chk =0;

break;

}

}

// printf("Client side : %s\n",send_data); Debug in formation

if(send (sock ,send_data ,strlen (send_data ), 0) == -1)

// Send data to server

{

printf ("\nError in sending!!\n" );

}

else

//Debug information

//printf("Sent");

}

printf ("\n Connection closed\n" );

-2-

Page 41: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\tcpclient.c 25 January 2013 18:50

return 0;

}

-3-

Page 42: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

I:\cam.sh 25 January 2013 18:45

Camera Stream Startup Client Side

#!/bin/bash

# Bash Script call "$ cam 192.168.43.106 5005"

# IP of server = 192.168.43.106

# Port is 5005

# Use TCP protocol to improve reliablity of reconnection but have dropped frames

# can use UDP protocol for higher frame rate but lower reliability

gst-launch tcpclientsrc host=$1 port=$2 ! jpegdec ! autovideosink

Camera startup Server Side

#!/bin/bash

# Bash Script Call "$cam_start 0 5005"

# Video device 0

# Port Number 5005

# Gstreamer TCP server setup on the Beaglebone

# We use a 6 Frames per Sec Frame rate , VGA Resolution, and jpeg Encoding

gst-launch v4l2src device=/dev/video$1 ! videorate ! video/x-raw-yuv,width=320,height=240,

framerate=6/1 ! jpegenc quality=30 ! tcpserversink port=$2

-1-

Page 43: Fast response search and rescue robot, assisted low power wsn net for navigation and detection

APPENDIX C – Bill of Materials

Component Manufacturer Cost per component

Quantity Total cost of component

TI Supplied/ Purchased

1 LM324 Quad Opamp TI $0.45 15 $6.75 TI supplied

2 MSP430G2553 TI $2.25 5 $11.25 TI supplied

3 CC2530 Mini ZNP kit TI $99 2 $198 TI supplied

4 LM317KTTR TI $0.84 5 $4.20 TI supplied

5 DFRobotShop Rover Tracked Robot Kit

DF Robots $60 1 $60 Purchased

6 Beaglebone Circuitco $80 1 $80 Purchased

7 USB web cam Intex $6 1 $6 Purchased

8 Wi-fi dongle Asus $18 1 $18 Purchased

9 USB hub Croma $6 1 $6 Purchased

10 PIR Sensors Murata $1.2 15 $18 Purchased

11 PCB Fabrication Chipkraft $1.66 15 $25 Purchased

12 Miscellaneous discrete components

$20 Purchased

Total cost of the project $453.20