Showing posts with label wireless sensor. Show all posts
Showing posts with label wireless sensor. Show all posts

Wednesday, January 20, 2016

Building a Wireless Sensor Network with the nRF24L01 Part 4

In part 4 of Building a Wireless Sensor Network with the nRF24L01 we take a look at the design's PCB layout in Eagle software as well as cover some software and hardware updates to the design.


You can access the updated code and PCB files from GitHub: https://github.com/ForceTronics/nRF24L01_Wireless_Sensor_Dev_Board


Wednesday, January 6, 2016

Building a Wireless Sensor Network with the nRF24L01 Part 3

In part three we take a look at the updated hardware schematic of the router / end device design, how the router / end device settings work, and we go over the initial software of the router / end device. You can find the code from this video in GitHub at https://github.com/ForceTronics/nRF24L01_Wireless_Sensor_Dev_Board


Monday, December 7, 2015

Building a Wireless Sensor Network with the nRF24L01 Part 1

This is part 1 in a series where we look at how to build a large wireless network using Arduino and the nRF24L01+ Transceiver Modules. At the end of this series you will have a reference design for a wireless sensor development board and the code needed to turn the wireless sensor developments boards into a network. You will be able purchase all the hardware for this project at my site: www.forcetronics.com


Initial Hardware Design

Wednesday, May 20, 2015

Reducing the Power Consumption of the nRF24L01 Transceiver

In this video we take a look at the power needs or power profile of the nRF24L01+ Transceiver. We discuss how much power it draws in each mode and how to reduce or optimize its power consumption for battery powered projects or designs. Finally we pair the nRF24L01 with an Arduino utilizing sleep mode and look at their combined power profile.



************Arduino and nRF24L01 Low Power Example Sketch*************
#include <SPI.h> //Call SPI library so you can communicate with the nRF24L01+
#include <nRF24L01.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/
#include <RF24.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/
#include <avr/sleep.h>
#include <avr/wdt.h> 

/*WDT BYTE variables for setting timer value
     WDTO_15MS, WDTO_30MS, WDTO_60MS, WDTO_120MS, WDTO_250MS, WDTO_500MS, WDTO_1S, WDTO_2S, WDTO_4S, WDTO_8S */

const int pinCE = 9; //This pin is used to set the nRF24 to standby (0) or active mode (1)
const int pinCSN = 10; //This pin is used to tell the nRF24 whether the SPI communication is a command or message to send out
RF24 wirelessSPI(pinCE, pinCSN); // Create your nRF24 object or wireless SPI connection
const uint64_t wAddress = 0xB00B1E50D2LL;              // Pipe to write or transmit on
const uint64_t rAddress = 0xB00B1E50B1LL;  //pipe to recive data on

void setup() {
  randomSeed(analogRead(0)); //create unique seed value for random number generation
  wirelessSPI.begin();            //Start the nRF24 module
  wirelessSPI.setRetries(15,10);
  wirelessSPI.openWritingPipe(wAddress);        //open writing or transmit pipe
  wirelessSPI.openReadingPipe(1,rAddress);  //open reading or recieve pipe
  wirelessSPI.stopListening(); //go into transmit mode
}

void loop() {
   byte randNumber = (byte)random(11); //generate random guess between 0 and 10 
    if (!wirelessSPI.write(&randNumber, 1)){  //if the write fails
      // delivery failed      
     }
     
   delay(30); //delay for short time in normal mode
   wirelessSPI.powerDown(); //put nRF24L01 into power down mode
   delayWDT(WDTO_30MS);   // Use WDT sleep delay function, argument is byte variable from WDT Library
   wirelessSPI.powerUp(); //power up the nRF24
}

//This function serves as a power saving delay function. The argument is a Byte type variable that is used to set the delay time
//The function sets up sleep mode in power down state. The function then sets up the WDT timer in interrupt mode and sets it.
//It then puts the Arduino to sleep for the set time. Upon wake up the WDT and sleep mode are shut off
void delayWDT(byte timer) {
  sleep_enable(); //enable the sleep capability
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); //set the type of sleep mode. Default is Idle
  ADCSRA &= ~(1<<ADEN); //Turn off ADC before going to sleep (set ADEN bit to 0)
  WDTCSR |= 0b00011000;    //Set the WDE bit and then clear it when set the prescaler, WDCE bit must be set if changing WDE bit   
  WDTCSR =  0b01000000 | timer; //Or timer prescaler byte value with interrupt selectrion bit set
  wdt_reset(); //Reset the WDT 
  sleep_cpu(); //enter sleep mode. Next code that will be executed is the ISR when interrupt wakes Arduino from sleep
  sleep_disable(); //disable sleep mode
  ADCSRA |= (1<<ADEN); //Turn the ADC back on
}

