albatross / Mbed 2 deprecated keiki2018

Dependencies:   BufferedSoftSerial2 INA226_ver1 mbed-rtos mbed SDFileSystem-RTOS

Fork of keiki2017 by albatross

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 //計器プログラム
00002 #include "mbed.h"
00003 #include "rtos.h"
00004 #include "Cadence.h"
00005 #include "Fusokukei.h"
00006 #include "MPU6050.h"
00007 #include "BufferedSoftSerial.h"
00008 #include "SDFileSystem.h"//2014.6/5以前の環境で動作します。アップデートすると動きません。
00009 #include "INA226.hpp"
00010 
00011 #define SOUDA_DATAS_NUM 28 //(yokutan 7 + input 7)*2
00012 #define YOKUTAN_DATAS_NUM 14
00013 #define WRITE_DATAS_NUM 34 // souda_datas_num + 6( rpy, airspeed, height, cadence)
00014 #define SD_WRITE_NUM 20
00015 #define MPU_LOOP_TIME 0.01
00016 #define AIR_LOOP_TIME 0.01//(0.002005)
00017 #define WRITE_DATAS_LOOP_TIME 1
00018 #define ROLL_R_MAX_DEG 1.5
00019 #define ROLL_L_MAX_DEG 1.5
00020 #define MPU_DELT_MIN 250
00021 #define INIT_SERVO_PERIOD_MS 20
00022 
00023 #define debug // pc.printf
00024 
00025 //-----------------------------------(resetInterrupt def)
00026 //extern "C" void mbed_reset();
00027 //InterruptIn resetPin(p25);
00028 //Timer resetTimeCount;
00029 //void resetInterrupt()
00030 //{
00031 //    while(resetPin) {
00032 //        resetTimeCount.start();
00033 //        if(resetTimeCount.read()>3) mbed_reset();
00034 //    }
00035 //    resetTimeCount.reset();
00036 //}
00037 //-------------------------------------------------------
00038 
00039 //SDFileSystem sd(p5, p6, p7, p8, "sd");
00040 LocalFileSystem local("local");
00041 FILE* fp;
00042 
00043 //RawSerial pc(USBTX,USBRX);
00044 //Serial android(p9,p10);
00045 BufferedSoftSerial soudaSerial(p17,p18);
00046 BufferedSoftSerial twe(p11,p12);
00047 //Cadence cadence_twe(p13,p14);
00048 RawSerial android(p13,p14);
00049 
00050 Ticker cadenceUpdateTicker;
00051 //Ticker writeDatasTicker;
00052 //Timer writeTimer;
00053 
00054 InterruptIn FusokukeiPin(p24);
00055 Ticker FusokukeiTicker;
00056 Fusokukei air;
00057 volatile int air_kaitensu= 0;
00058 
00059 //Timer sonarTimer;
00060 AnalogIn sonarPin(p15);
00061 double sonarDist;
00062 float sonarV;
00063 
00064 
00065 float sum = 0;
00066 uint32_t sumCount = 0;
00067 MPU6050 mpu6050;
00068 Timer t;
00069 Timer cadenceTimer;
00070 
00071 //Ticker mpu6050Ticker;
00072 
00073 DigitalOut RollAlarmR(p23);
00074 DigitalOut RollAlarmL(p22);
00075 DigitalOut led2(LED2);
00076 //DigitalOut led3(LED3);
00077 DigitalOut led4(LED4);
00078 I2C InaI2c(p9,p10);
00079 INA226 VCmonitor(InaI2c,0x9C);
00080 AnalogIn mgPin(p20);
00081 AnalogIn mgPin2(p16);
00082 
00083 char soudaDatas[SOUDA_DATAS_NUM];
00084 float writeDatas[SD_WRITE_NUM][WRITE_DATAS_NUM];
00085 volatile int write_datas_index = 0;
00086 float inputR,inputL;
00087 int drugR,drugL;
00088 
00089 void air_countUp();
00090 void call_calcAirSpeed();
00091 void sonarInterruptStart();
00092 void sonarInterruptStop();
00093 void updateCadence(double source, double input,double input2,bool isFFlag);
00094 void init();
00095 void FusokukeiInit();
00096 void MpuInit();
00097 void mpuProcessing(void const *arg);
00098 void DataReceiveFromSouda(void const *arg);
00099 void SdInit();
00100 void SDprintf();
00101 void WriteDatas();
00102 float calcAttackAngle();
00103 float calcKXdeg(float x);
00104 int lastCadenceInput = 0;           //1つ前のケイデンスのパルス値を取得します。これの取りうる値は0か1です。
00105 int lastCadenceInput2 = 0;           //1つ前のケイデンスのパルス値を取得します。これの取りうる値は0か1です。
00106 double cadenceResult = 0.0;         //最終的なケイデンスの値です。
00107 int cadenceCounter = 0;             //クランクが一回転すると、二つのセンサがそれぞれ2回ずつ状態が変化するため、0~4をカウントするためのカウンタです。
00108 double V;
00109 
00110 void air_countUp()
00111 {
00112     air_kaitensu++;
00113 //    led3 = !led3;
00114 }
00115 
00116 void call_calcAirSpeed()
00117 {
00118     air.calcAirSpeed(air_kaitensu);
00119     air_kaitensu = 0;
00120 }
00121 
00122 void sonarInterruptStart()
00123 {
00124 //    sonarTimer.start();
00125 }
00126 
00127 void sonarInterruptStop()
00128 {
00129 //    sonarTimer.stop();
00130 //    sonarDistTime = sonarTimer.read_us();
00131 //    sonarTimer.reset();
00132 //    sonarDist = sonarDistTime*0.018624 - 13.511;
00133 }
00134 void sonarCalc()
00135 {
00136     sonarV = 0;
00137     for(int i = 0; i<20; i++) {
00138         sonarV += sonarPin.read();
00139         wait(0.01);
00140     }
00141     sonarDist = (sonarV/20)*2064.5;// volt*3.3*1000/1.6 (電圧/距離:3.2mV/2cm)
00142 }
00143 
00144 
00145 // 定格12V電源の電圧値から定めた閾値を、oh182/E非接触回転速度センサ値が超えているかどうか
00146 // source: 定格12V電源の電圧値[mV], input: センサ値[mV]
00147 // return => 1:超えている, 0:超えていない, -1:エラー
00148 int isOh182eOverThreshold(double source, double input)
00149 {
00150     double a, b;
00151     if(source < 3200)
00152         return -1;
00153 
00154     if(source < 5500)
00155         a = 0.233333333, b = -308.3333333;
00156     else if(source < 7000)
00157         a = 0.173333333, b = 21.66666667;
00158     else
00159         a = 0, b = 1235;
00160 
00161     return (a * source + b < input) ? 1 : 0;
00162 }
00163 
00164 //ケイデンスの値を取得します。
00165 // source: 定格12V電源の電圧値[mV], input: センサ値[mV]
00166 void updateCadence(double source, double input,double input2)
00167 {
00168 
00169     static bool isFFlag = true;
00170     if(isFFlag) {
00171         lastCadenceInput =  isOh182eOverThreshold(source,input);
00172         lastCadenceInput2 =  isOh182eOverThreshold(source,input2);
00173         cadenceTimer.start();
00174         isFFlag = false;
00175         return;
00176     }
00177     if((isOh182eOverThreshold(source,input) != lastCadenceInput) ||(isOh182eOverThreshold(source,input2) != lastCadenceInput2)) {
00178         if(cadenceCounter < 3) {
00179             cadenceCounter++;
00180             led3 = !led3;
00181             lastCadenceInput =  isOh182eOverThreshold(source,input);
00182             lastCadenceInput2 =  isOh182eOverThreshold(source,input2);
00183             return;
00184         }
00185         cadenceResult =60.0/  (cadenceTimer.read_us() / 1000000.0); //クランク一回転にかかる時間を取得
00186         cadenceTimer.reset();
00187         cadenceCounter = 0;
00188     }
00189     lastCadenceInput =  isOh182eOverThreshold(source,input);
00190     lastCadenceInput2 =  isOh182eOverThreshold(source,input2);
00191 }
00192 
00193 void init()
00194 {
00195     pc.printf("(BUILD:[" __DATE__ "/" __TIME__ "])\n\r");
00196 //--------------------------------------(resetInterrupt init)
00197    // resetPin.rise(resetInterrupt);
00198    // resetPin.mode(PullDown);
00199 //-----------------------------------------------------------
00200     twe.baud(14400);//BufferedSoftSerialでは19200が上限。twelite側でもBPS無効化が必要
00201     android.baud(9600);
00202     //writeTimer.start();
00203     FusokukeiInit();
00204 //    SdInit();
00205 //    MpuInit();
00206     //writeDatasTicker.attach(&WriteDatas,1);
00207 
00208 //-----for InterruptMode of sonar----------------------------
00209 //    sonarPin.rise(&sonarInterruptStart);
00210 //    sonarPin.fall(&sonarInterruptStop);
00211 //-----------------------------------------------------------
00212     unsigned short val;
00213     val = 0;
00214     if(VCmonitor.rawRead(0x00,&val) != 0) {
00215         printf("VCmonitor READ ERROR\n");
00216     //    while(1) {}
00217     }
00218     VCmonitor.setCurrentCalibration();
00219 }
00220 
00221 void FusokukeiInit()
00222 {
00223     FusokukeiPin.rise(air_countUp);
00224     FusokukeiTicker.attach(&call_calcAirSpeed, AIR_LOOP_TIME);
00225 }
00226 
00227 void MpuInit()
00228 {
00229     i2c.frequency(400000);  // use fast (400 kHz) I2C
00230     t.start();
00231     uint8_t whoami = mpu6050.readByte(MPU6050_ADDRESS, WHO_AM_I_MPU6050);  // Read WHO_AM_I register for MPU-6050
00232     if (whoami == 0x68) { // WHO_AM_I should always be 0x68
00233         Thread::wait(100);
00234         mpu6050.MPU6050SelfTest(SelfTest); // Start by performing self test and reporting values
00235         Thread::wait(100);
00236         if(SelfTest[0] < 1.0f && SelfTest[1] < 1.0f && SelfTest[2] < 1.0f && SelfTest[3] < 1.0f && SelfTest[4] < 1.0f && SelfTest[5] < 1.0f) {
00237             mpu6050.resetMPU6050(); // Reset registers to default in preparation for device calibration
00238             mpu6050.calibrateMPU6050(gyroBias, accelBias); // Calibrate gyro and accelerometers, load biases in bias registers
00239             mpu6050.initMPU6050(); ////////////pc.printf("MPU6050 initialized for active data mode....\n\r"); // Initialize device for active mode read of acclerometer, gyroscope, and temperature
00240             Thread::wait(200);
00241         } else {
00242         }
00243     } else {
00244         //////pc.printf("out\n\r"); // Loop forever if communication doesn't happen
00245     }
00246 }
00247 
00248 double calcPulse(int deg)
00249 {
00250     return (0.0006+(deg/180.0)*(0.00235-0.00045));
00251 }
00252 
00253 void mpuProcessing(void const *arg)
00254 {
00255     MpuInit();
00256     while(1) {
00257         if(mpu6050.readByte(MPU6050_ADDRESS, INT_STATUS) & 0x01) {  // check if data ready interrupt
00258             mpu6050.readAccelData(accelCount);  // Read the x/y/z adc values
00259             mpu6050.getAres();
00260             ax = (float)accelCount[0]*aRes - accelBias[0];  // get actual g value, this depends on scale being set
00261             ay = (float)accelCount[1]*aRes - accelBias[1];
00262             az = (float)accelCount[2]*aRes - accelBias[2];
00263             mpu6050.readGyroData(gyroCount);  // Read the x/y/z adc values
00264             mpu6050.getGres();
00265             gx = (float)gyroCount[0]*gRes; // - gyroBias[0];  // get actual gyro value, this depends on scale being set
00266             gy = (float)gyroCount[1]*gRes; // - gyroBias[1];
00267             gz = (float)gyroCount[2]*gRes; // - gyroBias[2];
00268             tempCount = mpu6050.readTempData();  // Read the x/y/z adc values
00269             temperature = (tempCount) / 340. + 36.53; // Temperature in degrees Centigrade
00270         }
00271         Now = t.read_us();
00272         deltat = (float)((Now - lastUpdate)/1000000.0f) ; // set integration time by time elapsed since last filter update
00273         lastUpdate = Now;
00274         sum += deltat;
00275         sumCount++;
00276         if(lastUpdate - firstUpdate > 10000000.0f) {
00277             beta = 0.04;  // decrease filter gain after stabilized
00278             zeta = 0.015; // increasey bias drift gain after stabilized
00279         }
00280         mpu6050.MadgwickQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f);
00281         delt_t = t.read_ms() - count;
00282         if (delt_t > MPU_DELT_MIN) {
00283             yaw   = atan2(2.0f * (q[1] * q[2] + q[0] * q[3]), q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]);
00284             pitch = -asin(2.0f * (q[1] * q[3] - q[0] * q[2]));
00285             roll  = atan2(2.0f * (q[0] * q[1] + q[2] * q[3]), q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3]);
00286             pitch *= 180.0f / PI;
00287             yaw   *= 180.0f / PI;
00288             roll  *= 180.0f / PI;
00289             myled= !myled;
00290             count = t.read_ms();
00291             sum = 0;
00292             sumCount = 0;
00293         }
00294         Thread::wait(1);
00295     }//while(1)
00296 }
00297 
00298 void DataReceiveFromSouda(/*void const *arg*/)
00299 {
00300     char cErebonR[6] = {};
00301     char cErebonL[6] = {};
00302 //    while(1){
00303     if(soudaSerial.readable()) {
00304         led2 = !led2;
00305         char c = soudaSerial.getc();
00306         while( c != ';' ) {
00307             c = soudaSerial.getc();
00308         }
00309         for(int i = 0; i < SOUDA_DATAS_NUM; i++) {
00310             soudaDatas[i] = soudaSerial.getc();
00311 //            pc.printf("%d,",(int)(soudaDatas[i] - '0'));
00312         }
00313        // pc.printf("\n\r");
00314      //   sscanf(soudaDatas+YOKUTAN_DATAS_NUM,"%5.2f,%d,%5.2,%d",&inputR,&drugR,&inputL,&drugL);
00315         for(int i = 14; i < 19; i++) {
00316             cErebonR[i-14] = soudaDatas[i];
00317         }
00318         drugR = soudaDatas[19]- '0';
00319         inputR = atof(cErebonR);
00320         for(int i = 21; i < 26; i++) {
00321             cErebonL[i-21] = soudaDatas[i];
00322         }
00323         drugL = soudaDatas[26]- '0';
00324         inputL = atof(cErebonL);
00325         
00326         debug("erebonR:%5.5f,   drugR:%d     erebonL:%5.5f   drugL:%d",inputR,drugR,inputL,drugL);
00327 //        pc.printf("erebonR:%s,   drugR:%d     erebonL:%s   drugL:%d",cErebonR,drugR,cErebonL,drugL);
00328     }//if
00329 //    }//while(1)
00330 }
00331 
00332 void SdInit()
00333 {
00334 //    mkdir("/local/mydir", 0777);
00335     fp = fopen("/local/filetest.csv", "w");
00336     if(fp == NULL) {
00337         printf("Could not open file for write\n");
00338         return;
00339     }
00340     fprintf(fp, "Hello fun SD Card World!\n\r%f",0.1f);
00341     fclose(fp);
00342 }
00343 
00344 void SDprintf(const void* arg)
00345 {
00346     SdInit();
00347     while(1) {
00348         updateCadence(V,mgPin.read() * 3300.0,mgPin2.read() * 3300.0);
00349         //  pc.printf("V:%5.5f  mgPin:%5.5f     mgPin2:%5.5f",V,mgPin.read() * 3300.0,mgPin2.read() * 3300.0);
00350         if(write_datas_index == SD_WRITE_NUM-1) {
00351             fp = fopen("/local/data.csv", "a");
00352             if(fp == NULL) {
00353                 error("Could not open file for write!!\n");
00354             }
00355             for(int i = 0; i < SD_WRITE_NUM; i++) {
00356                 for(int j = 0; j < WRITE_DATAS_NUM; j++) {
00357                     fprintf(fp,"%f,", writeDatas[i][j]);
00358                 }
00359                 fprintf(fp,"\n");
00360             }
00361 
00362             fclose(fp);
00363 
00364             write_datas_index=0;
00365         }
00366         Thread::wait(100);
00367     }
00368 }
00369 
00370 void WriteDatas()
00371 {
00372     int i;
00373     for(i = 0; i < SOUDA_DATAS_NUM; i++) {
00374         //writeDatas[write_datas_index][i] = 0.0;
00375         writeDatas[write_datas_index][i] = (float)soudaDatas[i];
00376     }
00377     writeDatas[write_datas_index][i++] = pitch;
00378     writeDatas[write_datas_index][i++] = roll;
00379     writeDatas[write_datas_index][i++] = yaw;
00380     writeDatas[write_datas_index][i++] = airSpeed;
00381     writeDatas[write_datas_index][i++] = sonarDist;
00382     writeDatas[write_datas_index][i++] = cadenceResult;//cadence_twe.cadence;
00383     //writeDatas[write_datas_index][i++] = writeTimer.read();
00384     //for(i = 0; i < WRITE_DATAS_NUM; i++){
00385 //        ////pc.printf("%f   ", writeDatas[write_datas_index][i]);
00386 //        twe.printf("%f,", writeDatas[write_datas_index][i]);
00387 //    }
00388 //    //pc.printf("\n\r");
00389 //    twe.printf("\n\r");
00390     if(write_datas_index == SD_WRITE_NUM-1) {
00391 //        SDprintf();
00392         write_datas_index=0;
00393     } else {
00394         write_datas_index++;
00395     }
00396     char sbuf[128];
00397     int p=0;
00398 //    twe.printf("con,");
00399     p += sprintf(sbuf,"con,");
00400     for(int i = 0; i <YOKUTAN_DATAS_NUM ; i++) {
00401 //        pc.printf("%i   ",soudaDatas[i]);
00402 //        twe.printf("%i,",soudaDatas[i]);
00403         p += sprintf(sbuf+p,"%d,",soudaDatas[i]);
00404 
00405         if(i == YOKUTAN_DATAS_NUM - 1)
00406 //            twe.printf("%i\n",soudaDatas[i]);
00407             p += sprintf(sbuf+p,"%d\n",soudaDatas[i]);
00408     }
00409     twe.printf("%s",sbuf);
00410 //    twe.printf("inp,%f,%i,%f,%i\n",soudaDatas[YOKUTAN_DATAS_NUM],soudaDatas[sizeof(float) + YOKUTAN_DATAS_NUM + 2],(int)soudaDatas[SOUDA_DATAS_NUM - sizeof(float) - 3],soudaDatas[SOUDA_DATAS_NUM-1]);
00411     twe.printf("inp,%f,%i,%f,%i\n",inputR,drugR,inputL,drugL);
00412 
00413     /*
00414     送信文字列
00415     0-13翼端データ
00416     14-17 R erebon
00417     18 R DRUG
00418     19-22 L erebon
00419     23 LDRUG
00420     */
00421     ////pc.printf("\n\r");
00422     twe.printf("mpu,%f,%f,%f\n",pitch,roll,yaw);
00423     twe.printf("kei,%f,%f,%f\n",airSpeed,sonarDist,cadenceResult);//cadence_twe.cadence);
00424 
00425     ////pc.printf("%f,%f,%f\n\r",calcKXdeg(kx_X.read()),calcKXdeg(KX_Y),calcKXdeg(KX_Z));
00426 //    pc.printf("%f,%f,%f\n\r",airSpeed,sonarDist,cadenceResult);//cadence_twe.cadence);
00427 //    pc.printf("%d,%i,%d,%i,",soudaDatas[YOKUTAN_DATAS_NUM],soudaDatas[sizeof(int) + YOKUTAN_DATAS_NUM + 2],(int)soudaDatas[SOUDA_DATAS_NUM - sizeof(int) - 3],soudaDatas[SOUDA_DATAS_NUM-1]);
00428 //    pc.printf("%f,%f,%f\n\r",pitch,roll,yaw);
00429 //    printf("mgPin V:%f\n\r",mgPin.read()*3.3);
00430     // pc.printf("%d,%i,%d,%i\n%f,%f,%f\n%f,%f,%f\n\r",
00431 //              soudaDatas[YOKUTAN_DATAS_NUM],soudaDatas[sizeof(int) + YOKUTAN_DATAS_NUM + 2],(int)soudaDatas[SOUDA_DATAS_NUM - sizeof(int) - 3],soudaDatas[SOUDA_DATAS_NUM-1],
00432 //              pitch,roll,yaw,
00433 //              airSpeed,sonarDist,cadenceResult);
00434     debug("cadence:%5.5f\n\r",cadenceResult);
00435 
00436 //    for(int i = 0; i < strlen(cadence_twe.myBuff); i++){
00437 //        ////pc.printf("%c",*(cadence_twe.myBuff+i));
00438 //    }
00439 //    pc.printf("%f\t%f\t%f\t%f\n\r",airSpeed,air_sum[0],air_sum[1],air_sum[2]);
00440     if(android.writeable()) {
00441 //        android.printf("%f,%f,%f,",pitch,roll,yaw);
00442 //        android.printf("%f,%f,\r\n",airSpeed,sonarDist);
00443         android.printf("%4.2f,%4.2f,%4.2f,\n,",roll,airSpeed,cadenceResult);//cadence_twe.cadence);
00444 //        led2 = !led2;
00445     }
00446 //    SDprintf();
00447 }
00448 
00449 void WriteDatasF()
00450 {
00451     //pc.printf("airSpeed:%f\n\r",airSpeed);
00452 }
00453 
00454 //float calcKXdeg(float x){
00455 //    return -310.54*x+156.65;
00456 //}
00457 
00458 void RollAlarm()
00459 {
00460     if((roll < -ROLL_L_MAX_DEG ) && (roll > ROLL_L_MAX_DEG-180)) {
00461         RollAlarmL = 1;
00462     } else {
00463         RollAlarmL = 0;
00464     }
00465 
00466     if((roll > ROLL_R_MAX_DEG) && (roll < 180-ROLL_R_MAX_DEG)) {
00467         RollAlarmR = 1;
00468     } else {
00469         RollAlarmR = 0;
00470     }
00471 }
00472 
00473 int main()
00474 {
00475     Thread mpu_thread(&mpuProcessing);
00476     Thread SD_thread(&SDprintf);
00477 //    Thread soudaSerial_thread(&DataReceiveFromSouda);
00478     init();
00479     int VCcounter = 0;
00480     while(1) {
00481         if(VCcounter%20 == 0 ) {
00482             if( VCmonitor.getVoltage(&V) == 0) {
00483                 debug("e:%f\n",V);
00484             }
00485         }
00486         VCcounter++;
00487 
00488 //        updateCadence(V,mgPin.read() * 3.3,mgPin2.read() * 3.3,isFirstCadenceFlag);
00489         //pc.printf("test\n\r");
00490 //        mpuProcessing();
00491         sonarCalc();
00492         Thread::wait(30);
00493         RollAlarm();
00494         DataReceiveFromSouda();
00495         WriteDatas();
00496         led4 = !led4;
00497     }
00498 }