Thursday, March 28, 2013

Arduino capacitance measurement

I`m in the need to measure my plants soil moisture. I've read a lot about the possible options to measure soil moisture like sensing resistance or capacitance. Using the resistance measurement, the probes are sensitive to corrosion due electrolyse so I want to give it a go to measure the capacitance and see what happens.

Here is what I did for the hardware part on my Arduino nano:



This is the sketch I used

#include

// analog defines
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

void setup() {
  Serial.begin(9600);
  Serial.println("StartUp\n");

  // analog init
    analogReference(INTERNAL);
  // set prescale to 16
  sbi(ADCSRA,ADPS2) ;
  cbi(ADCSRA,ADPS1) ;
  cbi(ADCSRA,ADPS0) ;
    
  Serial.println("Init OK \n");
}

void capMeasurement(void)
{
  uint16_t sensorValue = 0;  // variable to store the value coming from the sensor
  static uint16_t sensorHistory;
  sensorValue = 0;
  
  for(int count = 16; count != 0; count--)
  {
    // note that default Wire.h was to slow to use, so these are direct MCU commands.
    // should make a Arduino library from it.

    //pinMode(A0, OUTPUT);
    //pinMode(A1, OUTPUT);
    // the above commented text is done with direct MCU register commands (faster)
    DDRC = DDRC | ~B11111100; // make A0/A1 output
    
    //digitalWrite(A0, HIGH);
    //digitalWrite(A1, HIGH);
    // the above commented text is done with direct MCU register commands (faster)
    PORTC = PORTC | B00000011; //charge external Cx
    delayMicroseconds(10); // let the Cx charge 10uS
    
    //pinMode(A1, INPUT); 
    DDRC = DDRC & B11111101; // make A1 input
    
    //digitalWrite(A0, LOW);
    PORTC = PORTC & B11111100; // transfer charge to C1 (by grounding C1)
    
    // read the value from the sensor:
    sensorValue += analogRead(A1); 
  }
  PORTC = PORTC | ~B11111100; // done 
  Serial.print(" cap=");
  Serial.print(sensorValue);
}

void loop() {
  capMeasurement();
  Serial.println();
}










No comments:

Post a Comment