JeeNode/ZigBee pressure sensor closed

Now that my Zigbee/Jeenode equipped pressure sensor is working for 3 months without any problems, it was time to leave the breadboard stage and move on to something more permanent. While ordering new Jeenodes at Jean-Claude Wipplers shop, i stumbled upon a post (i should read his daily weblog more often!) that showed me just what i needed: an enclosure that looked just right for this job. I ordered the Jeenodes, 2 enclosures (1 extra for when i mess up the first one and don’t want to wait for a second delivery..) and some other handy stuff.

First i sawed off the part of the PCB that i didn’t need, to decrease it’s size.

JeeNode PCB without RF part

JeeNode PCB size reduction

Guess what? Now the length of the PCB equals the internal width of the enclosure! Nice… I still had some battery holders laying around that also fitted quite well:

Enclose, batt holder and JeeNode

Enclosure, batt holder and JeeNode

I didn’t want to leave off the FTDI headers, so i used 6 straight headers and removed the plastic strip from the headers after the headers were soldered onto the PCB. With the plastic headers left on, the completed PCB was just a bit to wide for the enclosure, which caused tension and the enclosure wouldn’t close well anymore.

Next item that had to be prepared, was the XBee Breakout Board. Normally the top of this Breakout Board contains the 2mm XBee headers and the 0.1″ spaced headers are at the opposite side. I removed the bottom headers i soldered in when i used this board for other purposes and soldered 6 wires on it from the top, only for those pins i really needed:

XBee Breakout Board

XBee Breakout Board

Pin 1 (labeled Vcc) for Power, Pin 3  (labeled DIN) for transmission, Pin 9 (DTR) for controlling Sleep mode, Pin 10 (GND), Pin 11(CTS) and Pin 12 (ON) for the LED. This makes the Breakout board a lot thinner and the wires are coming out between the board and the XBee module.

After soldering the wires coming from the XBee board to the JeeNode, drilling a hole for the LED (which blinks when a pressure sample is being sent), soldering the wires and gluing the battery holder into the enclosure, it looked like this:

Almost done!

Almost done!

The FTDI headers are very handy now, for uploading the sketch with the JeeNode already inside the enclosure; cause all you have to do is open the enclosure, gently lift up the left side of the JeeNode and connect the cable. So whenever i need to upgrade the JeeNode, i don’t have to worry about connecting issues.

FTDI cable connected to the JeeNode

FTDI cable connected to the JeeNode

Now all there was left to do was moving the XBee module and the Pressure Plug from the Breadboard to their new ‘home’, add 4 batteries, click on the other half of the enclosure and.. my first WAF certified sensor was born!

Zigbee Pressure sensor

LED strip integrated in Domotica system

Now that the new floor is nearly finished, i can start working on some Home Automation related subjects again; the first was using LED strips in the kitchen.

LED strips

LED strips

In total 4 segments of LED strip are used; 2 near the floor at the plinths of the lower kitchen cabinets, 1 at the counter top and 1 on top of the upper kitchen cabinets.

Today i finished controlling all these LED strips individually.

I don’t have Ethernet in the kitchen, so i used the ZigBee approach (again :-)). I mounted a XBee on a Sparkfun XBee RS232 board and connected it to the Chromoflex RS232 RX input:

XBee and Chromoflex in a box

XBee and Chromoflex in a box

The XBee RS232 board is powered by the adapter that also powers the Chromoflex, so all i needed was a wall outlet for the Chromoflex adapter and the Chromoflex was “connected”.

Now it was time to add control functions to my Touchscreen application, running on my Asus TOP in the livingroom. I added a “LED” button on the floorplan, in the middle of the kitchen:

LED button on the floorplan

LED button on the floorplan

And i found a very cool Trackbar Control and created a new pop-up form with it, that appears when you push the “LED” button:

LED Trackbar

LED Trackbar

With this form i can control each LED segment individually. To minimize traffic, i used the same approach as i did earlier with controlling my thermostat; a timer event fires when the Trackbar value hasn’t changed for 1.5 seconds and sends the new value to my Domotica System by XMLRPC:

