First of all, not all MIDI messages have channels in them. (For instance, clock messages and sysex messages don't.) Messages with channels are called "voice" messages.
In order to determine whether an arbitrary MIDI message is a voice message, you need to check the top 4 bits of the first byte. Then, once you know you have a voice message, the channel is in the low 4 bits of the first byte.
Voice messages are between 0x8n
and 0xEn
, where n
is the channel.
Byte midiStatus = packet->data[0];
Byte midiCommand = midiStatus & 0xF0; // mask off all but top 4 bits
if (midiCommand >= 0x80 && midiCommand <= 0xE0) {
// it's a voice message
// find the channel by masking off all but the low 4 bits
Byte midiChannel = midiStatus & 0x0F;
// now you can look at the particular midiCommand and decide what to do
}
Also note that MIDI channels are between 0-15 in the message, but are normally presented to users as being between 1-16. You'll have to add 1 before you show the channel to the user, or subtract 1 if you take values from the user.