//This is the interrupt service routine for the WDT. It is called when the WDT times out. 
//This ISR must be in your Arduino sketch or else the WDT will not work correctly
ISR (WDT_vect) 
{
  wdt_disable();
   MCUSR = 0; //Clear WDT flag since it is disabled, this is optional

}  // end of WDT_vect

Saturday, May 9, 2015

Creating a nRF24L01 Transceiver Network

In this video we will look at how to create an nRF24L01 Transceiver module network (more than two). This is useful if you want to build a wireless sensor network or some type of wireless automation system that has multiple wireless nodes.



***************************Arduino Code for Receiver*******************************
//This sketch is from a tutorial video for networking more than two nRF24L01 tranciever modules on the ForceTronics YouTube Channel
//the code was leverage from the following code http://maniacbug.github.io/RF24/starping_8pde-example.html
//This sketch is free to the public to use and modify at your own risk

#include <SPI.h> //Call SPI library so you can communicate with the nRF24L01+
#include <nRF24L01.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/
#include <RF24.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/

const int pinCE = 9; //This pin is used to set the nRF24 to standby (0) or active mode (1)
const int pinCSN = 10; //This pin is used to tell the nRF24 whether the SPI communication is a command or message to send out
byte daNumber = 0; //The number that the transmitters are trying to guess
RF24 wirelessSPI(pinCE, pinCSN); // Declare object from nRF24 library (Create your wireless SPI) 
const uint64_t rAddress[] = {0xB00B1E50D2LL, 0xB00B1E50C3LL};  //Create pipe addresses for the 2 nodes to recieve data, the "LL" is for LongLong type
const uint64_t wAddress[] = {0xB00B1E50B1LL, 0xB00B1E50A4LL};  //Create pipe addresses for the 2 nodes to transmit data, the "LL" is for LongLong type

void setup()   
{
  randomSeed(analogRead(0)); //create unique seed value for random number generation
  daNumber = (byte)random(11); //Create random number that transmitters have to guess
  Serial.begin(57600);  //start serial to communication
  Serial.print("The number they are trying to guess is: "); 
  Serial.println(daNumber); //print the number that they have to guess
  Serial.println();
  wirelessSPI.begin();  //Start the nRF24 module
  wirelessSPI.openReadingPipe(1,rAddress[0]);      //open pipe o for recieving meassages with pipe address
  wirelessSPI.openReadingPipe(2,rAddress[1]);      //open pipe o for recieving meassages with pipe address
  wirelessSPI.startListening();                 // Start listening for messages
}

void loop()  
{   
    byte pipeNum = 0; //variable to hold which reading pipe sent data
    byte gotByte = 0; //used to store payload from transmit module
    
    while(wirelessSPI.available(&pipeNum)){ //Check if recieved data
     wirelessSPI.read( &gotByte, 1 ); //read one byte of data and store it in gotByte variable
     Serial.print("Recieved guess from transmitter: "); 
     Serial.println(pipeNum); //print which pipe or transmitter this is from
     Serial.print("They guess number: ");
     Serial.println(gotByte); //print payload or the number the transmitter guessed
     if(gotByte != daNumber) { //if true they guessed wrong
      Serial.println("Fail!! Try again."); 
     }
     else { //if this is true they guessed right
      if(sendCorrectNumber(pipeNum)) Serial.println("Correct! You're done."); //if true we successfully responded
      else Serial.println("Write failed"); //if true we failed responding
     }
     Serial.println();
    }

  delay(200);    
}

//This function turns the reciever into a transmitter briefly to tell one of the nRF24s
//in the network that it guessed the right number. Returns true if write to module was
//successful
bool sendCorrectNumber(byte xMitter) {
    bool worked; //variable to track if write was successful
    wirelessSPI.stopListening(); //Stop listening, stop recieving data.
    wirelessSPI.openWritingPipe(wAddress[xMitter-1]); //Open writing pipe to the nRF24 that guessed the right number
    if(!wirelessSPI.write(&daNumber, 1))  worked = false; //write the correct number to the nRF24 module, and check that it was recieved
    else worked = true; //it was recieved
    wirelessSPI.startListening(); //Switch back to a reciever
    return worked;  //return whether write was successful
}

