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++;
    }
}
Advertisements

MCP9700

Soil temperature is one of the things the Garduino monitors.  Unfortunately, soil is a harsh environment and replacing a $1.50 TMP36 everything time one stopped working was becoming a bit of a drag, so I looked for something cheaper.  The MCP9700 is a temperature sensor available from Mouser.com for $0.34, and at that price, I feel a little more free to experiment with waterproofing these sensors.

These devices are pretty nice to work with, since they can take a supply voltage of 2.1 to 5.5V and the output pin will be at .5V at 0° C and rise 0.01V for every rise in 1°C.  This document  describes how to compensate for 2nd order effects to increase accuracy further.

It is critical to put a capacitor between the Vout pin in ground (about 2nF), because without it, there is a 27kHz wave that appears on the output.  In my tests, Vout oscillated 0.0575 Volt P-P, which represents a variation of 5.75 °C from reading to reading.  With the capacitor between Vout and GND, the variation between readings drops to about 0.5°C.

The code for reading the temperature of these devices is pretty straightforward:

float readMCP9700(int pin,float offset)
{
  analogReference(INTERNAL);
  for (int n=0;n<5;n++)
    analogRead(pin);

  int adc=analogRead(pin);
  float tSensor=((adc*(1.1/1024.0))-0.5+offset)*100;
  float error=244e-6*(125-tSensor)*(tSensor - -40.0) + 2E-12*(tSensor - -40.0)-2.0;
  float temp=tSensor-error;

  return temp;
}

In my application, I have some ADC calls done against the 5V analogReference, and the analogReads for the MCP9700 are done against the internal 1.1V reference.  According to the ATMega328 datasheet, when switching between references, you should throw out the reading immediately after the switch, because it will be inaccurate.  In this function, I throw out  5 readings after setting the analogReference, just to give it extra time to settle down, and then I take the real measurement.  The 2nd order error is calculated as described in the accuracy compensation document mentioned above.

I also pass in an offset to allow me to adjust each individual sensor against a know temperature.  In my case, I really didn’t have a know temperature reading I thought was any more accurate than anything else I had, so I setup 4 MCP9700s and let them read the same temperature.  I averaged these readings, and I pass in the offset for each individual MCP9700 from that average, so, if nothing else, the temperatures read between these 4 devices will be consistent.  The offsets were on the order of 0.01V.

MAX44009

One of the questions I wanted to answer with my Garduino was how much light is lost through the plastic covering of the Greenhouse.  What I have found is it is very difficult to find a light sensor that has the dynamic range from darkness to full sun, but I finally stumbled on the MAX44009, which has a range from 0.045 to 180,000 Lux.  The downside of this device is no one is making a breakout board for it, so I was on my own.

Homemade breakout board for the MAX44009

Yes, this beautiful homemade PCB does work.  I made it by the laser toner transfer method, but my home printer, a Brother HL-4040CN did not work; the toner did not stick to the copper board no matter how long I put the iron on it.  I ended up creating a PDF file with Gerber2PDF and printing the image on some HP printers at work.  Unfortunately,  in my rush to not be caught screwing around with something that wasn’t work related, I forgot to make a mirror image of the PCB, so everything is backwards on the PCB.  Even with the HP toner, the toner transfer was not very good, but, considering the fact that the MAX44009 chip is 2mm x 2mm and the pads for the 6 pins are 0.36mm x 0.48 mm, the toner transfer was accurate enough to work.  Adding to the fact that this was the first time I used my hot air re-work station to do something constructive, you could have knocked me off my chair with a feather when the final assembly actually returned valid data.

It wasn’t a complete Eureka moment, though, because while the data sheet says the I2C address can be selected (with the AD pin) to be 148 or 150, that does not seem to be true.  I found this important utility, I2CScanner which runs through every I2C address, and shows which addresses a device is responding to.  This really saved me, because it showed that the real address of the MAX44009 was 203 (I forgot to note the address when AD is low, so I’ll document that when I make the improved version of the PCB).  Once I had the right address, interfacing with the MAX44009 is very straightforward, since it uses the I2C Wire Arduino  library:

#define MAX_ADDR 203

float getLux()
{
int luxHigh=readI2CAddr(0x03);
int luxLow=readI2CAddr(0x04);
int exponent=(luxHigh&0xf0)>>4;
int mant=(luxHigh&0x0f)<<4|luxLow;
return (float)(pow(2,exponent)*mant)*0.045;

}

int readI2CAddr(int addr)
{

Wire.beginTransmission(MAX_ADDR);
Wire.write(addr);
Wire.endTransmission();

Wire.requestFrom(MAX_ADDR,1);

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

delay(100);
}

if (n==25)
return 0;
else
return Wire.read();
}

I was expecting to have to handled the situation where I would have to programatically change the sensitivity of the device so that I would have to set longer integration times in low light conditions, and shorter ones in bright conditions, but the device handles that all by itself.  The device can be configured in a manual mode so that the user has control of exactly what integration time will be used for each reading, but in my case, the automatic setting behaved the way I wished.

I’ve created an Eagle library that contains the land pattern for the MAX44009.

I really like the I2C bus, but its major disadvantage is the max length which is reportedly pretty short.  I currently have the MAX44009 sitting off of about 2.5 M of 6 conductor satin cable, connected to the same 3.3V bi-directional voltage translator circuit my BMP085 is connected to, and it is working well.  I expect when I have to connect another MAX44009 to measure the light loss from inside the Greenhouse, though, the length will become a problem.  I will be researching some I2C bus lengthing techniques and will report on them in the future.

The waterproof enclosure for the MAX44009 consists of a plastic food container with a clear plastic cover, and the bottom cut out for ventilation.

 

This is the PDF for the Break Out Board that I used for the Toner Transfer method to create the PCB.

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.