MIDI - How to handle multiple key inputs on monophonic synth?

Hey there,
is there a proper way how you can go around that problem with midi and multiple keys pressed simultaniously?
I have made a quick and dirty version where i just save the keystrokes in an array and if a key is lift up (NoteOff) it just delete one index from the counter of the array and played the last one:

  do {
    if(Serial.available() > 2) {

      //Read Serial
      commandByte = Serial.read(); //read first byte
      noteByte = Serial.read(); //read next byte
      velocityByte = Serial.read(); //read final byte


      //CHANNEL 1
      //if note on message (Key Pressed)
      if (commandByte == noteOnCh1){
        if (velocityByte > 0 && noteByte > 0) {
          float an = pow(SEMITONE, (float)(noteByte - MIDI_NOTE_CONCERT_A));
          float fn = PITCH_CONCERT_A * an;
          setFrequency(wave1,fn);
          notePlayingCH1[noteCountCH1] = fn;
          noteCountCH1 = noteCountCH1 + 1;
        }
      }
      
      //if note off message
      if (commandByte == noteOffCh1) {
        noteCountCH1 = noteCountCH1 - 1;
        if (noteCountCH1 > 12) {
          noteCountCH1 = 12;
        }
        
        if (noteCountCH1 == 0) {
          setFrequency(wave1,0);
        } else {
          setFrequency(wave1,notePlayingCH1[noteCountCH1]);
        }
      }
      
      //Handle Midi Reset Messages
      if (commandByte == noteResetCh1) { 
        setFrequency(wave1,0);
        noteCountCH1 = 0;
      }
    }
  } while (Serial.available() >= 2); //when at least three bytes available

WIth these its possible to play buttons quick but i doesn't think its the proper way. Do you guys have an idea or maybe a hint? Would be awesome :slight_smile:

Well I would keep the value of the note currently playing in a variable and clear it when a note off came along. Then if another note on message arrived and a note was playing I would then send a note off for that note and start the new note.

multiple keys pressed simultaniously?

Nothing is simultaneous, it all happens one at a time even if you think the keys are being pressed at the same time one will arrive before the other.

You have to decide on a priority scheme, such as first note-down, or lowest active note, so
long as the behaviour is consistent and straightforward its probably usable. Lowest active
note reduces chords to the fundamental (assuming its not an inverted chord!) - that might
have some utility.

Thanks a lot guys,
i have just realized it with a counter:
if another note is pressed the counter gets +1 and only when counter is =0 then the noteoff command is trigered by the monophonic synth. Not great but for now a working solution.