Simon Barker / Mbed 2 deprecated RPMMonitor

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 
00003 AnalogIn input(p20);
00004 DigitalOut led1(LED1);
00005 Serial pc(USBTX, USBRX); // tx, rx
00006 Timer t;
00007 
00008 int main() {
00009     float sample;
00010     bool newDetection = true;   //need this as multiple reads happen across white spot
00011     int samples[120];           //higher number = greater accuracy but longer read time
00012     int sampleCount = 0;
00013         
00014     pc.printf("Starting:\n\r"); 
00015 
00016     //start initial timer
00017     t.start();
00018 
00019     while(1) {
00020         //poll analogue in
00021         sample = input.read();
00022         if(sample < 0.1 && newDetection == true){       //tune 0.1 to appropriate level
00023             //detected white spot so stop timer
00024             samples[sampleCount] = t.read_us();
00025             t.reset();
00026             //reset flag
00027             newDetection = false;
00028             sampleCount++;
00029             
00030             //change for shorter/longer read times - must be less than array length (set in ling 11)
00031             if(sampleCount == 100){
00032                 //total up time and average across number of readings taken
00033                 int total = 0;
00034                 for(int i = 1; i < 99; i++){    //start at 1 as the first one will be a junk reading
00035                     total += samples[i];
00036                 }
00037                 float ave = total/98;
00038                 float rpm = (1000000/ave)*60;   //convert from us to rpm
00039                 pc.printf("RPM = %f\r\n",rpm);
00040                 sampleCount = 0;
00041             }
00042         }
00043         else if(sample > 0.9){      //tune 0.9 to appropriate level
00044             newDetection = true;
00045         }
00046     }
00047 }