Measure capacitances by counting rising edges of a 555 astable oscillator.

Dependencies:   4DGL-uLCD-SE mbed

capSense.h

Committer:
jford38
Date:
2014-03-24
Revision:
0:292d0c987fe3

File content as of revision 0:292d0c987fe3:

#ifndef CAP_SENSE_H
#define CAP_SENSE_H

#include "mbed.h"

class CapSense {
    
    public:
        int _Ra;
        int _Rb;
        int _Period;
        
        CapSense(int, int, int, PinName);
        ~CapSense();
        float measure();
    
    //private:
        volatile int _count;
        volatile float _partial;  
        float _coeff; 
        
        void atInterrupt(); 
    
        Timer _t;
        InterruptIn* _event;
};

Serial pc(USBTX, USBRX);

CapSense::CapSense(int Ra, int Rb, int Period, PinName pIn) {
    _Ra = Ra;
    _Rb = Rb;
    _Period = Period;
    _event = new InterruptIn(pIn);
    
    _coeff = (_Ra*_Rb)/(float)(_Ra+_Rb) * log( (float)(_Rb-2*_Ra)/(2*_Rb-_Ra) );
}

CapSense::~CapSense() {
    delete _event;    
}

void CapSense::atInterrupt(void) {
    static float lastTime = 1;
    float time = _t.read_us();
    _t.stop();
    _t.reset();
    _partial = (time < lastTime) ? time/lastTime : 1;
    _count++;
    lastTime = time;
    _t.start();
}

float CapSense::measure() {
    _event->rise(this, &CapSense::atInterrupt);
    
    _count = 0;
    _partial = 0;
    wait_us(_Period);
    float read = _count + _partial; 
    
    _event->rise(NULL);
    _t.stop();
    return (float)_Period / ((.693*_Ra + _coeff) * read); 
}

#endif