IRsensor DemoProgram

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /*
00002 超音波を参考にした
00003 
00004 */
00005 
00006 #include "mbed.h"
00007 #define BREAKPT_IR 833
00008 #define ERROR_IR 0xFFF
00009 //#define OVERLINE_IR 46
00010 #define ALL_IR 1
00011 volatile unsigned int ave[ALL_IR] = {0};
00012 Serial pc(USBTX,USBRX);//tx,rx
00013 Timer time_ir;
00014 PinName num_ir[ALL_IR] = {p21/*,p22,p23,p24,p25,p26,p27,p28,p29,p30*/};
00015 
00016 unsigned int moving_ave(int num,unsigned int data){
00017     static unsigned int sum[ALL_IR] = {0};
00018     static unsigned int temp[ALL_IR][10] = {{0}};
00019     //static unsigned int ave[ALL_IR] = {0};
00020     sum[num] -= temp[num][9];
00021     sum[num] += data;
00022     temp[num][9] = temp[num][8];
00023     temp[num][8] = temp[num][7];
00024     temp[num][7] = temp[num][6];
00025     temp[num][6] = temp[num][5];
00026     temp[num][5] = temp[num][4];
00027     temp[num][4] = temp[num][3];
00028     temp[num][3] = temp[num][2];
00029     temp[num][2] = temp[num][1];
00030     temp[num][1] = temp[num][0];
00031     temp[num][0] = data;
00032     ave[num] = sum[num]/100;
00033     
00034     /*if(ave[num] >= OVERLINE_IR){
00035         ave[num] = 0;
00036     }*/
00037     return ave[num];
00038        
00039 }
00040 unsigned int ir_function (int num){
00041     DigitalIn sensor_ir(num_ir[num]);
00042     int flag = 0;
00043     unsigned int memory = 0;
00044     unsigned int temp = 0;   
00045     flag = 1;
00046     time_ir.start();
00047     if((sensor_ir)){
00048         while((sensor_ir)){
00049             if(time_ir.read_us() >= BREAKPT_IR){
00050                 flag = 0;
00051                 break;
00052             }
00053         }
00054     }
00055     time_ir.stop();
00056     time_ir.reset();
00057     if(flag){
00058         time_ir.start();
00059         while(!sensor_ir){//!
00060             if(time_ir.read_us() >= BREAKPT_IR){
00061                 break;
00062             }
00063         }
00064         memory = time_ir.read_us();
00065         while(1){
00066             if(!sensor_ir){
00067                 temp = (time_ir.read_us() - memory);
00068                 time_ir.stop();
00069                 time_ir.reset();
00070                 wait(0.01);
00071                 return temp;
00072                 
00073             }
00074         }
00075     }else{//not found
00076     
00077     }
00078     time_ir.stop();
00079     time_ir.reset();
00080     return ERROR_IR;
00081 }
00082 
00083 int main() {
00084     int num = 0;
00085     unsigned int hangar[ALL_IR] = {0};
00086     while(1) {
00087        
00088         hangar[num] = moving_ave(num ,ir_function(num));
00089        
00090         pc.printf("han[%d]=%d ",num, hangar[num]);
00091         num++;
00092         if(num >= ALL_IR){
00093             num = 0;
00094             putchar('\n');
00095         }
00096     }
00097 }