Adjusting LED brightness using a Distance Sensor

I'd like to adjust the brightness of one LED based on the distance measured by the distance sensor.

Distance is low (Object is nearby) -> LED should be brighter Distance is high (Object is away) -> LED should be lower brightness

This should be done with 2 cases:

if distance is between 0 and 250 cm, led should be high brightness. if distance is between 251 and 500 cm, led should be low brightness. We ignore any readings above 500 cm.

Here's the code I'm using for the distance sensor, the LED part hasn't been added yet.

Thank you

#define trigPin1 2 //initialize pins

#define echoPin1 3

#define trigPin2 4

#define vibrator1 8

long duration, distance, Sensor1;

void setup()

{

Serial.begin (9600);

pinMode(trigPin1, OUTPUT);

pinMode(echoPin1, INPUT);

}

void loop() {

SonarSensor(trigPin1, echoPin1);

Sensor1 = distance;

Serial.print(Sensor1);} //print distance

void SonarSensor(int trigPin,int echoPin) //calculates distance from sensor

{

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH); //emits ultrasonic wave

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH); // calculates the time between sending and receiving

distance = (duration/2) / 29.1; // use the time and velocity of the ultrasonic wave to find distance

delay(250);}

Look at analogWrite() for adjusting the brightness of a led connected to a pin which is defined for pwm (pulse width modulation).