Midi Out delay and strange noise Problem

Hey Guys

i have a small Problem during my Midi Out Project. Maybe somebody can help me.

scope of work: To send a note without delay via midi out on TX Port by pressing a button until its released.

Problem: If i push and hold the button principal the note signal works and is send without a delay and thats fine. I tryed it with my yamaha keyboard and its midi in port. The strange thing is that if i insert a delay after the noteOn message it sounds clear but without a delay time when i push the button it sounds first like going from a low frequency to a high very fast before i hear the right and clear tone. Could it be something with the debouncing time? Maybe somebody has an idea. Thanks :slight_smile:

Here is my primitive code

const int buttonPin = 4;
int buttonState = 0;

void setup() {
// Set MIDI baud rate:
Serial.begin(31250);
pinMode(buttonPin, INPUT);
}

void loop() {
// play notes from F#-0 (0x1E) to F#-5 (0x5A):
buttonState = digitalRead(buttonPin);
{
int note1 = 0x40;
//Note on channel 1 (0x90), some note value (note), middle velocity (0x45):
if (buttonState == HIGH){

noteOn(0x90, note1, 0x45);
}
else {
}
}
}

// plays a MIDI note. Doesn't check to see that
// cmd is greater than 127, or that data values are less than 127:
void noteOn(int cmd, int pitch, int velocity) {
Serial.write(cmd);
Serial.write(pitch);
Serial.write(velocity);
}

I'm only beginning play with midi code but I was under the impression once you send note-on it would play until you send note-off?

Apart from that... it might also depend on how your how yamaha keyboard interprets midi signals... best bet is to add debounce...

Remember loop is looping constantly - you will be calling noteOn maybe a thousand times a second (depending on the serial clock for midi).

You need to detect button-down event and button-up event separately - you don't want to do actions everytime you see a state, just when you see the state change - ie a state-transition.

[BTW note use of code tags...]

int prev_state ;

void loop ()
{
  int state = digitalRead (buttonPin)
  if (state != prev_state)  // only do actions on state-changes
  {
    prev_state = state ;   // record for next time
    if (state == HIGH)  // decide which action
    {
      noteOn(0x90, note1, 0x45);
    }
    else
    {
      noteOff(...) ; // or whatever
    }
  }
}