HC SR04 to MIDI CC ISSUE

Hi people,

I'm having a small issue regarding an HC-SR04 sensor. When converting my data to MIDI CC, it comes up correct in Hairless MIDI, but with every read, there is a "0" reading as well.

Below is the written code and a screenshot from Hairless MIDI. Any help would be much appreciated!

#include <MIDI.h>
#include <NewPing.h>
MIDI_CREATE_DEFAULT_INSTANCE();

#define SONAR_NUM 2      // Number of sensors.
#define MAX_DISTANCE 200 // Maximum distance (in cm) to ping.

NewPing sonar[SONAR_NUM] = {   // Sensor object array.
  NewPing(A0, A1, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
  NewPing(A2, A3, MAX_DISTANCE)
};

int midiCState = 0;
int midiPState = 0;
int sonarCState = 0;
int sonarPState = 0;
int sonarVar = 5;

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through each sensor and display results.
    delay(100); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
    sonarCState = sonar[i].ping_cm();
    midiCState = map(sonarCState, 0, 200, 0, 127);

    sonarVar = abs(sonarCState - sonarPState);

    if (sonarVar > 5) {
      if (midiPState != midiCState) {
        MIDI.sendControlChange (1, midiCState, 1);


        midiPState = midiCState;
        sonarPState = sonarCState;

      }
    }
  }
}

The comment doesn’t match the code. That code will wait 0.1 seconds or 100mS not 50mS the comment mentions.
Even so it is looking a bit fast hence you are getting the zeros.
So either slow it down, or test the sample before you send it and only send the none zero ones.

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.