Sparkfun Weather Station

I installed the Sparkfun Weather Meters mainly for the rain gauge.  It is quite expensive, and didn’t even come with the small screws which hold the anemometer and wind vane to the support arm.  It does seem to be well made, and makes my system look like a weather station.

Sparkfun Weather Meters in the wild

The datasheet shows that the rain gauge and the anemometer are magnetic reed switches; every 0.011″ of rain causes a momentary contact and a 2.4km/h wind will cause a momentary contact every second for the anemometer.  These inputs will be connected to Arduino interrupts.  The wind vane uses an array of resistors which can be read through the ADC of the Arduino, but the datasheet is wrong for the wind vane.  At 315°, the datasheet states that the voltage should be 4.78V, but in actuality, with a 10K resistor in series with a 64.9K resistor, the voltage drop across the vane will be 4.33V.

The following code setups up the inputs and the interrupts to read this device.  Note that setting a pin to INPUT and then writing a HIGH value to it turns on the internal 20K pull up resistor in the Arduino, which prevents the need for external pull up resistors on the interrupt driven devices.  The wind vane requires a 10K resistor in series with the vane’s resistors, and to save power, this resistor and the vane are powered from a digital output, which is driven HIGH only when the reading is to be taken.

#define ANEMOMETER_PIN 3
#define ANEMOMETER_INT 1
#define VANE_PWR 4
#define VANE_PIN A0
#define RAIN_GAUGE_PIN 2
#define RAIN_GAUGE_INT 0

void setupWeatherInts()
{
  pinMode(ANEMOMETER_PIN,INPUT);
  digitalWrite(ANEMOMETER_PIN,HIGH);  // Turn on the internal Pull Up Resistor
  pinMode(RAIN_GAUGE_PIN,INPUT);
  digitalWrite(RAIN_GAUGE_PIN,HIGH);  // Turn on the internal Pull Up Resistor
  pinMode(VANE_PWR,OUTPUT);
  digitalWrite(VANE_PWR,LOW);
  attachInterrupt(ANEMOMETER_INT,anemometerClick,FALLING);
  attachInterrupt(RAIN_GAUGE_INT,rainGageClick,FALLING);
  interrupts();
}

In order for the anemometer to be accurate, any surrounding objects must be 4 time as far as they are higher than the anemometer.  For example, if my anemometer is 5 feet off the ground, and my house is 25 feet tall, the anemometer would need to be 80 feet from the house to be able to measure the wind speed accurately.  In my case, nothing close to this leeway is possible, but I still setup the anemometer just for the educational experience.

Every rotation of the anemometer causes a call to the interrupt service routine anemometerClick().  Switch debouncing is accomplished by assuming any interrupt that occurs within 500 uS of the previous one is a bounce and should be ignored.  This limits the max speed this configuration can measure to about 2900 miles per hour, but since I don’t live on Jupiter I think I can live with this compromise.  The getUnitWind() function returns the average wind speed since the last poll, which is every 60 seconds.  The getGust function uses the shortest time between 2 interrupts to calculate the fastest wind speed since the last poll.

#define WIND_FACTOR 2.4
#define TEST_PAUSE 60000

volatile unsigned long anem_count=0;
volatile unsigned long anem_last=0;
volatile unsigned long anem_min=0xffffffff;

double getUnitWind()
{
  unsigned long reading=anem_count;
  anem_count=0;
  return (WIND_FACTOR*reading)/(TEST_PAUSE/1000);
}

double getGust()
{

  unsigned long reading=anem_min;
  anem_min=0xffffffff;
  double time=reading/1000000.0;

  return (1/(reading/1000000.0))*WIND_FACTOR;
}

void anemometerClick()
{
  long thisTime=micros()-anem_last;
  anem_last=micros();
  if(thisTime>500)
  {
    anem_count++;
    if(thisTime<anem_min)
    {
      anem_min=thisTime;
    }

  }
}

