Smoother readings using an SR04 sensor for a max4live theremin

Hi there :slight_smile:

I’m trying to build a theremin-style controller to have analogue control of a synth patch in Ableton (ie: continuous pitch bending rather than just scrolling through the piano roll). This requires a smooth response so I can control the phrasing of the sound.

I’ve hooked up an Arduino to max4live and using a SR04 proximity sensor I’m able to map it to the frequency shifter audio effect, however the readings jump all over the place and it seems like I’m jumping between Hz values, rather than smoothly cycling through them.

  • Would it help to have the arduino sketch output readings with decimal places? Currently they’re rounded to the nearest cm
  • Is it possible to get more stable readings? Holding my hand still seems to result in the readings jumping around. Would a lower delay value or higher max distance help? Or is there a more efficient way to code it?

#define echoPin 11 // The number of the digital pin connected to the echo input
#define trigPin 12 // The number of the digital pin connected to the trigger output
#define LEDPin 13 // This enables the LED feedback for testing

int maximumRange = 70; // The max distance observed from the sensor
int minimumRange = 0;
long duration, distance; //duration used to calculate distance

void setup() {
Serial.begin(9600); //starts the serial communication via USB
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LEDPin, OUTPUT); //board LED for testing


void loop() {

digitalWrite(trigPin, LOW);
delayMicroseconds(2); // pulse off

digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // pulse for 10 microseconds

digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // echo pin listens / receives

// from that data calculate distance in CentiMeters based on Speed of Sound
distance = duration / 58.2;

// error handling
if (distance >= maximumRange || distance <= minimumRange) {
Serial.println("-1"); //if nothing observed ouput -1
digitalWrite(LEDPin, HIGH); // LED will be on
} else {
Serial.println(distance); // prints the distance in CM
digitalWrite(LEDPin, LOW); // LED will be off if object detected

delay(10); // good practice not to overload the serial port


See attached for the M4L patch, though I’ve also added a sel-1 object to remove the -1 readings that Ableton sees as invalid.

If anyone could point me in the right direction that would be great :slight_smile:



You can set a timeout on the pulseIn, 10000 us is probably enough. That saves long delays in case of no reading.

What do you see on the monitor? How is it "jumping around"? Expect up to 2 cm difference between readings with the HC-SR04.


Image tags will show your imaga. Code tags will show your code properly