VB.Net code

That’s all there is to it. My Domotica system takes care of the rest e.g. building the Chromoflex packet based on the USP3 protocol, wrapping it in a XBee Transmit Request packet and sending it to the ZigBee coordinator. Home Automation is sooo cool 🙂

Wireless LED strip control

Well, this post could just as well be called Wireless Chromoflex controller, or Zigbee LED Strip controller, or … 🙂

What i’m actually trying to accomplish is placing 14 meters of LED strip, split into 5 separately controllable parts in my house, without the need of additional wiring (i hate that!).  Just plug it into the mains and start using it… that’s the goal.

Yesterday the last goods i was waiting for arrived, so tonight it was time to make some sort of ‘proof of concept’; would i be able to control a Chromoflex by using Zigbee as transport medium instead of wires? Of course! Why wouldn’t it? But it’s always nice to actually see it working with your own eyes; and tonight i did.

Wireless Chromoflex

Wireless Chromoflex

In terms of programming, enabling my Home Automation system to be able to control an interface like the Chromoflex by using Zigbee, needed some additional coding. Normally an interface is addressed directly over TCP/IP or RS232, but this time i could not transmit the Chromoflex packet directly; it had to be encapsulated in a Zigbee Transmit Request frame. A feature that will be very useful in the future i guess.

To be continued…

First DIY Zigbee sensor operational

On my desk i have a JeeNode, equipped with a Pressure sensor. This JeeNode is also controlling a XBee Series 2 module which is configured as Zigbee End Device. All this is battery powered. Calculations on power usage of the JeeNode+Sensor+XBee are good enough to expect an acceptible battery life. A Sparkfun XBee RS232 holds another XBee module, configured as Zigbee coordinator. This setup has been operating for more than a week now. It all looks stable enough to go ahead and connect the Zigbee network (ok, it’s only 2 nodes right now 🙂 ) to my Domotica system and  actually do something with it; something different from logging the incoming pressure data to a text file and reviewing this file periodically to see if everything is still up and running; so i added another (the 16th) interface to my Domotica system: Zigbee! 🙂

In fact all the hard work had already been done in an earlier stage where i created an API-mode interface for Zigbee; in essence, the only thing left to do was making this interface ‘talk’ to the rest of the Home Automation system, add some records in the database for this new sensor type and write a routine that would convert the incoming packets to the measured values of temperature and pressure.

Zigbee interface

Wow! It’s great to see my first Zigbee based sensor really working! The pressure data is being stored in the database, so in a few hours i can start creating an additional web page to show a pressure chart… and here it is!

BMP085 Pressure sensor data

BMP085 Pressure sensor data

Next on the list: finding a suitable, small housing, making a light sensor, a motion sensor, humidity sensor, … the list is to long! 🙂

Battery powered sensors

Now that i have 2 JeeNodes up and running for more than a week and everything’s working fine, it’s time to do some calculations on power usage of the sensors. First thing i wanted to know was how much power a combination of a sensorless Jeenode and XBee module was using, so i created a sketch that would give me some ‘inside’ information about what was going on inside the Jeenode. The sketch i made informs me about a couple of things, like:

– the timespan the JeeNode is awake to power up the XBee, send a packet to the XBee and wait for it to finish transmission;

– the timespan the XBee is powered to send that packet of 10 bytes.

Battery powered JeeNode

With these numbers i should be able to roughly calculate the power usage of this sensor. The power that is used by the JeeNode while it’s awake is about 35 mA, while the XBee uses around 40 mA while transmitting. When both the JeeNode and XBee are in deep sleep, the combination of both uses only 60 μA.

The time measurements i did to find out the timespans mentioned above gave me the following figures: the total time the JeeNode is awake to read a sample from the Pressure sensor, wake the XBee, transmit the data and go back to sleep is 40 ms. The time that the XBee is awake is around 25 ms. With a sample interval of 30 seconds, and a 2000 mAh battery, i have calculated a battery life of more than a year; increase the interval to 60 seconds (still good enough for this type of information) and batteries should survive more than 2 years… i think.