When the system included the logger shield, SRAM memory was so tight that I had to move variable data from SRAM to FLASH.  Using PROGMEM allowed me to move the vane directions and the expected values out of SRAM, and in itself saved almost 100 bytes of the 2000 the Arduino has (moving String values in addition freed up about 500 bytes of SRAM).  The pgm_read_word function pulls the values out of FLASH and into SRAM when needed, but only works with integers, so the actual wind directions are stored as 10X their value.

As mentioned in the MCP9700 post, the analogReference for the Wind Vane must be switched from the 1.1V the MCP9700 was using to the 5V default value.  Since it takes some time for the ADC to adjust to the new reference, the first 10 adc readings are just thrown out.

To save battery power, the wind vane is powered by the digital pin VANE_PWR right before it is used.  a 100ms delay is inserted after the power pin is driven high just to left things settle down.  The rest of the function compares the ADC value to the ideal values in vaneValues, and returns the corresponding wind direction.


static int vaneValues[] PROGMEM={66,84,92,127,184,244,287,406,461,600,631,702,786,827,889,946};
static int vaneDirections[] PROGMEM={1125,675,900,1575,1350,2025,1800,225,450,2475,2250,3375,0,2925,3150,2700};

double getWindVane()
{
  analogReference(DEFAULT);
  digitalWrite(VANE_PWR,HIGH);
  delay(100);
  for(int n=0;n<10;n++)
  {
    analogRead(VANE_PIN);
  }

  unsigned int reading=analogRead(VANE_PIN);
  digitalWrite(VANE_PWR,LOW);
  unsigned int lastDiff=2048;

  for (int n=0;n<16;n++)
  {
    int diff=reading-pgm_read_word(&vaneValues[n]);
    diff=abs(diff);
    if(diff==0)
       return pgm_read_word(&vaneDirections[n])/10.0;

    if(diff>lastDiff)
    {
      return pgm_read_word(&vaneDirections[n-1])/10.0;
    }

    lastDiff=diff;
 }

  return pgm_read_word(&vaneDirections[15])/10.0;

}

The rain gauge work much like the anemometer in that it drives an interrupt, and a 500us debounce time is used.  The interrupt the simply counts the number of switch contacts that occurred since the last poll and multiplies that by the number of mm of rain each switch contact represents.

#define RAIN_FACTOR 0.2794

volatile unsigned long rain_count=0;
volatile unsigned long rain_last=0;

double getUnitRain()
{

  unsigned long reading=rain_count;
  rain_count=0;
  double unit_rain=reading*RAIN_FACTOR;

  return unit_rain;
}

void rainGageClick()
{
    long thisTime=micros()-rain_last;
    rain_last=micros();
    if(thisTime>500)
    {
      rain_count++;
    }
}

BMP085

The BMP085 is a I2C Barometric Pressure/Temperature sensor available from both Sparkfun and eBay.  The Sparkfun breakout board is very expensive, about $20, but they have excellent instructions on how to use it.  You can get the BMP085 chip on eBay for about $4 and the breakout board for about $6 for 3, but you have to be able to solder SMD to use them.

BMP085 breakout board soldered into my weather station interface board

Sparkfun has an excellent tutorial whose code I pretty much just used verbatim in my application. The only thing I changed were the bmp085Read and bmp085ReadInt functions, since as written, they will retry forever for the bmp085 to respond.  Since my device is outside, and attached to an I2C bus that is about 2.5 M long (for the Max44009 light sensor), sometimes I get a failure in reading the responses from the BMP085.  I just changed the lines that read


  while(!Wire.available())
    ;

To read:


  int n=0;
  for(n=0;n<25;n++)
  {
    if(Wire.available())
      break;

    delay(100);
  }

  if (n==25)
  {
    return 0;
  }

This way if my BMP085 malfunctions, the whole system doesn’t hang.  The other code adjustment was to put in the altitude compensation in the calculations:

#define ALT 142.0

float getPressure()
{
  long pa=bmp085GetPressure(bmp085ReadUP());

  float press=((float)pa/pow((1-ALT/44330),5.255))/100.0;
  return press;
}

