Output the angle data of Encoder

Dependencies:   AD5754 FatFileSystem Impact_nagano_0630 MSCFileSystem QEI mbed

main.cpp

Committer:
chinacaonan
Date:
2016-10-11
Revision:
2:8b24c7cfc9b2
Parent:
1:f37787740470

File content as of revision 2:8b24c7cfc9b2:

#include "mbed.h"
#include "QEI.h" // for encoder
#include "MSCFileSystem.h"
#include "AD5754.h" // for DA converter


#define ENCODER_PERIOD_US 1000 // 1kHz
//#define ENCODER_PERIOD_US 100000 // 10Hz


//// State in main phase ////
#define INITIALISATION_STATE 0
#define RECORD_PERIOD 1.0
#define AVE_WINDOW 10
#define VEL_WINDOW 10


Serial pc(USBTX, USBRX);
QEI encoder(p21, p22, NC, 2000);  // encoder
AD5754 dac(p5, NC, p7, p8); // spi_(mosi, miso, sck), nCS_(cs)


Ticker encoder_t;
Timer t;

volatile bool encoder_flag = false;
void encoder_interrupt()
{
    encoder_flag = true;
}


int main() 
{    
    pc.baud(115200);  
    encoder_t.attach_us(&encoder_interrupt, ENCODER_PERIOD_US);

    bool start_flag = true;
    bool main_flag = false;

    //// Encoder ////
    int encoder_cnt = 0;
    int encoder_buf[AVE_WINDOW] = {};
    int encoder_ave = 0;

    //// Option ////
    int print_cnt = 0;
        
    pc.printf("'S' key: Start state\n\n");
    wait(1);
    
    dac.rangeSelect();
    dac.setPowerControl();
    
    while(start_flag)
    {
        if(pc.readable())
        {
            if(pc.getc() == 's')
            {
                start_flag = false;
                pc.printf("\nHAPTIC test start\n");            
                wait(0.5);
                pc.printf("Start initialization\nLift device\n\n");
                wait(0.5);
                main_flag = true;
            }
        }
    }
    
    t.start();

    while(main_flag)
    {
        if(encoder_flag)
        {    
            encoder_flag = false;
            encoder_cnt = encoder.getPulses();  // One of the encoders needs a sign change
            
            encoder_ave = encoder_cnt;
            for(int i=0; i<AVE_WINDOW-1; i++)
            {
                encoder_buf[i+1] = encoder_buf[i];
                encoder_ave += encoder_buf[i];
            }
            encoder_buf[0] = encoder_cnt;
            encoder_ave = encoder_ave/AVE_WINDOW;
    
            if(print_cnt > 1000000/ENCODER_PERIOD_US)
            {
                printf("encoder = %d\n", encoder_ave);
                printf("time = %f\n", t.read());
                print_cnt = 0;
            }
            print_cnt++;      
        }              
    }

}