You need to add a variable to remember if you've already sent note-on. When it's not, do the first part where you check if it should turn on. When it is on, do the second part where to check if it should turn off. The idea is you do not want to be checking if the note should turn on when it's already on.
Kinda like this:
Code:
const int channel = 1;
bool noteIsOn = false;
void setup() {
Serial.begin(9600);
}
void loop() {
if (noteIsOn == false) {
if (touchRead(1) > 1100) {
usbMIDI.sendNoteOn (40, 99, channel);
noteIsOn = true;
}
} else {
if (touchRead(1) < 900) {
usbMIDI.sendNoteOff (40, 0, channel);
noteIsOn = false;
}
}
Serial.println(touchRead(1));
while (usbMIDI.read()) {}
delay(5);
}
It also helps to use 2 different thresholds, where the on threshold is slightly higher. That way the note won't rapidly turn on & off if the signal is right at the threshold and has a small amount of noise. In this code, I changed 1000 to 1100 and 900. You might wish to adjust as you like.