# how do you capture the top value in a fallen edge in analogs data (flex sensor)

Guys i'm working with a flex sensor and I'm trying to capture a specific value which is the moment before the user lets go of a flexed flex sensor and its represented as the top point of a falling edge as sub picture A in the picture I included. using an array I tried two methods, which can produce a close value at times but at other it will give me wrong values first I tried the following logic, whenever I detect a value below a certain threshold it indicates that a fallen edge has occurred so get me the value that came right before it as shown in sub picture C but depending on the delay this can be quite unpredictable.

the second method is to store the maximum value of but this returns the peak and it's not always the top of the fallen edge as shown in subpicture B

what do you guys suggest to capture those values? this is my code so far

``````bool loaded = false;
int threshold = 760;
int index = 0 ;
int _max=0;
int values;
int values_size = 4;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
// put your main code here, to run repeatedly:

values[index] = data;
if(data>_max){
_max=data;
}

if (data < threshold) {
Serial.flush();
Serial.print('a');
Serial.print(',');
Serial.print(_max);
Serial.println();
_max=0;
delay(300);
}
index++;
index %= values_size;
}
else if ( data > threshold && !loaded) {

}

delay(20);

}
`````` • Did you forget the picture?
– Majenko
Jun 13 '16 at 14:04
• yeah, sorry about that...it's now up :)
– Raed
Jun 13 '16 at 15:40

I suggest you consider as “top value of the falling edge” the maximum of the values you have read during a specified time window before the edge is detected. This means you have to compute the maximum at the time you detect the edge. If you instead continuously compute a running maximum, then you are going to get a global maximum. Amended source:

``````bool loaded = false;
int threshold = 760;
int index = 0 ;
const int values_size = 4;  // this controls the time window
int values[values_size];

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

void loop() {

values[index] = data;
index = (index + 1) % values_size;

// Detect falling edge.
if (data < threshold) {

// Find the max.
int _max = 0;
for (int i = 0; i < values_size; i++) {
if (values[i] > _max) _max = values[i];
values[i] = 0;  // clear, for next time
}

// Report it.
Serial.flush();
Serial.print('a');
Serial.print(',');
Serial.print(_max);
Serial.println();
delay(300);
}
}

// Detect rising edge.
else if (!loaded && data > threshold) {
Notice the line `values[i] = 0;`. It is intended to avoid the reading of one falling edge being seen on the next one.
• @Raed: Resetting `index` doesn't hurt, but it's not really needed: the `values` array is used as a circular buffer, and when you are in a circle it doesn't matter where you start. Jun 13 '16 at 15:55