I am trying to make a system to where when the ultrasonic detects proximity and the two LED's fade according to the proximity of an object or person. The closer an object gets to the sensor, the brighter the LED's get. The farther an object moves away from the sensor, the fainter the LED's get until the object is out of range, then the LED's turn off.
Can anyone help with my code? Right now it is pulsating and very shaky and does not fade smoothly in transitioning from off to bright. And it will not fade out to off when an object moves away from it.
I am a beginner with coding and arduino, so I apologize if my code seems strange. Please have patience with me. Any help would be much appreciated.
Here is the code:
#define trigPin 7
#define echoPin 6
int led = 10;
int led2 =11;
// the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 1;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance <= 50) {
analogWrite (led, brightness);
analogWrite (led2, brightness);
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
}
else {
digitalWrite(led,fadeAmount);
}
}