LED won't reverse :( please help

I am using an ultrasonic sensor with a LED. My problem is that I want the LED to get brighter when something comes closer to the device, but for some reason the LED does the opposite (starts off bright, then gets dimmer until you are touching the sensor). Can anyone please tell me how I can code it so that the LED gets brighter the closer you get to the device and not the opposite.

// here is the code //
Ps~ I'm new to this stuff

#define trigPin 7
#define echoPin 8
#define ledPin 9

long duration, distance;

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

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH); // Wait for HIGH, timer on, timer ends on LOW
  distance = duration / 58; // distance in cm (for inches divide by 148)
  analogWrite(ledPin, distance); // 4 - 200
  
  if (distance >= 400 || distance <= 2){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

The second parameter to analogWrite is the "duty cycle" - what fraction of the time will the pin be HIGH. So, assuming the positive leg of the LED is connected to this pin, then obviously the larger the distance, the more time it's in HIGH state and therefore appears brighter.

How to reverse that? Think of it as a little math problem, with what kind of formula can you make Y bigger as X gets smaller and vice versa? :slight_smile:

Also, note that analogWrite can only get a duty cycle up to 255. If you send it greater values, strange things will happen.

Also, note that analogWrite can only get a duty cycle up to 255. If you send it greater values, strange things will happen.

Not so strange - only the lower 8 bits get used, the rest are ignored.

CrossRoads:
Not so strange - only the lower 8 bits get used, the rest are ignored.

Well yes, when you know what's going on under the hood, it makes perfect sense - but for a beginner who encounters the effects of this for the first time... :wink: