Voltage Monitor Class widh LED Alert

Dependents:   KIK01

VoltageMonitor.h

Committer:
ryood
Date:
2017-11-26
Revision:
1:ada48e929184
Parent:
0:bf80e6084873
Child:
2:ee0c146f02e6

File content as of revision 1:ada48e929184:

/*
 * Voltage Monitor Class
 *
 * 2017.11.26
 *
 */

#ifndef _VOLTAGE_MONIOR_H_
#define _VOLTAGE_MONIOR_H_

#include "mbed.h"

class VoltageMonitor
{
public:
    enum {
        VM_NORMAL = 0,
        VM_UNDER = -1,
        VM_OVER = 1
    };
    
    //---------------------------------------------------------------------
    // パラメータ
    // _ain: 電圧監視用ADC
    // _vdd: VDDの電圧値(実測値を指定)
    // _loThreshold: 電圧低下閾値
    // _hiThreshold: 過電圧閾値
    // _pLed: 警告用LED (NULL: LEDを使用しない)
    VoltageMonitor(AnalogIn* _pAin, float _vdd, float _loThreshold, float _hiThreshold, DigitalOut* _pLed=NULL) :
        pAin(_pAin),
        vdd(_vdd),
        loThreshold(_loThreshold),
        hiThreshold(_hiThreshold),
        pLed(_pLed),
        status(VM_NORMAL)
    {
        if (pLed != NULL) {
            *pLed = 1;
        }
    };
    
    ~VoltageMonitor() {};

    //---------------------------------------------------------------------
    // 返り値
    // -1: 電圧低下
    //  0: 正常
    //  1: 過電圧
    int check()
    {
        float vMeas = pAin->read() * vdd;
    
        int st;
        if      (vMeas < loThreshold)   st = VM_UNDER;
        else if (vMeas > hiThreshold)   st = VM_OVER;
        else                            st = VM_NORMAL;
        
#if UART_TRACE
        printf("VoltageMonitor:\t%.3fV\t %d\r\n", vMeas, st);
#endif

        if (st != status) {
            status = st;
            if (pLed != NULL) {
                switch (status) {
                case VM_UNDER:
                    t.attach(this, &VoltageMonitor::blinkLed, 0.5);
                    break;
                case VM_OVER:
                    t.attach(this, &VoltageMonitor::blinkLed, 0.1);
                    break;
                case VM_NORMAL:
                    t.detach();
                    *pLed = 1;
                }
            }
        }
        
        return status;
    };
    
private:
    AnalogIn* pAin;
    float vdd;
    float loThreshold;
    float hiThreshold;
    DigitalOut* pLed;
    Ticker t;
    int status;
    
    void blinkLed() {
        if (pLed != NULL) {
            *pLed = !*pLed;
        }
    };
};

#endif //_VOLTAGE_MONIOR_H_