ICRS Eurobot 2013

Dependencies:   mbed mbed-rtos Servo QEI

Processes/Kalman/Kalman.cpp

Committer:
madcowswe
Date:
2013-04-09
Revision:
20:70d651156779
Parent:
19:4b993a9a156e

File content as of revision 20:70d651156779:

//***************************************************************************************
//Kalman Filter implementation
//***************************************************************************************
#include "Kalman.h"
#include "rtos.h"
#include "math.h"
#include "supportfuncs.h"
#include "Encoder.h"
//#include "globals.h"

#include "tvmet/Matrix.h"
using namespace tvmet;



namespace Kalman
{

Ticker predictticker;

DigitalOut OLED4(LED4);
DigitalOut OLED1(LED1);

//State variables
Matrix<float, 3, 1> X;
Matrix<float, 3, 3> P;
Mutex statelock;

float RawReadings[maxmeasure+1];
float IRpahseOffset;

bool Kalman_inited = 0;

struct measurmentdata {
    measurement_t mtype;
    float value;
    float variance;
};

Mail <measurmentdata, 16> measureMQ;

Thread* predict_thread_ptr = NULL;


//Note: this init function assumes that the robot faces east, theta=0, in the +x direction
void KalmanInit()
{
    printf("kalmaninit \r\n");
    
    //WARNING: HARDCODED!
    
    //solve for our position (assume perfect bias)
    const float d = beaconpos[2].y - beaconpos[1].y;
    const float i = beaconpos[2].y - beaconpos[0].y;
    const float j = beaconpos[2].x - beaconpos[0].x;
    float r1 = RawReadings[SONAR2];
    float r2 = RawReadings[SONAR1];
    float r3 = RawReadings[SONAR0];
    
    printf("ranges: 0: %0.4f, 1: %0.4f, 2: %0.4f \r\n", r1, r2, r3);

    float y_coor = (r1*r1-r2*r2+d*d)/(2*d);
    float x_coor = (r1*r1-r3*r3+i*i+j*j)/(2*j) - (i*y_coor)/j;
    
    //coordinate system hack (for now)
    x_coor = beaconpos[2].x - x_coor;
    y_coor = beaconpos[2].y - y_coor;
    
    printf("solved pos from sonar: %f, %f \r\n", x_coor, y_coor);
    
    //IR
    float IRMeasuresloc[3];
    IRMeasuresloc[0] = RawReadings[IR0];
    IRMeasuresloc[1] = RawReadings[IR1];
    IRMeasuresloc[2] = RawReadings[IR2];
    printf("IR 0: %0.4f, 1: %0.4f, 2: %0.4f \r\n", IRMeasuresloc[0]*180/PI, IRMeasuresloc[1]*180/PI, IRMeasuresloc[2]*180/PI);

    float IR_Offsets[3];
    float fromb0offset = 0;
    for (int i = 0; i < 3; i++) {

        //Compute IR offset
        float angle_est = atan2(beaconpos[i].y - y_coor,beaconpos[i].x - x_coor);

        //printf("Angle %d : %f \n\r",i,angle_est*180/PI );
        IR_Offsets[i] = constrainAngle(IRMeasuresloc[i] - angle_est);

        fromb0offset += constrainAngle(IR_Offsets[i] - IR_Offsets[0]);
    }

    IRpahseOffset = constrainAngle(IR_Offsets[0] + fromb0offset/3);

    //debug
    printf("Offsets IR: %0.4f\r\n",IRpahseOffset*180/PI);

    statelock.lock();
    X(0,0) = x_coor;
    X(1,0) = y_coor;
    X(2,0) = 0;
    statelock.unlock();
    
    Kalman_inited = 1;
}


State getState(){
    statelock.lock();
    State state = {X(0,0), X(1,0), X(2,0)};
    statelock.unlock();
    return state;
}


void predictloop(void const *dummy)
{

    //OLED4 = !ui.regid(0, 3);
    //OLED4 = !ui.regid(1, 4);

    float lastleft = 0;
    float lastright = 0;

    while (1) {
        Thread::signal_wait(0x1);
        OLED1 = !OLED1;

        float leftenc = left_encoder.getTicks() * ENCODER_M_PER_TICK;
        float rightenc = right_encoder.getTicks() * ENCODER_M_PER_TICK;

        float dleft = leftenc-lastleft;
        float dright = rightenc-lastright;

        lastleft = leftenc;
        lastright = rightenc;


        //The below calculation are in body frame (where +x is forward)
        float dxp, dyp,d,r;
        float thetap = (dright - dleft) / ENCODER_WHEELBASE;
        if (abs(thetap) < 0.01f) { //if the rotation through the integration step is small, approximate with a straight line to avoid numerical error
            d = (dright + dleft)/2.0f;
            dxp = d*cos(thetap/2.0f);
            dyp = d*sin(thetap/2.0f);

        } else { //calculate circle arc
            //float r = (right + left) / (4.0f * PI * thetap);
            r = (dright + dleft) / (2.0f*thetap);
            dxp = r*sin(thetap);
            dyp = r - r*cos(thetap);
        }

        statelock.lock();

        float tempX2 = X(2,0);
        //rotating to cartesian frame and updating state
        X(0,0) += dxp * cos(X(2,0)) - dyp * sin(X(2,0));
        X(1,0) += dxp * sin(X(2,0)) + dyp * cos(X(2,0));
        X(2,0) = constrainAngle(X(2,0) + thetap);

        //Linearising F around X
        float avgX2 = (X(2,0) + tempX2)/2.0f;
        Matrix<float, 3, 3> F;
        F = 1, 0, (dxp * -sin(avgX2) - dyp * cos(avgX2)),
        0, 1, (dxp * cos(avgX2) - dyp * sin(avgX2)),
        0, 0, 1;

        //Generating forward and rotational variance
        float varfwd = fwdvarperunit * abs(dright + dleft) / 2.0f;
        float varang = varperang * abs(thetap);
        float varxydt = xyvarpertime * KALMAN_PREDICT_PERIOD;
        float varangdt = angvarpertime * KALMAN_PREDICT_PERIOD;

        //Rotating into cartesian frame
        Matrix<float, 2, 2> Qsub,Qsubrot,Qrot;
        Qsub = varfwd + varxydt, 0,
        0, varxydt;

        Qrot = Rotmatrix(X(2,0));

        Qsubrot = Qrot * Qsub * trans(Qrot);

        //Generate Q
        Matrix<float, 3, 3> Q;//(Qsubrot);
        Q = Qsubrot(0,0), Qsubrot(0,1), 0,
        Qsubrot(1,0), Qsubrot(1,1), 0,
        0, 0, varang + varangdt;

        P = F * P * trans(F) + Q;

        //printf("x: %f, y: %f, t: %f\r\n", X(0,0), X(1,0), X(2,0));
        //Update UI
        //float statecpy[] = {X(0,0), X(1,0), X(2,0)};
        //ui.updateval(0, statecpy, 3);

        //float Pcpy[] = {P(0,0), P(0,1), P(1,0), P(1,1)};
        //ui.updateval(1, Pcpy, 4);

        statelock.unlock();
    }
}


void predict_event_setter(){
    if(predict_thread_ptr)
        predict_thread_ptr->signal_set(0x1);
    else
        OLED4 = 1;
}

void start_predict_ticker(Thread* predict_thread_ptr_in){
    predict_thread_ptr = predict_thread_ptr_in;
    predictticker.attach(predict_event_setter, KALMAN_PREDICT_PERIOD);
}

void runupdate(measurement_t type, float value, float variance)
{
    if (!Kalman_inited) {
        RawReadings[type] = value;
    } else {

        if (type >= IR0 && type <= IR2)
            RawReadings[type] = value - IRpahseOffset;
        else
            RawReadings[type] = value;


        measurmentdata* measured = (measurmentdata*)measureMQ.alloc();
        if (measured) {
            measured->mtype = type;
            measured->value = value;
            measured->variance = variance;

            osStatus putret = measureMQ.put(measured);
            //if (putret)
                //OLED4 = 1;
            //    printf("putting in MQ error code %#x\r\n", putret);
        } else {
            //OLED4 = 1;
            //printf("MQalloc returned NULL ptr\r\n");
        }
    
    }
    

}
/*
void Kalman::updateloop(void const *dummy)
{

    //sonar Y chanels
    ui.regid(2, 1);
    ui.regid(3, 1);
    ui.regid(4, 1);

    //IR Y chanels
    ui.regid(5, 1);
    ui.regid(6, 1);
    ui.regid(7, 1);

    measurement_t type;
    float value,variance,rbx,rby,expecdist,Y;
    float dhdx,dhdy;
    bool aborton2stddev = false;

    Matrix<float, 1, 3> H;

    float S;
    Matrix<float, 3, 3> I3( identity< Matrix<float, 3, 3> >() );


    while (1) {
        OLED2 = !OLED2;

        osEvent evt = measureMQ.get();

        if (evt.status == osEventMail) {

            measurmentdata &measured = *(measurmentdata*)evt.value.p;
            type = measured.mtype; //Note, may support more measurment types than sonar in the future!
            value = measured.value;
            variance = measured.variance;

            // don't forget to free the memory
            measureMQ.free(&measured);

            if (type <= maxmeasure) {

                if (type <= SONAR3) {

                    InitLock.lock();
                    float dist = value / 1000.0f - Sonar_Offset; //converting to m from mm,subtract the offset
                    InitLock.unlock();

                    int sonarid = type;
                    aborton2stddev = true;

                    statelock.lock();
                    //update the current sonar readings
                    SonarMeasures[sonarid] = dist;

                    rbx = X(0) - beaconpos[sonarid].x/1000.0f;
                    rby = X(1) - beaconpos[sonarid].y/1000.0f;

                    expecdist = hypot(rbx, rby);//sqrt(rbx*rbx + rby*rby);
                    Y = dist - expecdist;

                    //send to ui
                    ui.updateval(sonarid+2, Y);

                    dhdx = rbx / expecdist;
                    dhdy = rby / expecdist;

                    H = dhdx, dhdy, 0;

                } else if (type <= IR3) {

                    aborton2stddev = false;
                    int IRidx = type-3;

                    // subtract the IR offset
                    InitLock.lock();
                    value -= IR_Offset;
                    InitLock.unlock();

                    statelock.lock();
                    IRMeasures[IRidx] = value;

                    rbx = X(0) - beaconpos[IRidx].x/1000.0f;
                    rby = X(1) - beaconpos[IRidx].y/1000.0f;

                    float expecang = atan2(-rby, -rbx) - X(2);
                    Y = rectifyAng(value - expecang);

                    //send to ui
                    ui.updateval(IRidx + 5, Y);

                    float dstsq = rbx*rbx + rby*rby;
                    H = -rby/dstsq, rbx/dstsq, -1;
                }

                Matrix<float, 3, 1> PH (P * trans(H));
                S = (H * PH)(0,0) + variance;

                if (aborton2stddev && Y*Y > 4 * S) {
                    statelock.unlock();
                    continue;
                }

                Matrix<float, 3, 1> K (PH * (1/S));

                //Updating state
                X += col(K, 0) * Y;
                X(2) = rectifyAng(X(2));

                P = (I3 - K * H) * P;

                statelock.unlock();

            }

        } else {
            OLED4 = 1;
            //printf("ERROR: in updateloop, code %#x", evt);
        }

    }

}

*/

} //Kalman Namespace