Ritesh Nandy
Ritesh Nandy

Reputation: 1

How to count certain peak values from my arduino's analog pin for an interval of time?

I am getting my analog data from Arduino's analog pin 0. After I plot the data on the serial plotter I get certain maximum peaks. My aim is to count the number of peaks for an interval of time. I have tried to create a function called void bpm(). I have tried to plot the baseline value taking the average of the sampling set of data but I don't know why it's creating a problem. The values are going negative however the sampling set of data doesn't have any negative value. Please help if I am wrong in this code or logic.

const unsigned long sampling_time=6000; // sample the data for 6 seconds interval
unsigned long previous_time=0; // initialise previous time
int sign_arr[100];
int sum=0;
int baseline=0;
int counter=0;  
  
void bpm(){
    
     unsigned long current_time= millis(); // it will constantly get updated
     if( current_time-previous_time >=sampling_time)
     {
      for(int i=0;i<100;i++)
      {
        sign_arr[i]=analogRead(A0);
        sum=sign_arr[i]+sum;
      }
      baseline=sum/100;
     Serial.print("bl: ");
     Serial.println(baseline);
      previous_time=sampling_time;
     }
    
     
    // counting peaks which is greater than base line
      for(int i=0;i<100;i++)
      {
        if(sign_arr[i]>baseline)
        {
          counter++;
        }
      }
      Serial.print("BPM: ");
      Serial.println(counter*10);
      counter=0;
    
}

please refer to this screenshot for better understanding of the problem

Upvotes: 0

Views: 268

Answers (1)

Alex
Alex

Reputation: 877

The problem is probably overflow. Integers can't store very high values on Arduino. Instead of adding all of your samples at once and then dividing by 100, multiply each by 0.01 as you receive it, then accumulate those fractional values. This will prevent overflow. Also use unsigned long if you don't need negative values to raise the threshold for overflowing.

Upvotes: 0

Related Questions