Drain batteries through an LM324 controlled CEB6030L from a defunct graphics card

Dependencies:   mbed FastAnalogIn PID mbed-rtos

main.cpp

Committer:
eisd
Date:
2016-07-05
Revision:
3:08488e544b3e
Parent:
2:e7ce63ada1d2
Child:
4:fb20b0b3f57d

File content as of revision 3:08488e544b3e:

#include "mbed.h"
#include "rtos.h"
#include "FastAnalogIn.h"
#include "PID.h"

PID I(10.0, 0.01, 0.0, 0.01);

AnalogOut Iset(PTE30);
FastAnalogIn Iget(PTE20);
AnalogIn Vbat(PTB0);
bool active = true;

class Lag {
    float k, v;
public:
    Lag(float seed, float factor = 0.005) { v = seed; k = factor; }
    float operator()(float in) { return v = k * in + (1 - k) * v; }
    operator float() { return v; }
};
inline float Iin(float x) { return x * 32.9697 + 1/60.0; }
inline float Vin(float x) { return x * 34.08516 + 0.06567447; }

Lag iget(Iin(Iget.read())), vbat(Vin(Vbat.read())), vbat_rest(Vin(Vbat.read()));
void filter() {
    if (active) {
        iget(Iin(Iget.read()));
        vbat(Vin(Vbat.read()));
    }
    if (Iset.read() == 0)
        vbat_rest(Vin(Vbat.read()));
}
void rest(const void *) {
    while (true) {
        Thread::wait(5000);
        if (Iset.read() > 0) {
            active = false;
            Iset.write_u16(16);
            Thread::wait(400);
            Iset.write_u16(0);
            Thread::wait(100);
            active = true;
        }
    }
}
int flop = 0;
void adjust() {
    //flop = (flop + 1) % 4;
    //Iset.write(flop == 0? 0.2/4.61 : 0);
    if (active) {
        I.setProcessValue(iget);
        Iset = I.compute();
    }
}

Serial pc(USBTX, USBRX);
void ui(const void*) {
    while (true) {
        Thread::wait(100);
        while (pc.readable()) {
            pc.getc();
            I = I + 0.1;
        }
    }
}

int main()
{
    pc.baud(115200);

    I.setInputLimits(0, 100);
    I.setOutputLimits(0, 1);
    I = 0;
    I.setMode(AUTO_MODE);

    Ticker t2;
    t2.attach_us(&filter, 1000);
    Ticker t;
    t.attach(&adjust, I.getInterval());
    Thread t3(&rest);
    Thread t4(&ui);

    while (true) {
        //pc.printf("Iset %f    Iget %6d %f    Vbat %6d %f    \r", Iset.read(), Iget.read_u16(), Iget.read(), Vbat.read_u16(), Vbat.read());
        pc.printf("Iset %f      Iget %8d %f %f", Iset.read(), Iget.read_u16(), Iin(Iget.read()), (float)iget);
        pc.printf("      Vbat %8d %f %f %f\r", Vbat.read_u16(), Vin(Vbat.read()), (float)vbat, (float)vbat_rest);
        Thread::wait(500);
    }
}