Just ask me in a year or so ..

But good enough to go ahead with the expedition! 🙂

Wireless Pressure Sensor – small fix

The fact that in the setup i made yesterday, the XBee module sometimes had trouble setting up the connection was troubling me, so i tried to figure out what was going on. My guess was that the CTS line was not monitored, so i built a counter into the loop that waits for CTS to get high; and made this counter part of the packet payload so that i could monitor what was going on; this counter  was always 1, meaning CTS was high at the time the first CTS check was done!

Hmm, seeing that, the error was found very quickly: CTS was attached to the wrong digital input, so CTS wasn’t monitored at all… fixed the wiring and now everything’s OK.

Second thing i changed was for the sake of convenience: the new sketch does the temperature and pressure calculations “on board”, so now the payload immediately shows value that are easily interpreted. I also took the time to create a small Delphi program that uses my XBee API to log all the packets that are received in a more readable style:

31-1-2010 20:43:30:Packet payload=[2 215 100159]
31-1-2010 20:43:41:Packet payload=[7 215 100150]
31-1-2010 20:43:52:Packet payload=[0 215 100153]
31-1-2010 20:44:03:Packet payload=[0 215 100156]
31-1-2010 20:44:14:Packet payload=[0 215 100166]
31-1-2010 20:44:25:Packet payload=[5 215 100156]
31-1-2010 20:44:36:Packet payload=[10 215 100159]
31-1-2010 20:44:47:Packet payload=[0 215 100150]
31-1-2010 20:44:59:Packet payload=[0 215 100156]
31-1-2010 20:45:10:Packet payload=[0 214 100153]

The first value is the time in milliseconds that it takes for the CTS to become high, the second value is the temperature in 1/10th of a degree and the last value is the pressure in mbar.  Neat 🙂

Wireless Pressure Sensor – first results

JeeNode connected to XBee

JeeNode connected to XBee

Here you see my first setup of a JeeNode with pressure sensor connected to a XBee Series 2 module.  And it’s working! With Hyperterminal i captured the raw data coming in on my XStick:

XBee API mode packets with sensor data

XBee API mode packets with sensor data

The ‘experts’ will immediately recognize the first character (tilde, ~) as being the frame header of a XBee packet. The payload on the first line is ‘26311 39767’. All characters before that are XBee API frame related as well as the last character, which is the checksum. When you have a look at the code you can see what the payload is made of.

This is absolutely very cool; it think in total it has cost me an evening to put this all together; something i would have never dared dreaming about a year ago!

But there’s still a lot to do:

There seems to be a timing issue in the code, cause i saw the XBee having a bit of trouble joining the PAN. Maybe give it some more time in the setup routine, or give some more time during powering up the XBee to send a new sample… we’ll see.

I need to write some software on PC-side to test reliability of it all.

How long will the batteries survive? I haven’t got a clue… and how am i going to test this? For example, i can’t switch off my PC now, cause the XStick is powered by it; XStick not powered means no PAN means the XBee will keep on searching for the PAN and will use much much more power…

To make the whole package smaller, i need to stop using the pin headers on the JeeNode and just solder the wires right onto the board.

A big step ahead, but still a lot of questions to be answered…

Here’s the code that is currently running on the JeeNode:

#include <Ports.h>
#include <RF12.h>
#include "PortsBMP085.h"
#include <avr/sleep.h>
#include <NewSoftSerial.h>

NewSoftSerial XBSerial = NewSoftSerial(2, 3);
PortI2C two (2);
BMP085 psensor (two);

int pinXBee=7;                        // to Control XBee on/off
int pinCTS=6;                         // to monitor CTS

static int SampleInterval = 1000;     // 60000;
static int HeartBeatInterval = 10000; // 300000;
static int CTS=0;                     // value of XBee CTS pin

struct {
    int16_t temp;
    int32_t pres;
} payload;