***************************Arduino Code for Transmitter 1****************************
//This sketch is from a tutorial video for networking more than two nRF24L01 tranciever modules on the ForceTronics YouTube Channel
//the code was leverage from the following code http://maniacbug.github.io/RF24/starping_8pde-example.html
//This sketch is free to the public to use and modify at your own risk

#include <SPI.h> //Call SPI library so you can communicate with the nRF24L01+
#include <nRF24L01.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/
#include <RF24.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/

const int pinCE = 9; //This pin is used to set the nRF24 to standby (0) or active mode (1)
const int pinCSN = 10; //This pin is used to tell the nRF24 whether the SPI communication is a command or message to send out
byte counter = 1; //used to count the packets sent
bool done = false; //used to know when to stop sending packets
RF24 wirelessSPI(pinCE, pinCSN); // Create your nRF24 object or wireless SPI connection
const uint64_t wAddress = 0xB00B1E50D2LL;              // Pipe to write or transmit on
const uint64_t rAddress = 0xB00B1E50B1LL;  //pipe to recive data on

void setup()  
{
  Serial.begin(57600);   //start serial to communicate process
  randomSeed(analogRead(0)); //create unique seed value for random number generation
  wirelessSPI.begin();            //Start the nRF24 module
  wirelessSPI.openWritingPipe(wAddress);        //open writing or transmit pipe
  wirelessSPI.openReadingPipe(1,rAddress);  //open reading or recieve pipe
  wirelessSPI.stopListening(); //go into transmit mode
}


void loop()  
{
   if(!done) { //true once you guess the right number
     byte randNumber = (byte)random(11); //generate random guess between 0 and 10
   
    if (!wirelessSPI.write( &randNumber, 1 )){  //if the write fails let the user know over serial monitor
         Serial.println("Guess delivery failed");      
     }
     else { //if the write was successful 
          Serial.print("Success sending guess: ");
          Serial.println(randNumber);
       
        wirelessSPI.startListening(); //switch to recieve mode to see if the guess was right
        unsigned long startTimer = millis(); //start timer, we will wait 200ms 
        bool timeout = false; 
        while ( !wirelessSPI.available() && !timeout ) { //run while no recieve data and not timed out
          if (millis() - startTimer > 200 ) timeout = true; //timed out
        }
    
        if (timeout) Serial.println("Last guess was wrong, try again"); //no data to recieve guess must have been wrong
        else  { //we recieved something so guess must have been right
          byte daNumber; //variable to store recived value
          wirelessSPI.read( &daNumber,1); //read value
          if(daNumber == randNumber) { //make sure it equals value we just sent, if so we are done
            Serial.println("You guessed right so you are done");
            done = true; //signal to loop that we are done guessing
          }
          else Serial.println("Something went wrong, keep guessing"); //this should never be true, but just in case
        }
        wirelessSPI.stopListening(); //go back to transmit mode
      
     }
   }
    delay(1000);
}

***************************Arduino Code for Transmitter 2****************************
//This sketch is from a tutorial video for networking more than two nRF24L01 tranciever modules on the ForceTronics YouTube Channel
//the code was leverage from the following code http://maniacbug.github.io/RF24/starping_8pde-example.html
//This sketch is free to the public to use and modify at your own risk

#include <SPI.h> //Call SPI library so you can communicate with the nRF24L01+
#include <nRF24L01.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/
#include <RF24.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/

const int pinCE = 9; //This pin is used to set the nRF24 to standby (0) or active mode (1)
const int pinCSN = 10; //This pin is used to tell the nRF24 whether the SPI communication is a command or message to send out
bool done = false; //used to know when to stop sending guesses
RF24 wirelessSPI(pinCE, pinCSN); // Create your nRF24 object or wireless SPI connection
const uint64_t wAddress = 0xB00B1E50C3LL;  //pipe for writing or transmitting data
const uint64_t rAddress = 0xB00B1E50A4LL;  //pipe for reading or recieving data

