fhksc.cpp 2.47 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* Copyright (c) 2017 Philippe Kalaf, MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/* Digmesa FHKSC flowmeter driver */
#include "fhksc.h"

FHKSC::FHKSC(PinName pin) : _interrupt(pin) {        // create the InterruptIn on the pin specified to FHKSC
        _interrupt.mode(PullDown); // an internal pull up is used, otherwise disable here
        _interrupt.rise(callback(this, &FHKSC::increment)); // attach increment function of this counter instance  
Philippe Kalaf's avatar
Philippe Kalaf committed
25
        _flow_rate_timer.start(); 
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
        _time_last_increment_us = 0;
}

void FHKSC::increment()
{
    int time_us = _flow_rate_timer.read_us();
    // Every 1925 pulses is 1L
    // Each pulse is 1000000/1925 = 520 ul or 0.52 ml
    _flow_ul += 520;
    _interval_between_increments_us = time_us - _time_last_increment_us;
    _time_last_increment_us = time_us;
}

// return in ml
float FHKSC::read()
{
    return float(_flow_ul)/1000;
}

uint32_t FHKSC::read_ul()
{
    return _flow_ul;
}

void FHKSC::reset_count()
{
    _flow_ul = 0;
Philippe Kalaf's avatar
Philippe Kalaf committed
53 54 55
    // reset timer since it can only run for 30 mins
    _flow_rate_timer.reset();
    _time_last_increment_us = 0;
56 57 58 59 60
}

// flow rate in ml per second
float FHKSC::get_flow_rate()
{
61 62 63 64 65 66 67 68 69 70
    int time_us = _flow_rate_timer.read_us();
    // if we got no incremenet in 2 seconds, flowrate is 0
    if (time_us - _time_last_increment_us > 2000000)
	return 0;

    if (_interval_between_increments_us)
	return float(0.52 / (float(_interval_between_increments_us)/1000000));
    else
	return 0;
}