Dimming LED using the analogwrite function

Hello,

I would like to preface this post by saying that this is my first time using an Arduino and trying to program something, so apologies in advance if my code is very basic and a mess.

My project consists of ultrasonic sensors and LED’s hooked up to an Arduino board. As an object gets closer to the sensor, the corresponding LED should gradually light up.

I have almost achieved this. Everything is working, except that as an object gets closer to the sensor, the LED dims! When an object is far away, the LED lights up, and if the object is far enough away, the LED blinks. Everything is happening in reverse. How can i fix this? I suppose i need the distance values to be reversed in some way.

My code is as follows:

#define trig 13;
#define echo 7;
#define LED 11;

long duration, distance;

void setup() {
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(LED, OUTPUT);
}

void loop() {
digitalWrite(trig, LOW);
delayMicroseconds(2);

digitalWrite(trig,HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);

duration = pulseIn(echo, HIGH);
distance = duration/58;
analogWrite(LED, distance);

delay(100);
}

I’m sure there is an easy solution to this. I tried to use the map function to reverse the range of numbers, however this did not work. I am not sure if this is just an inappropriate use of the map function or i used it wrong. I had the function as follows:

distance = map(distance, 1, 300, 300, 1);

Below is my code for the whole project. Again, apologies for the mess.

Thanks in advance for your help!

ultrasonic_led_basic.ino (1.74 KB)

Well, the maximum value for analogWrite is 255, you might try:

distance = constrain(distance, 0, 255);
analogWrite(LED, 255 - distance);

I am going to assume the maximum distance you care about is 150.

distance = (distance <150)? (distance):150;

int led_brightness = 255 - map(distance, 150, 0, 255,0);

outsider:
Well, the maximum value for analogWrite is 255, you might try:

distance = constrain(distance, 0, 255);

analogWrite(LED, 255 - distance);

This worked perfectly - thanks for your help!