Before I put in the compensation for altitude, my pressure was always too low.  Once I compensated for my 142 M altitude, the results from this device are spot on.  I’m very happy with the accuracy of this chip.

The other trick to using this device is the fact that it is a 3.3V device, and you can’t simply connect it up to a 5V I2C Arduino connection and hope for it to have a long life.  This document gives a very detailed discussion on setting up a bi-directional voltage level translator for the I2C bus.  The highlighted part of the schematic below shows the voltage level translator (the transistors are a couple of SN7000 MOSFETs):

Bi-Directional voltage translator for the I2C bus.

RHT22 / RHT03

Over the last year my Garduino project has morphed into more of simply a weather station.  While I still have plans to activate a water valve with the Arduino, my failure in creating a reliable moisture sensor has led me to more or less indirectly guess the soil moisture my measuring the temperature, rain, and humidity.

To measure the temperature and humidity, I’m using the RHT03 (referred to as an RHT22 and DHT-22 as well), available from Sparkfun, and on eBay.

RHT03

RHT03 in breadboard connected to the Saleae Logic Analyzer

Most of my work on the RHT03 is based on the work of Craig Ringer and Nethoncho.   The RHT03 is a bit of an odd device, with kind of a non-standard signalling protocol.  All signalling is done over 1 data line, and the Arduino sets that signal line to an OUTPUT and pulls the line low for about 3ms, and then high for about 30us.  At that point, the Arduino sets the data line pin to an INPUT, and the RHT03 takes control of that pin; pulling the line low for 80us, then high for 80us, and then sending the temperature and humidity in a series of pulses.  High pulses of 26us represent a 0 and 80us represents a 1.  You can try to decipher the whole protocol by reading the datasheet, if you are not too picky about grammar (and if you are reading my blog, you must not be). The following is the code I am using:

#define RHT22_PIN 7
unsigned int temp;
unsigned int humidity;
void setup()
{
 Serial.begin(9600);
 Serial.println("Begin");
}
void loop()
{
 Serial.println("Reading sensor...");

 boolean success = readRHT03();
 if (success) {
   char buf[128];
   sprintf(buf, "Unit 1 Reading: %i.%i degrees C at %i.%i relative humidity", temp/10, abs(temp%10), humidity/10, humidity%10);
   Serial.println(buf);
 }
 delay(2000);
}
boolean readRHT03()
{
 unsigned int rht22_timings[88];
 initRHT03();

 pinMode(6,OUTPUT);
 pinMode(5,OUTPUT);
 digitalWrite(5,LOW);

 pinMode(RHT22_PIN, OUTPUT);
 digitalWrite(RHT22_PIN, LOW);
 delayMicroseconds(3000);

 digitalWrite(RHT22_PIN, HIGH);
 delayMicroseconds(30);
 pinMode(RHT22_PIN, INPUT);
 pinMode(6,OUTPUT);
 pinMode(5,OUTPUT);
 digitalWrite(5,LOW);

 int state=digitalRead(RHT22_PIN);
 unsigned int counter=0;
 unsigned int signalLineChanges=0;
 TCNT1=0;
 digitalWrite(5,HIGH);
 cli();
 while (counter!=0xffff)
 {
   counter++;
   if(state!=digitalRead(RHT22_PIN))
   {
     state=digitalRead(RHT22_PIN);
     digitalWrite(6,state);
     rht22_timings[signalLineChanges] = TCNT1;
     TCNT1=0;
     counter=0;
     signalLineChanges++;
   }
   if(signalLineChanges==83)
   break;
 }
 sei();
 digitalWrite(5,LOW);
 boolean errorFlag=false;
 if (signalLineChanges != 83)
 {
   temp=-1;
   humidity=-1;
   errorFlag=true;
 }
 else
 {
   errorFlag=!(getHumidityAndTemp(rht22_timings));
 }

 return !errorFlag;
}
void initRHT03()
{
 //for (int i = 0; i < 86; i++) { rht22_timings[i] = 0; }

 TCCR1A=0;
 TCCR1B=_BV(CS10);
 pinMode(RHT22_PIN,INPUT);
 digitalWrite(RHT22_PIN,HIGH);

}
// DEBUG routine: dump timings array to serial
void debugPrintTimings(unsigned int rht22_timings[]) { // XXX DEBUG
for (int i = 0; i < 88; i++) { // XXX DEBUG
 if (i%10==0) { Serial.print("\n\t"); }
 char buf[24];
 sprintf(buf, i%2==0 ? "H[%02i]: %-3i " : "L[%02i]: %-3i ", i, rht22_timings[i]);
 Serial.print(buf);
 } // XXX DEBUG
 Serial.print("\n"); // XXX DEBUG
}
boolean getHumidityAndTemp(unsigned int rht22_timings[])
{
  // 25us = 400, 70us = 1120;
  humidity=0;
  for(int i=0;i<32;i+=2)
  {
    if(rht22_timings[i+3]>750)
    {

      humidity|=(1 << (15-(i/2)));
    }
  }
  
  temp=0;
  for(int i=0;i<32;i+=2)
  {

    if(rht22_timings[i+35]>750)
      temp|=(1<<(15-(i/2)));
  }

  int cksum=0;
  for(int i=0;i<16;i+=2)
  {

    if(rht22_timings[i+67]>750)
      cksum|=(1<<(7-(i/2)));
  }

  int cChksum=((humidity >> 8)+(humidity & 0xff) + (temp >> 8) + (temp &0xff)) & 0xFF;  
  
  if(temp & 0x8000)
    temp=(temp & 0x7fff)*-1;
    
  if(cChksum == cksum)
    return true;
  
  return false;
}

