Peak Finding

updated 9 Sept 2014

This example finds the peak value of an analog sensor over time. It assumes the sensor is moving in a simple curve.

The peak value is initially set at zero. The program checks to see that the current value is greater than the current peak value. If so, then it saves the current value as a peak.  If the current value is below a given threshold and the current peak value is above it, then the current peak is taken as the final peak. This example also includes a noise value, that allows you to adjust for sensor fluctuation.

The graph below gives you a visual sense of how the program operates. At readings 1, 2, and 3, the latest reading becomes the new peak. At reading 4, the peak remains unchanged because reading 4 is less than the last recorded peak. But the peak isn’t reported until reading 5, when the current reading goes below the threshold. This is the one disadvantage to this peak finding method: you don’t know you’ve had a peak until after it’s over.

peak_explained

 

Beware local peaks

This example works well for simple situations, where a sensor will generate a reasonably simple, sharp peak like this one below:

peak_1

It will also work in situations where your sensor generates some local peaks on the way to a highest peak, like this one:

peak_2

It will fail, however, if your sensor goes below the threshold again on the way to a highest peak, like this:

peak_3


/*
Peak Finder

 This example finds the peak value of an analog sensor over time.
 It assumes the sensor is moving in a simple curve.

 The program checks to see that the current value is above a given threshold,
 then checks to see if the value is greater than the previous value. if so,
 then it saves the current value as a peak. When the current value goes below
 the threshold again, it outputs the last peak value recorded.

 created 12 Sept. 2005
 modified 9 Sept. 2014
 by Tom Igoe

 */

int peakValue = 0;
int threshold = 50;   //set your own value based on your sensors
int noise = 5;        //set a noise value based on your particular sensor

void setup() {
  Serial.begin(9600);
}

void loop() {
  //read sensor on pin A0:
  int sensorValue = analogRead(A0);
  // check if it's higher than the current peak:
  if (sensorValue > peakValue) {
    peakValue = sensorValue;
  }
  if (sensorValue <= threshold - noise ) {
    if (peakValue > threshold + noise) {
      Serial.println(peakValue);
      peakValue = 0;
    }
  }
}

This entry was posted in arduino/wiring, PicBasic Pro. Bookmark the permalink.

Comments are closed.