void setup()  
{
  Serial.begin(57600);   //start serial to communicate process
  randomSeed(analogRead(0)); //create unique seed value for random number generation
  wirelessSPI.begin();            //Start the nRF24 module
  wirelessSPI.openWritingPipe(wAddress);    // setup pipe to transmit over
  wirelessSPI.openReadingPipe(1,rAddress);  //set up pipe to recieve data
  wirelessSPI.stopListening();  //turn off recieve capability so you can transmit
}


void loop()  
{
  if(!done) { //true once you guess the right number
     byte randNumber = (byte)random(11); //generate random guess between 0 and 10
   
    if (!wirelessSPI.write( &randNumber, 1 )){  //if the write fails let the user know over serial monitor
         Serial.println("Guess delivery failed");      
     }
     else { //if the write was successful 
          Serial.print("Success sending guess: ");
          Serial.println(randNumber);
       
        wirelessSPI.startListening(); //switch to recieve mode to see if the guess was right
        unsigned long startTimer = millis(); //start timer, we will wait 200ms 
        bool timeout = false; 
        while ( !wirelessSPI.available() && !timeout ) { //run while no recieve data and not timed out
          if (millis() - startTimer > 200 ) timeout = true; //timed out
        }
    
        if (timeout) Serial.println("Last guess was wrong, try again"); //no data to recieve guess must have been wrong
        else  { //we recieved something so guess must have been right
          byte daNumber; //variable to store recived value
          wirelessSPI.read( &daNumber,1); //read value
          if(daNumber == randNumber) { //make sure it equals value we just sent, if so we are done
            Serial.println("You guessed right so you are done");
            done = true; //signal to loop that we are done guessing
          }
          else Serial.println("Something went wrong, keep guessing"); //this should never be true, but just in case
        }
        wirelessSPI.stopListening(); //go back to transmit mode
      
     }
   }
    delay(1000);
}

Thursday, February 6, 2014

Building a Wireless Temperature Sensor Network Part 1

In this ForceTronics' inaugural project we will be building a wireless temperature sensor network that will include features such as battery powered sensors and the ability to access the temperature data over the internet via a computer or an iOS device such as an iPhone.

The two main building blocks we will be using for this project are an Arduino Board (first the Uno and then later the Yun to add internet capability) and XBee Wireless RF Modules. Now it is assumed that the reader has a basic understanding what Arduino is and some basic experience with the Arduino Uno board, if you do not have Arduino experience don't fret just go to arduino.cc to get started and come back here when you are ready. As for XBee, no experience is necessary we will go over the basics of using XBee here for this project.

Building a wireless temperature sensor network is no easy task so we will break this project up into parts and each part will be covered in a separate post. The project will be broken up into 6 parts, they are as follows:
  1. Introduction, getting started with XBee, and using XBee with Arduino (This post is part 1)
  2. Gathering data from multiple sensors
  3. Design options for powering your sensor network
  4. Design options for powering your sensor network continued 
  5. Monitoring your sensor network over the internet and logging temperature data
  6. Connecting to your sensor network with your iOS device
The focus of the rest of this post will be to learn the basics of XBee and how to use it with Arduino. In an attempt not to reinvent the wheel, we will refer to some fantastic XBee video tutorials created by "tunnelsup." The "XBee Basics" video tutorials is a series made up of 5 video, but you do not need to do all of the videos to complete this project. I am recommended that you actually get the parts and complete Lessons 1 and 4. For lessons 2 and 3 I recommend you watch them and follow along, but you do not need to actually get all the parts and do them (unless you want to). You will not need to do lesson 5 for this project, but if you want to feel free it can only help. Each video provides a parts list of what is needed to complete the tutorial, but if you want to buy in bulk to get you through part 1 and 2 of this project see the parts list at the end of this post.

XBee Basics - Lesson 1 - General Information and Initial Setup

XBee Basics - Lesson 2 - Simple Chat Program Between Two XBees



