Executing an if statement only once?

Status
Not open for further replies.

Deadp1xels

Well-known member
Code:
{
digitalWrite(0, HIGH);
digitalWrite(1, HIGH);
digitalWrite(2, LOW);
digitalWrite(3, LOW);

int readInThree = analogRead(3); 
Serial.println(readInThree); //use the result
delay(50);
if(readInThree<=350){
  usbMIDI.sendNoteOn(64+octave*12,readInThree,1);
  delay(50); 
}
if(readInThree>=350){
  usbMIDI.sendNoteOff(64+octave*12,readInThree,1);  
}
}

I'm making a Midi controller with flex sensors the code is working fine but i keep seeing "Note off: E5/ velocity 66" in the screen on FL Studio

How do i do:
Code:
if(readInThree>=350){
  usbMIDI.sendNoteOff(64+octave*12,readInThree,1);  
}

Only once so its not continously trying to turn a note off?
 
Last edited:
Something like this:

Code:
byte singleFlag=1; // if you declare this in your loop() then use 'static byte singleFlag=1'

if (singleFlag && readInThree>=350) {
  singleFlag=0;
  usbMIDI.sendNoteOff(64+octave*12,readInThree,1);  
}

Good luck!
 
I tried something similar to no avail but didn't mention it

Just put your code straight in and it gave no errors but it seems to ignore my sendNoteOff altogether

I can't see why its not working because logically there seems to be no code issues...
 
Your code is also vulnerable to sending a lot of on/off if the value read from the ADC is near 350, just from small random fluctuations. It would be better to have some space between the on and off values

Code:
byte pressed=0;

if (!pressed && readInThree > 375) {
  pressed=1;
  usbMIDI.sendNoteOn(64+octave*12,readInThree,1);  
}
if (pressed && readInThree < 325) {
  pressed=0;
  usbMIDI.sendNoteOff(64+octave*12,readInThree,1);  
}

So the pressure needs to be above 375 to register as a press, and below 325 to register as a release (adjust the values to suit).
 
Status
Not open for further replies.
Back
Top