Dear Community,
i hope somebody can help me with this (as i didn’t found something on the forum that did): I’m fading an LED with the cosinus function. As input i have a HC SR 04 ultrasonic sensor. I want the LED to fade faster when the object is distant from the sensor and slower when the object is closer. So far i kind of managed but when the object gets closer to the sensor and the LED fades slower it also starts flickering. I figured out it must be because the constant input of the sensor doesn’t allow teh LED to complete one fade-cycle (“valueR” of red LED from 0 to 255 and back to 0). So i tried modifying the code so that the LED only takes a new Value from the ultrasonic sensor when the “valueR” is back to 0 and starts a new fade-cycle only using ONE value from the sensor and only using a new one when a new fade-cycle begins. But it still doesn’t work… Does anybody have a tip on how to use only one Value for one fade-cycle? I would be very happy about any help!
Thank you in advance!
Here’s the code i’m using:
// http://playground.arduino.cc/Code/NewPing
#include <NewPing.h>
#define TRIG_PIN 5
#define ECHO_PIN 11
#define MAX_DIST 50
int RED = 3;
int valueR;
long time=0;
int periode = 2000;
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DIST); // NewPing initialisieren
int inputPin = A0;
void setup() {
Serial.begin(9600);
pinMode(RED, OUTPUT);
}
void loop() {
analogWrite(RED, valueR);
valueR = 0;
//delay(10);
unsigned int distanceCM = sonar.ping_cm();
//Serial.print(distanceCM);
//Serial.println("cm");
//sonar.ping_median(3);
if (distanceCM <= 5) {
distanceCM = distanceCM + MAX_DIST;
}
float VAR = map(distanceCM, 0, 50, 7500, 100);
int VALUE;
if (valueR >= 250) {
VALUE = VAR;
}
if (VALUE == 0) {
VALUE = VAR;
}
time = millis();
valueR = 128+127*cos(2*PI/(VALUE)*time);
analogWrite(RED, valueR);
}