Ignoring Repeated Analog Data

Hi,

I'm trying to get my sketch to trigger a MIDI note when my analog data passes a certain threshold.

Right now it repeats the midi note super fast, so long as the data is above the threshold. I don't want it to repeat at all, I only want the note to play once. I would like my sketch to ignore repetitions until the data passes under the threshold again.

Basically I want to do what the [change] object does in Max/MSP, if anyone's familiar. I will need to store the "state" of the sensor and compare it against new data to see if it has changed.

Here's a chunk of the sketch I'm working on:

data3 = analogRead(2);
if (data3 < loThresh3 || data3 > hiThresh3){
noteOn(0x90, kickDrum, 0x7F);
}

Any help would be greatly appreciated.

If that code is in your main loop you will need someway of "remembering" that it has already been executed. I think something like this would work, although it feels sloppy.

boolean playedNote = true; // in setup

data3 = analogRead(2);
if (data < loThresh3 || data > hiThresh3 && playedNote) {
noteOn(0X90, kickDrum, 0x7f);
playedNote = false;
}
elsif(data > loThresh3 && data < hiThresh) playedNote = true;

Here's what I'm trying now, which is kind of an improvement:

data1 = analogRead(0);                               // read the sensor data
   if (data1 < loThresh1 || data1 > hiThresh1){      // determine if data is above or below threshold
     state1 = 1;                                     // 1 if sensor is being tripped
   }
   else {
     state1 = 0;                                     // 0 if sensor is not being tripped
   }
   if (state1 - lastState1 == 1){                    // will yield 1 for a change from off to on (1 minus 0)
       noteOn(0x90, handClap, 127);                  // play the note
   }
lastState1 = state1;                                 // remember last sensor state

However it's still repeating the note, but not nearly as fast. Maybe it's an issue of my analog data bouncing under/over the threshold?

Yeah that is a common threshold problem in electronics, what happens is as you cross the threshold you get rapid switching between the off and on state, one way to deal with this is to create a buffer, as in the tone will start one it passes out of threshold but it will not start again until it passes a few notches below the threshold. Those notches create a buffer.

I'm not quite sure what you mean, could you give an example?

Thanks

What Justin means is that:-
If the note is playing the threshold to turn it off is say 512
If the note is NOT playing the threshold to turn it on is say 600

It's a different threshold when going up to going down, I call this hysteresis.