MIDI gotchas !!
When I was writing code to handle the MIDI port it behaved well with my Yamaha P120 electronic Piano but behaved badly with my Yamaha PSR 6000. When I played keys on the PSR 6000, some notes would not play and others would not end correctly and kept sustaining.
I was baffled by this and saw that bytes seemed to be dropping out when viewing a raw dump of the port on the Raspberry PI. I was convinced there was a hardware problem, or a bug in the PI operating system.
I could play single notes and they would work but if I played a chord or two notes together I would get a problem. I then analysed the dump again and it struck me that there was a pattern. When a key is pressed, you normally get three bytes, the control byte $90, the pitch byte and the velocity byte. When two notes are pressed on the PSR 6000, I expected to get six bytes, two groups of three, but I got the control byte $90 for key down, the pitch byte for the first note, the velocity byte for the first note, the pitch byte for the second note and the velocity byte for the second note. I got 5 bytes instead of 6.
Its simple, multiple key presses are grouped together using a single MIDI control byte ! I altered the receiver code to keep accepting two byte segments until a new control byte is received. This solved the problem and the code works with both keyboards.
There is a subtle difference between theYamaha P120 midi firmware and the PSR 6000 firmware in this respect.
Gotcha #2 was that Yamaha do not use the MIDI spec for note off. (i.e. a control byte of $80). They use an alternative by using a key on but with a zero velocity. Presumably this helps when grouping mutiple key on/off events together.
Anyhow my code can handle both situations and always outputs 3 byte midi commands irrespective of what is received to keep things simple.
Gotcha #3 was that was a continuous flow of MIDI sense bytes of $F8 and $FE from both keyboards. These are simply filtered out.