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);
}