Midi-Out does not work well

The probem is that you need to detect the transition from off to on and on to off, only sending the MIDI message when you see the transition (this is the EDGE detection mentioned). As has already been suggested, you need to remember the last state of the input and only act when the state is different from what it was before.