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);
}
}
J-M-L
June 8, 2021, 12:42pm
#2
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.
J-M-L
June 8, 2021, 12:59pm
#4
rgrontheradar:
midiCState = map(potCState, 0 , 1023, 0 ,127);
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);
rgrontheradar:
distance = sonar.ping_cm();
if (distance >= 2 || distance <= 400) {
potCState = analogRead(distance);
midiCState = map(potCState, 0 , 1023, 0 ,128);
potVar = abs(potCState - potPState);
Wow! It works now! Thanks a lot! Really appreciate it!
Thank you!
J-M-L
June 8, 2021, 1:32pm
#6
the code you posted is the wrong one
have fun
Hi @rgrontheradar
If you solved your difficulty, mark the post you solved with a "solved" tick.
RV mineirin
1 Like
system
Closed
October 6, 2021, 1:36pm
#8
This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.