Assistance with LED fading in and out based on Ultrasonic sensor Arduino

I am trying to make a system to where when the ultrasonic detects proximity and the two LED's fade according to the proximity of an object or person. The closer an object gets to the sensor, the brighter the LED's get. The farther an object moves away from the sensor, the fainter the LED's get until the object is out of range, then the LED's turn off.

Can anyone help with my code? Right now it is pulsating and very shaky and does not fade smoothly in transitioning from off to bright. And it will not fade out to off when an object moves away from it.

I am a beginner with coding and arduino, so I apologize if my code seems strange. Please have patience with me. Any help would be much appreciated.

Here is the code:

#define trigPin 7
#define echoPin 6

int led = 10;
int led2 =11;
// the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 1;

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);

}

void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;

if (distance <= 50) {

analogWrite (led, brightness);
analogWrite (led2, brightness);

brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}

}
else {
digitalWrite(led,fadeAmount);
}
}

Next time you post code, please make sure you use code tags. Read the forum guidelines to find out how.

Your code seems too complicated compared to your description. It would be simpler to transform the distance to a pwm brightness, rather than the fading you are trying to implement. Did you try that already? You could use the map() function. You may need to use the constrain() function too.

In your description you say the brightness should depend on distance, but the way it's written there's only one threshold, at 50cm.

Then once it's closer than 50 it's zooming through the fade/unfade as fast as loop() can manage, and the distance doesn't dictate the brightness.

Why don't you set up a bunch of thresholds, and have a set brightness for each "band". (Or do what PaulRB said and have brightness=f(distance) and decide what that function is.)

I would probably have gone for a bunch of leds (either discrete or like in one of these bargraph modules) and not have brightness, but have more leds on as it got closer.