smoothing ultrasonic readings

I’m building a sensor to ultimately transmit midi CC messages. The code below works, but the values are erratic - I want to provide smoothed readings between 70 and 0, so have divided the returned value to get the readings within the range I need, to correspond to the maximum distance I want it to react to. Any suggestions? I’ve tried various smoothing codes without success.

// testing ultrasonic detector - display values 
const int trigPin = 3;
const int echoPin = 2;

long duration;
int distance;
int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is

void setup() {
pinMode(led, OUTPUT);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT);  // Sets the echoPin as an Input
Serial.begin(9600);       // Starts the serial communication
}

void loop() {                 
digitalWrite(trigPin, LOW);     // Clears the trigPin
delayMicroseconds(2);           // gap between readings
digitalWrite(trigPin, HIGH);    // Sets the trigPin on HIGH state for 10 micro seconds
delayMicroseconds(5);           // gap between readings
digitalWrite(trigPin, LOW);
analogWrite(led, 255);     // set the brightness of pin 9:

duration = pulseIn(echoPin, HIGH);    // Reads the echoPin, returns the sound wave travel time in microseconds
distance= duration*0.05;  // Calculating the distance

if (distance <70 && distance >7)    // ignore outside suitable range
  {
  analogWrite(led, (distance*4));     // set the brightness of pin 9:
  Serial.print("Distance: ");
  Serial.println(distance);
  }
}

Hi, See the NewPing library which has this capability:

Start HERE

See Tim Eckel's info and library HERE

thanks, I'll check this out. I've been a bit wary of libraries, since I'm trying to learn and don't understand how they work internally, but I guess I need to just accept that they work!

I’ve been a bit wary of libraries,

Hey, I like to make my own pizza, but sometimes I just buy a finished one from someone else. Libraries are better: they are free and you can make as many copies as you want…

See THIS about Libraries

but I guess I need to just accept that they work!

Sadly, that is not a good assumption.

Most have poor documentation, do not have good error checking and many simply don't work under a number of different circumstances, for example if you use two libraries that use the same resource, like a timer.

Always test before you trust, and post on the forum if you run into difficulties with a particular library, as forum members are aware of many of the problems.