HC-SR04 as a potentiometer/filter cutoff (MIDI CC)

Hey,

I've been trying to use an HC-SR04 sensor instead of a normal potentiometer to send midi CC but there is a problem that I just cannot figure out.
It is on the right MIDI channel and everything but I'm doing something wrong while mapping the distance, as it sends out the same random CCs. I uploaded a Screenshot from Hairless MIDI and the code I managed to come up with.
Could anyone please help me. I would very much appreciate it.

#include <MIDI.h>

MIDI_CREATE_DEFAULT_INSTANCE();

// Include NewPing Library
#include "NewPing.h"

#define TRIGGER_PIN A0
#define ECHO_PIN A1

#define MAX_DISTANCE 400  

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
float duration, distance;

int midiCState = 0;
int midiPState = 0;

int potCState = 0;
int potPState = 0;
int potVar = 5;


void setup() 
{
  Serial.begin(115200);
}

void loop() 
{
  // Send ping, get distance in cm
  distance = sonar.ping_cm();
  if (distance >= 2 || distance <= 400) {
  potCState = analogRead(distance);
  midiCState = map(potCState, 0 , 1023, 0 ,128);
  potVar = abs(potCState - potPState);

  if (potVar>5) {
    if(midiPState != midiCState) {
     MIDI.sendControlChange(1, midiCState, 1);
     midiPState = midiCState;
      potPState = potCState;
  }
}
  
 // outputValue = map(distance, 0, 1023, 0, 127);
  delay(300);
}
}

I doubt that distance is now magically an analog pin number...

Thanks for the help. I removed the analogRead function.

potCState = distance;
midiCState = map(potCState, 0 , 1023, 0 ,127);
potVar = abs(potCState - potPState);

I can't figure out how to scale the max distance to the midi cc correctly.
Now it works from 0 to 35 in the HAIRLESS MIDI, but it just doesn't scale like a normal potentiometer would do.

this dated back when your analogRead() was returning a value between 0 and 1023 and you wanted to convert that into a value of 0 to 127.

Now you have a distance, which you checked to be between 2 and 400. So you need to do

midiCState = map(potCState, 2 , 400, 0 ,127);

Wow! It works now! Thanks a lot! Really appreciate it!
Thank you!

the code you posted is the wrong one

have fun :slight_smile:

Hi @rgrontheradar
If you solved your difficulty, mark the post you solved with a "solved" tick.

RV mineirin