NEWPING library and MIDIUSB library: Jumpy midi values with HC-SR04

I am using a Pro Micro microcontroller and HC-SR04 sensor to send midi values to Ableton Live over midi usb serial.

When I print the distance to the console, the values are not jerky. However, when the values are sent over midi to Ableton, the parameter that they are mapped to bounces all over the place. It will stay around the correct value for 60% of the time but it will jump up and down like crazy for 40%.

Would anyone know why this is?

The reason I am using the newping library is that it does not require a delay in the code, so I really don’t want to have to introduce any delay if possible.

Thanks in advance for any tips. My code is below:

#include <NewPing.h>
#define TRIGGER_PIN   6//12 // Arduino pin tied to trigger pin on ping sensor.
#define ECHO_PIN      5//11 // Arduino pin tied to echo pin on ping sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
unsigned int pingSpeed = 50; // How frequently are we going to send out a ping (in milliseconds). 50ms would be 20 times a second.
unsigned long pingTimer;     // Holds the next ping time.
 
//MIDI SECTION
#include "MIDIUSB.h" 
int midiChannel1 = 0;  
int cc1 = 13;   


void setup() {
  Serial.begin(9600);   // Initiate a serial communication
  pingTimer = millis(); // Start now.   
}


void loop() {
  if (millis() >= pingTimer) {   // pingSpeed milliseconds since last ping, do another ping.
    pingTimer += pingSpeed;      // Set the next ping time.
    sonar.ping_timer(echoCheck); // Send out the ping, calls "echoCheck" function every 24uS where you can check the ping status.
  }
} 


void echoCheck() { 
  if (sonar.check_timer()) { // This is how you check to see if the ping was received.
     int mappedVal = map(sonar.ping_result / US_ROUNDTRIP_CM, 0, 30, 30, 0);
     controlChange(midiChannel1, cc1, mappedVal*3); // (Channel, CC number, CC value)
     MidiUSB.flush();    
  }
}


// These are midi functions specifically for the Arduino Micro Pro
void noteOn(byte channel, byte pitch, byte velocity) {
  midiEventPacket_t noteOn = {0x09, 0x90 | channel, pitch, velocity};
  MidiUSB.sendMIDI(noteOn);
}

void noteOff(byte channel, byte pitch, byte velocity) {
  midiEventPacket_t noteOff = {0x08, 0x80 | channel, pitch, velocity};
  MidiUSB.sendMIDI(noteOff);
}

void controlChange(byte channel, byte control, byte value) {
  midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
  MidiUSB.sendMIDI(event);
}