Hardware you will need for part 1 and 2 of the wireless temperature sensor network project is listed below. Two places where you can buy all this hardware is sparkfun.com and adafruit.com.
  • An Arduino Uno or similar Arduino board. When we add internet connectivity in part 4 to our sensor network we will switch to the Arduino Yun. 
  • Three XBee Modules, ZB Series 2, 2mW with Wire Antenna.
  • Either three XBee Explorers USB from SparkFun or three XBee Adapter Kits from Adafruit (used in video tutorial) for programming and connecting to our XBee modules. If you want to save some money you could just buy two XBee Explorer boards or Xvee Adapter boards, but you will need to buy parts to get your XBee board to plug into a standard breadboard.
  • At least two cables to connect your XBee Explorer boards or XBee Adapter boards to a computer. See the product details for which type cable you need with your board.
  • Three mini breadboards.
  • Three TMP36 or MCP9700 temperature sensors.
  • A power supply that is capable of outputting 3.3 V for powering two of the XBee modules. If you are using the Adafruit Xbee Adapter Kits your power supply can output anywhere between 3.3 V and 5 V since they have an onboard regulator. The third XBee module will be powered by the Arduino board. 
  • Wiring, wire strippers, and a soldering iron
That is it for part 1 of building a wireless temperature sensor network. If you have any questions on what was covered here feel free to asked them in the comments section below or email me at forcetronics@gmail.com. Stay tuned for part 2!



Wednesday, February 5, 2014

Building a Wireless Temperature Sensor Network Part 2

Welcome to part 2 of building a wireless temperature sensor network. In part 1 we learned the basics of how to use XBee and how to use it with Arduino. In this post we will start to build our sensor network and collect temperature data from multiple sensors. The parts list for this post can be found at the end of the part 1 post. Our hardware setup will be very similar to the setup in XBee Basics Lesson 4 video tutorial (found in part 1), except we will add a second XBee router with a temperature sensor and we will add a third temperature sensor to our Arduino board.

Let's get started by installing the proper firmware on our three XBee modules. We want to setup the XBee firmware the same way as in the XBee Basics Lesson 4 video except this time setup two routers instead of one. Be sure to use the same PAN ID for each. Once you have the proper firmware on the XBees let's put the hardware together as shown in the below figure.

Hardware setup for capturing temperature data from multiple XBees
As you can see in the figure, the two routers are tied to the same power supply. That is not very useful for creating a network, but this is just to get started. In part 3 we will look at options for powering each sensor so we can spread them out. You will need to solder a wire or pin to the AD3 hole on the XBee adapter board so you can connect it to the temperature sensor's output on the breadboard. Going forward I will refer to the Arduino and XBee coordinator as the "controller" since it gathers the temperature data from the router XBees, turns it into useful information, and communicates it to the user. Please note that I tied sensor 3 to one of the analog pins on the Arduino so we will use the Arduino to make the analog measurement for calculating the temperature from sensor 3. Having a temperature sensor on the controller is optional. Depending on how you choose to use your sensor network, you may or may not want to make temperature readings at the controller. Below are photos of my setup. The first photo shows the two routers on small red breadboards connected to the TMP36 or MCP9700 temperature sensors. The alligator clips you see in the picture are from the power supply, which is putting out 3.3 V since I am using the Sparkfun Xbee boards (no onboard regulator like the Adafruit versions).

The two routers each with a temperature sensor
XBee coordinator, temperature sensor, and Arduino Uno
The two main differences between this setup and the setup we saw in XBee Basics Lesson 4 is we have two routers sending the controller temperature data and we also have a temperature sensor tied to the controller. That means in the Arduino code we now need to read the address from the received frame of data from each router to determine which router sent it. We also need to read the temperature from sensor 3 and display it to the user. Below is the code for the Arduino with comments to explain what is happening in each line of code. When you go through the code you will want to have the the format or layout of an XBee API RX data frame on hand so you can understand what is happening in the code when it is handling incoming data from the routers. You can get this information from the XBee manual or from the XBee S2 Quick Reference Guide that was in lesson 3 and 4 of the XBee Basics video series. You can get the reference guide from the tunnelsup blog, if you do use it I encourage you to donate $1 to blog. Click here to go access the reference guide.

/*This program was written for the Arduino Uno. The Uno has an XBee Series 2 RF Module connected to it as a coordinator. The Uno uses the XBee coordinator to communicate with two router or end point XBees with temperature sensors. This program recieves the temperature readings from the two endpoint XBees and writes the data to the serial monitor */

/*Each Xbee has a unque 64 bit address. The first 32 bits are common to all XBee. The following four ints (each int holds an address byte) hold the unique 32 bits of the second half of the XBee address*/
 int addr1;
 int addr2;
 int addr3;
 int addr4;
 int sen3Counter = 0; //This counter variable is used print sensor 3 every 5 seconds