static void lowPower (byte mode) {
    // prepare to go into power down mode
    set_sleep_mode(mode);
    // disable the ADC
    byte prrSave = PRR, adcsraSave = ADCSRA;
    ADCSRA &= ~ bit(ADEN);
    PRR &= ~ bit(PRADC);
    // zzzzz...
    sleep_mode();
    // re-enable the ADC
    PRR = prrSave;
    ADCSRA = adcsraSave;
}

EMPTY_INTERRUPT(WDT_vect); // just wakes us up to resume

static void watchdogInterrupts (uint8_t mode) {
    MCUSR &= ~(1<<WDRF); // only generate interrupts, no reset
    cli();
    WDTCSR |= (1<<WDCE) | (1<<WDE); // start timed sequence
    WDTCSR = bit(WDIE) | mode; // mode is a slightly quirky bit-pattern
    sei();
}

static byte loseSomeTime (word msecs) {
    // only slow down for periods longer than twice the watchdog granularity
    if (msecs >= 32) {
        for (word ticks = msecs / 16; ticks > 0; --ticks) {
            lowPower(SLEEP_MODE_PWR_DOWN); // now completely power down
            // adjust the milli ticks, since we will have missed several
            extern volatile unsigned long timer0_millis;
            timer0_millis += 16L;
        }
        return 1;
    }
    return 0;
}

static MilliTimer SampleTimer;     // Interval for reading a sample from the BMP085
static MilliTimer HeartBeatTimer;  // forced maximum interval (Heartbeat)

static byte periodicSleep (word msecs) {
    // switch to idle mode while waiting for the next event
    lowPower(SLEEP_MODE_IDLE);
    return SampleTimer.poll(msecs);
}

static void Send (const void* ptr, byte len) {

  unsigned long tXB1;    // time XBee was woken up
  unsigned long tXB0;    // time XBee was put to sleep

  Serial.println("Sending payload");
  HeartBeatTimer.set(0);

  CTS = HIGH;
  tXB1=millis();
  // wake up Xbee
  digitalWrite(pinXBee,LOW);

  // wait for CTS to become LOW
  do
  {
    CTS=digitalRead(pinCTS);
  } while (CTS != LOW);

  // wait 2 msec otherwise data will be received all messed up
  delay(2);

  // send dummy data
  XBSerial.print(payload.temp);
  XBSerial.print(" ");
  XBSerial.println(payload.pres);

  Serial.print(payload.temp);
  Serial.print(" ");
  Serial.println(payload.pres);

  // wait again for XBee to finish transmission
  delay(2);

  // switch off XBee
  digitalWrite(pinXBee,HIGH);
}

static int16_t prevTemp;           // save previous temp value
static int32_t prevPres;           // save previous temp value

// this code is called once per second, but not all calls will be reported
int ReadSensor() {

    int16_t temp = psensor.measure(BMP085::TEMP);
    int32_t pres = psensor.measure(BMP085::PRES);

    Serial.print("Readings: ");
    Serial.print(temp);
    Serial.print(' ');
    Serial.print(pres);
    Serial.println(' ');

    int changed = (temp != prevTemp) || (pres != prevPres);
    prevTemp = temp;
    prevPres = pres;

    payload.temp = temp;
    payload.pres = pres;

    changed = 1;            // force sending always during testing
    return changed;

}

void setup() {

  // setup XBee
  pinMode(pinXBee,OUTPUT);
  digitalWrite(pinXBee,LOW);
  pinMode(pinCTS,INPUT);
  digitalWrite(pinCTS,LOW);   // really necessary?
  delay(10);

  XBSerial.begin(9600);
  // give XBee some time to join PAN
  delay(5000);

  // let the world know we're here
  XBSerial.println("n[TempPres]");
  Serial.println("n[TempPres]");

  watchdogInterrupts(0); // 16ms
}

void loop() {
    if (periodicSleep(SampleInterval)) {
      // sensor values changed or heartbeat interval elapsed?
      if (ReadSensor() || (HeartBeatTimer.poll(HeartBeatInterval)))
      {
         Send(&payload, sizeof payload);
       }

    }
}

Making a Wireless Pressure Sensor