Signal handling is done in the readRHT03 function.  After sending the start sending signal, the Arduino uses Timer/Counter 1 to time the incoming pulses.  Originally, I was trying to use micros() to measure the timing, but I got some very erratic results.  This gave me the opportunity to use my new Saleae Logic Analyzer.  As you can see in the code, I have Pin 6 follow the state of the data input from the RHT03.  Normally, there is a 15us delay between the time the RHT03 changes state and the time Pin 6 changes state (the time to execute the if statement and the digitalWrite()), but sometimes it is longer.  The highlighted pulse on Channel 1, though, shows the delay is at least 10us longer.  To make a long story short, this is caused by interrupts in the Arduino, and turning off the interrupts before I start timing the pulses fixes that problem.  Functions like millis() and micros() need interrupts to be update, though, so I could not use them with the interrupts disabled.  This means I had to use the hardware timer/counter to time the pulse length, which is what the references to the TCCR1A, TCCR1B and TCNT1 do.  Additionally, to measure the time the interrupts are disabled, I set Pin 5 (Channel 2) to go high when the interrupts are disabled and low when they are re-enabled, which gave me about 4ms of “interrupt-less” time.  Since my weather station is going to be polled at 60 second intervals, I now know that the timers won’t be running for about 4ms of that time, so I have to set my timers to 59996 to get a 60 second poll.

Anyone using this code should pull out all the references to Pin 5 and 6, unless they want to use them for debugging as well.


Note the short pulse caused by the Arduino handling other interrupts.

The other thing to note is the temperature is pretty inaccurate when the device is in direct sunlight.  My original design had the RHT03 sharing the waterproof container of my MAX44009 light sensor, but even though it is open to the air at the bottom on the container, the temperature inside the container got well above 110°F on bright sunny 90°F+ days.  I’m now extending the cable to the RHT03 and putting it in it’s own container, shaded by the solar cell.  I will update on how well that works.

RHT03 Mount

Mount for the RHT03 to keep it out of the rain and the sun.

 

Sunny Location

The RHT03 is in the container on the left with the blue top. This container also houses the MAX44009 sun sensor.

Shade RGT03

New location of the RHT03, under the black cover.