void setup()  { 
 Serial.begin(9600); //start the serial communication
}

void loop()  { 
  if (Serial.available() >= 21) { // Wait for coordinator to recieve full XBee frame 
    if (Serial.read() == 0x7E) { // Look for 7E because it is the start byte
      for (int i = 1; i<19; i++) { // Skip through the frame to get to the unique 32 bit address
        //get each byte of the XBee address
        if(i == 8) { addr1 = Serial.read(); }
        else if (i==9) { addr2 = Serial.read(); }
        else if (i==10) { addr3 = Serial.read(); }
        else if (i==11) { addr4 = Serial.read(); }
        else { byte discardByte = Serial.read(); } //else throwout byte we don't need it
      }
      int analogMSB = Serial.read(); // Read the first analog byte data
      int analogLSB = Serial.read(); // Read the second byte
      float volt = calculateXBeeVolt(analogMSB, analogLSB);//Convert analog values to voltage values
      Serial.println(indentifySensor(addr1,addr2,addr3,addr4)); //get identity of XBee and print it
      Serial.print("Temperature in F: ");
      Serial.println(calculateTempF(volt)); //calculate temperature value from voltage value
    }
  }
  delay(10); //delay to allow operations to complete
  //This if else statement is used to print sensor 3 value every 5 second to match the XBee routers
  //It uses the delay() function above to calculate 5 seconds
  if (sen3Counter < 500) { sen3Counter++; }
  else {
    Serial.println("Temperature from sensor 3:");//This is sensor 3
    Serial.print("Temperature in F: ");
    //the following line calculates voltage, then temperature, and then prints temp to serial monitor
    Serial.println(calculateTempF(calculateArduinoVolt(analogRead(A0))));
    sen3Counter = 0; //reset counter back to zero to start another 5 seconds
  }
}

//Function takes in the XBee address and returns the identity of the Xbee that sent the temperature data
String indentifySensor(int a1, int a2, int a3, int a4) {
  int rout1[] = {64, 176, 163, 166}; //Arrays are the 32 bit address of the two XBees routers
  int rout2[] = {64, 177, 63, 221}; 
  if(a1==rout1[0] && a2==rout1[1] && a3==rout1[2] && a4==rout1[3]) { //Check if Sensor 1
    return "Temperature from sensor 1:"; } //temp data is from XBee one
  else if(a1==rout2[0] && a2==rout2[1] && a3==rout2[2] && a4==rout2[3]) {//Check if Sensor 2
    return "Temperature from sensor 2:"; } //temp data is from XBee two
  else { return "I don't know this sensor"; }  //Data is from an unknown XBee
}

//this function calculates temp in F from temp sensor
float calculateTempF(float v1) { 
 float temp = 0;
 //calculate temp in C, .75 volts is 25 C. 10mV per degree
 if (v1 < .75) { temp = 25 - ((.75-v1)/.01); } //if below 25 C
 else if (v1 == .75) {temp = 25; }
 else { temp = 25 + ((v1 -.75)/.01); } //if above 25
 //convert to F
 temp =((temp*9)/5) + 32;
 return temp;
}

//This function takes an XBee analog pin reading and converts it to a voltage value
float calculateXBeeVolt(int analogMSB, int analogLSB) {
  int analogReading = analogLSB + (analogMSB * 256); //Turn the two bytes into an integer value
  float volt = ((float)analogReading / 1023)*1.23; //Convert the analog value to a voltage value
  return volt;
}

//This function takes an Arduino analog pin reading and converts it to a voltage value
float calculateArduinoVolt(int val) {
 float volt = (float)val * (5.0 / 1023.0); //convert ADC value to voltage
 return volt;
}

The next step is to take the code and upload it to the Arduino. Do not forget to disconnect the wire connecting the Arduino digital pin 0 to the XBee coordinator when you upload the code to the Arduino or else you will get an error. Once the code it uploaded, reconnect the wire to digital pin 0 and open the serial monitor. If you have everything setup correctly your serial monitor should look something like the one in the below figure. 