I don’t own a weather station, nor do i intend to buy one, but i always did like the idea of having a pressure sensor. Now i have 🙂

This BMP085 based pressure sensor doesn’t only do pressure, but can also measure the temperature. Time to hook it up to a JeeNode!

Due to the fact that our plans for today had to be canceled by the bad weather, i had some extra time to test this Pressure Sensor. First i had to solder the 2nd JeeNode i bought last week, cause it was still unassembled in it’s plastic bag. Soldering a JeeNode is quite easy to do; it’s really hard to do something wrong… This time i left the RF12 radio off because i wanted to use one of my XBee modules to send the raw measured values. And i attached a battery holder, cause eventually this is my goal: a battery powered pressure sensor.

I installed the Ports library, uploaded the BMP085 demo sketch from the Ports Library examples  to the JeeNode and everything ran fine:

BMP 26265 39759 225 99390
BMP 26260 39755 225 99372
BMP 26267 39761 226 99400
BMP 26263 39756 225 99378
BMP 26265 39759 225 99390
BMP 26263 39758 225 99384
BMP 26261 39757 225 99378

Next step will be adding code for the XBee and sleeping. To bad, time’s up for now… hopefully, later this evening i have some time left to finish this sensor.

JeeNodev4 with BMP085 Sensor

JeeNodev4 with BMP085 Sensor

The power of Arduino and Zigbee

Today i had some spare time to combine a few of the things i’ve been working on lately:

  • My Zigbee API;
  • Arduino;
  • Pan & Tilt mechanism

I wanted to create a small executable that would enable me to control the position of the 2 servo’s.

XBee module

I started with programming the XBee: Zigbee End Device AT firmware, the right PAN, Node Identifier ED5 (as in End Device 5), Sleep Mode=1 (Pin Hibernate). I put the module on a breadboard by use of a Breakout Board. Grounded pin 9 and used the 3.3V output of the Arduino to power the module.

Arduino

I strapped the Arduino Duemilanove to the same breadboard and wired the 2 servo’s. Pins 9 and 10 of the Arduino are used as PWM output for the 2 servo’s. Arduino pins 2 & 3 were connected to the DIN and DOUT pins of the XBee module.

Sketch

Now it was time to write a sketch that would receive commands from the XBee and move the servo’s accordingly. The sketch is a real quick and dirty one, low on error handling and validation. I made up a small ‘protocol’: commands have to end with the exclamation mark (“!”) and can be either 1 or 2 characters long.

P+! would Pan right 3 degrees, P-! would Pan left 3 degrees, T+! would Tilt up 3 degrees and so on. H! is the command to go back to the Home position. Of course you can extend this as much as you like, e.g. add absolute positioning, presets, you name it.

This is the sketch:

#include <NewSoftSerial.h>
#include <ServoTimer1.h>
#include <PString.h>

ServoTimer1 PanServo;
ServoTimer1 TiltServo;

int PanAngle = 90;
int TiltAngle = 90;
byte DeltaPan = 3;         // move 3 degrees
byte DeltaTilt = 3;        // move 3 degrees
char cbuffer[40] = "";     // receive buffer
NewSoftSerial XBSerial = NewSoftSerial(2, 3);
PString buffer(cbuffer, sizeof(cbuffer));

void setup() {

  XBSerial.begin(9600);         // set up XBee at 9600 bps
  delay(10000);                 // wait 10 sec. for possible joining

  PanServo.attach(9);
  TiltServo.attach(10);

  PanServo.write(PanAngle);
  TiltServo.write(TiltAngle);
}

void waitforcommand()
{
  while (true)
  {
    if (XBSerial.available())
    {
      int c = XBSerial.read();
      if (c == 0x21)     // command terminator = "!"
      {
        break;
      }
      else
      {
        // add to buffer
        buffer.print(c,BYTE);
      };
    };
  };
}

