Hi everyone,
I start in arduino and I currently have a little problem and i come to ask some help :
This assembly consists of an arduino, an ultrasonic sensor and a led.
when I approach the sensor, I would like the latter gradually illuminates the led, but when I leave the sensor field rather than suddenly turn off the leds, it begins a fade out.
To that I would like to add, when entering the sensor field, a fade recovery by rising from the value where it is based on the distance detected in the field of the sensor.
Actually this is my code :
#define trigPin 7
#define echoPin 6
#define pinLed 9
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(pinLed, OUTPUT);
}
void loop() {
long duration, distance, distance2, fadeValue;
digitalWrite(trigPin, LOW);
delayMicroseconds(1);
digitalWrite(trigPin, HIGH);
delayMicroseconds(2);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance <= 50)
{
distance2 = 50 - distance;
fadeValue = map(distance2, 0, 50, 0, 254);
analogWrite(pinLed, fadeValue); // Writes the fadeValue to pin 9
}
else
{
for (int fadeValueout = fadeValue; fadeValueout >= 0; fadeValueout -= 5) {
analogWrite(pinLed, fadeValueout);
delay(100);
}
}
delay(100);
}
currently the detector works, and lights the LED depending on the distance (but led is to quickly at her max brightness). But on the other hand, my fadeout code does not work (led just turn off), and I do not have much idea about how to code the fade in recovery on an existing value of the fade out.
Can you help me ?