Search code examples
c++arraysmbed

In C++, finding repeated peak values in array and calculating pulse


First of all I apologise in advance, I'm very new to programming and any help at all is greatly appreciated. I am using mbed to program a microcontroller: my goal is to check an array for peak values:

void peakvals(int array[],const int count);{     //count = size array = 10, meant to find peak vals in array
    int peakcount=0;                             //meant to record the number of peak vals occurring
    for (int i=0;i<peakcount;i++){                
    for (int j=0;j<i;j++){                   
        if ( array[i]==array[j] ){  
            peakcount=1;                         
            peakcount++;                         
        
        }
    }

My overall goal is that I would like to then take this code and output an estimate for pulse rate first waiting for a couple seconds to accumulate values and give an accurate reading, then update every 1 second. I hope my question is clear enough and thank you for your time


Solution

  • As I suggest in the comments, a simple function could looks like this:

    int count_peaks(const int array[], const int arrsize)
    {     
        int peakcount=0;                            
    
        // NOTE: C++ index start at 0, so (arrsize-1) is the last element you can access in the array.
        for (int i= 1; i < arrsize - 2; ++i)
        {    
            // Temporary variables are just to clarify the code, you can do it one-liner below instead.
            const int previous  = array[i-1];
            const int current   = array[i];
            const int next      = array[i+1];
            
            // if( array[i] > array[i-1] && array[i] > array[i+1])
            if( current > previous && current > next)
                peakcount++;
        }
        return peakcount;
    }
    

    Where you look previous and next elements of the array.