Serial monitor displaying data from each temperature sensor
It is a good idea to place all your sensors in the same area so you know that they should have a similar temperature reading. That way if one of the sensors is off you can easily spot it and investigate what the problem is. Note that these sensors have an accuracy tolerance of +/- 1 degree from the actual temperature so theoretically your sensor readings could differ by up to 2 degrees even if they are right next to each other. If your serial monitor does not look something like the figure above don't worry just go over instructions again to make sure everything is correctly setup, its easy to miss something! If you see the sensor 3 readings in your serial monitor, but you are missing sensor 1 or 2 or both that means one or both of your routers is not sending data to the coordinator. Check the power and communication lights on the XBee adapter boards to ensure they are getting power and are communicating with the coordinator. If they have power, but are not communicating check to make sure you loaded the correct configuration on them.

Well that is it for part 2. Normally I would share the list of parts you need for the next part of the project, but in part 3 and part 4 we will look at multiple options for powering the sensors in the project so read it first and then decide what works best for powering your temperature sensor network. If you have any questions on part 2 use the comment area below or feel free to email your question to me at forcetronics@gmail.com. Stay tuned for part 3!


Tuesday, February 4, 2014

Building a Wireless Temperature Sensor Network Part 3

Welcome back for part 3 of building a wireless temperature sensor network. In part 2 we started to build our sensor network and collect temperature data from multiple sensors. In this post (part 3) and continuing into the next post (part 4) we will look at some design options for powering our wireless sensors so we can spread them out to anywhere we need to monitor the temperature.

The two power source options we will consider for powering our wireless sensors are battery power and an AC line powered DC power supply. What I mean by “AC line powered DC power supply” is the low cost constant voltage power supplies that often come with consumer electronics or that can be bought standalone from places like Radio Shack. In the below picture is an example of low cost DC power supply that puts out a constant 12 VDC and up to 200 mA.


Before deciding on a power source, lets first cover the need for a voltage conversion stage in our sensor designs. Whether we use a power supply or a battery pack they probably will not output the exact voltage we need for the sensors, which is 5 V for the controller and approximately 3.3 V for the routers hence the need for a voltage conversion stage. For doing voltage conversion there are two main options available: voltage regulators and DC to DC converters. Each has their advantages and disadvantages. Voltage regulators are low cost and less complex, but are less efficient (more power loss in the conversion process). DC to DC converters are more efficient, but are more complex to implement and can be more expensive. Let me add explanation around the complexity of DC to DC converters. When you implement a DC to DC converter you need to add a lot of “supporting components” (resistors, capacitors, inductors) at the input and output of the DC to DC converter to have it operate correctly, which is beyond the scope of this post. But there is a way around it, some companies sell DC to DC converters with the “supporting components” already built-in. These DC to DC converters are easy to implement like voltage regulators, but still deliver great efficiency. Their downside is cost, they will easily be 5 or more times the price of a voltage regulator.

Which voltage conversion method you use in your design depends on factors such as power efficiency needs, budget, project time table. For instance, is power efficiency critical to your design? If your sensor needs to be battery powered and it is going to be located in a place where it can not be easily accessed than you probably want to go with a DC to DC converter. If your sensor will be near a power outlet or if changing the battery and recharging it is easy than the voltage regulator is a good choice. In this tutorial we will us both conversion methods for example purposes.

If you want to power your sensors using battery power the most common battery technologies for this task include alkaline, nickel metal hydride (NiMH), lithium ion (Li-ion), and lithium ion polymer (Li-ion polymer). Alkaline batteries are the ones you buy at the store for your TV remote or flashlight, they are typically not rechargeable. The other battery technologies listed above are rechargeable and have their advantages and disadvantages. Covering the details of each battery technology and their safety precautions is beyond the scope of this tutorial. Luckily there is plenty of information on the internet on these battery technologies and how to use them safely so if you plan to use batteries to power your sensor do your homework first. Especially if you want to use the Li-ion or Li-ion polymer technologies because they are the most dangerous. For this tutorial we will use two different battery technologies for example purposes, alkaline and Li-ion polymer.