void loop() {

  buffer="";
  waitforcommand();

  // what's the first character?
  switch (buffer[0])
  {
    case 0x50:             // P for Pan
      {
        // what's the next character?
        switch (buffer[1])
        {
          case 0x2B:       // +
            PanAngle += DeltaPan;
            break;

          case 0x2D:       // -
            PanAngle -= DeltaPan;
            break;
          };
          break;
      };
    case 0x54:            // T for Tilt
      {
        // what's the next character?
        switch (buffer[1])
        {
          case 0x2B:       // +
            TiltAngle += DeltaTilt;
            break;

          case 0x2D:       // -
            TiltAngle -= DeltaTilt;
            break;
          };
          break;
      };
    case 0x48:            // H for Home
      {
        PanAngle=90;
        TiltAngle=90;
        break;
      };

  };

  // check boundaries for Pan
  PanAngle=(PanAngle < 0)?0:PanAngle;
  PanAngle=(PanAngle > 180)?180:PanAngle;

  // check boundaries for Tilt
  TiltAngle=(TiltAngle < 90)?90:TiltAngle;
  TiltAngle=(TiltAngle > 180)?180:TiltAngle;

  // Set dervo's accordingly
  PanServo.write(PanAngle);
  TiltServo.write(TiltAngle);

}

PC software

Next item was a small program that would use the API to address the XBee module.

XBee servo control

XBee servo control

4  buttons for Left, Rigth, Up and Down, a Home button and a button to connect to the Zigbee network. Not very spectacular, I’d say.

There are 2 important API functions that are used to communicate with the Zigbee module:

  • Node Discovery
  • XBee Transmit Request.

The code that is executed when the “Connect” button is pressed, sends out a Node Discovery command. This will trigger all joined Zigbee modules to respond with information about themselves, like 16- and 64-bit address, node identifier and some more interesting stuff. The code goes something like this:

  XB:=TXBEE.Create(14,9600);
  XB.Open;
  gXBeeModules.Clear;
  cmd:=TXBee_NodeDiscover.Create('');
  XB.SendPacket(cmd.GetPacket);

The Node Identifier is used to see if the Zigbee module that is connected to the Arduino, is “in the air”. Cause it doesn’t have to be, it could be disconnected from power or whatever…

When the Zigbee module with Node Identifier “”ED5” has responded, the 5 buttons are enabled and clicking them will move the servo’s. This is done with the XBee Transmit Request function; a string is being sent to the XBee and the XBee will take care of transferring it out on the UART.  Below the code for the “Home” button:

i:=gXBeeModules.Indexof('ED5');
if i >=0
then begin
Module := TXBeeModule(gXBeeModules.Objects[i]);
Addr16:= Module.Addr16 ;
Addr64:= Module.Addr64 ;
TR:=TXBeeTransmitRequest.Create(1,Addr16,Addr64,"H!");
X.SendPacket(TR.GetPacket);
end;

Et voila, the servo’s start moving!

To see how (good or bad) it works, i’ve made a small video.
The power of Arduino and Zigbee!!!

ATMega328 and its Watchdog Timer

Now that i managed to put an XBee ZB module to sleep, all i had left to do was being able to put the RBBB to sleep for a certain amount of time (and have it wake up again!).  It would be very nice if i could use 2 triggers for waking up the controller: based on a predefined interval and by some external source (for example an attached motion detector that detects motion).

Zigbee module

Low-power Zigbee & Arduino

Both are actually equally important, so i tossed a coin with the outcome that i started with trying to accomplish to wake up the RBBB on a predefined interval. I found an article that pretty much did what i wanted. The maximum time that the Watchdog Timer can power down the microcontroller is 8 seconds, after which it will wake up again and carry on with it’s job. I modified some things so that the power down routine is called multiple times, which results in a power down mode in multples of 8 seconds. Currently the wake up interval is set at 32 (4*8) seconds and it has run flawlessly for 16 hours now. I still have to dig in deeper to the Watchdog code see if my ‘modifications’ can be made more efficient, but for now this will be OK.

Now i wonder what the power consumption of this combination of RBBB and Zigbee module is… should i let it run on a battery and wait till it stops? How long will that be…. no; i think it’s better to find a way to estimate battery life by actually measuring the power consumption. That will probably mean i will need extra hardware and tools.