(MIDI) Using Pitchbend with Ultrasonic Sensor?

Hello,
I made this post in the Audio forum but it doesn't get much traffic, so I'm retrying here :slight_smile:

I've currently got a MIDI project going, and I'm trying to use a SR04 sensor to control pitch bend.
Here's what I've got:

void loop() { 

  a=sr04.Distance();          
  if (a <= 20){                          //If Distance is less than 20cm, start pitch bending.
  pitchBend = map(a,0,20,8191,-8192);     // Map 0-20cm to Pitch Bend Parameters (close is higher, further is lower pitch).
  if (pitchBend>8191){pitchBend=8191;};if (pitchBend<-8192){pitchBend=-8192;}   // Debug
  PitchWheelChange(pitchBend);      


void PitchWheelChange(int value) {          // Pitch Wheel Function taken from here: [url=https://forum.arduino.cc/index.php?topic=119790.0]https://forum.arduino.cc/index.php?topic=119790.0[/url]
    unsigned int change = 0x2000 + value;  //  0x2000 == No Change
    unsigned char low = change & 0x7F;  // Low 7 bits
    unsigned char high = (change >> 7) & 0x7F;  // High 7 bits
    midiMessage(0xE0, low, high);
    
}

void midiMessage(int commandByte, int data1Byte, int data2Byte) {   // Midi Output Function
    Serial.write(commandByte);
    Serial.write(data1Byte);
    Serial.write(data2Byte);
}

So essentially I've mapped 0-20cm distance to pitch bend midi parameters, which outputs to a MIDI Message Function.

The issue I'm having is that Hairless MIDI freaks out with its "Received a Status Byte when we were expecting 1 more data byte" message. And my DAW (FL Studio) simply states that I'm sending pitch bend of 158/168 cents no matter what the distance is. I guess therefore, SOMETHING works, but there is obviously something wrong.

Any ideas on this? Perhaps my coding is wrong? I also heard the default library for those ultrasonc modules are very temperamental. Maybe worth getting a new library?

Any help's appreciated,

Eh what are you sending here ?

void midiMessage(int commandByte, int data1Byte, int data2Byte) {   // Midi Output Function
    Serial.write(commandByte);
    Serial.write(data1Byte);
    Serial.write(data2Byte);
}

3 16-bit signed integers ? how about changing it like this

void midiMessage(uint8_t commandByte, uint8_t data1Byte, uint8_t data2Byte) {   // Midi Output Function
    Serial.write(commandByte);
    Serial.write(data1Byte);
    Serial.write(data2Byte);
}

I've made that change ^ I'm getting less warnings in Hairless MIDI when playing notes now, so thanks for that.

The ultrasonic is still behaving the same way though :frowning:

Most ultrasonic sensor libraries will return 0 if no echo is detected (nothing in range). You might want to use the range 1 to 21 instead of 0 to 20.