Here is a breakdown of the power source and voltage conversion technique that will be used for each part of the wireless sensor network:
  • For the controller the Arduino Uno has a built-in voltage regulator at the power input connector that takes 7 to 12 VDC power source and converts it to 5 V to power the Uno. A 9 V DC power supply will be used to power the controller. The power supply was obtained from an old cordless phone.
  • For sensor 1 (XBee router with temperature sensor) we will use the LM317 voltage regulator for the conversion stage. This is a common low cost regulator that has an adjustable output voltage. You can find it at RadioShack. The datasheet, which you can easily find online, explains how to set the output voltage using basic components. For instructions on how I set the output voltage to 3.3 V for this project see the last section of this post. The power source we will use is a 7.4 volt Li-ion polymer rechargeable battery pack. 
  • For sensor 2 we will use the TSR12433 DC to DC converter that requires no external components, just plug in and go. This was $15 and it was purchased from Adafruit. The power source we will use is four series Alkaline batteries. You could easily get away with three series Alkaline batteries, four was used because I had a holder for four batteries.
What is nice about the XBee modules is they use very low power in general so with the power setups we are using we are going to get good battery life. Let's do some quick calculations to look at what kind of battery life we can expect with these two battery powered setups. To do this let's first look at the amp hour (abbreviated 'Ah') ratings of our two battery based power sources:
  1. The 7.4 V Li-ion Polymer is rated for 2200 mAh or 2.2 Ah.
  2. The Ah ratings for Alkaline batteries varies widely depending on the brand, a good rule of thumb is the higher the cost the more Ah you are getting. We will use the conservative estimate of 1500 mAh or 1.5 Ah for each battery so a total of 6000 mAh or 6 Ah
Next for our battery life calculation we need to know the average current consumption of sensor 1 and sensor 2. We need to know on average how much current does the XBee router, temperature sensor, and power conversion stage consume. To do this I measured the current consumption of each sensor design using an Agilent N6705B DC power analyzer. I am fortunate enough to have access to this device at work since it is out of the price range of most hobbyists. For sensor 1 the average current consumption was 15.59 mA, for simplicity we will round up to 16 mA. For sensor 2 the average current consumption was 6.58 mA, for simplicity we will round up to 7 mA. Please note that using the regulator more than doubles the current consumption of our sensor. This results in the following battery life calculations:
  1. Sensor 1 --> 2200 mAh / 16 mA = 137.5 hours of battery life or ~ 6 days
  2. Sensor 2 --> 6000 mAh / 7 mA = 857.1 hours of battery life or ~ 36 days
The lower current consumption of the DC to DC converter combined with the higher Ah rating of the Alkaline batteries results in ~ 6 times longer battery life for sensor 1 compared to sensor 2. This is the power design direction you would want to go with if your sensor is going to be used in an area that is not easy to access. The sensor 2's power design is a lower cost example since the regulator is cheap and you do not have to keep buying new batteries since the Li-ion Polymer is rechargeable. 

As a comparison of the sensor 1 and 2's current consumption compared to the controller's (sensor 3), the controller's average current consumption is 102.6 mA. As you can see the Arduino consumes quite a bit more power compared to the XBee. You can further increase the battery life of your sensors by using the "sleep" capabilities of the XBee modules. We will not be getting into the details of the sleep capabilities of the XBee modules in this project, but refer to the XBee manual for details on using the sleep capabilities. 

That is it for part 3 of building a wireless sensor network. We will see you back soon for part 4 where we will look at a schematic diagram of our sensors with the new power sections added, we will implement a way to know when our batteries need to be replaced, and make the needed changes to our Arduino code to accommodate these changes. 

Setting the output of the LM317 voltage regulator
The LM317 is a widely used low cost regulator. It is great part to keep in stock around you electronics lab bench since its output voltage level is adjustable so you can fit it into any project you are working on. It is made by a couple different manufacturers including Fairchild, you can find its data sheet by following the link: http://www.fairchildsemi.com/ds/LM/LM317.pdf. The figure below is from page 5 of the datasheet and it shows the circuit setup and equation to set the output voltage level to the value you desire.


From the above equation we need to solve for R2 because that is the unknown. Also since IADJ is so small we can just take the last term out of the equation. Solving for R2 and dropping out the last term we get:
R2 = (Vo*R1)/1.25 - R1. Now we just need to plug in our known values which are 3.3 V for Vo and for R1 I used a 301 Ohm resistor that was laying around. plugging in our values to the equation we get 494 Ohms for R2. To implement R2 a 1 kOhm adjustable resistor was used. The resistor was adjusted to about ~500 Ohms. I then connected its input to the battery and its output to the sensor. I used a DMM to measure the resulting output voltage of the regulator and fine tuned the resistor value to get exactly 3.3 VDC, the desired output voltage.