I'm using a sonar sensor to detect proximity, and need to control the brightness of an LED strip in direct relationship to the distance detected. For example, as someone moves toward the sonar, the strip needs to dim.
I'm using map() to do it now crudely but it's way too abrupt and I'm not sure how best to achieve the effect I'm looking for. Ideally, as the person moves toward the light, it very smoothly fades out in relationship to the person's movement/pace.
Initial thoughts / questions:
-- Can I use a more refined number type to set the LED brightness other than int? -- Do I need to do something more complex where I detect the delta in the person's movement and use the loop to fade the LED from one value to another? Seems complicated...
Any help / ideas on this would be much appreciated! Existing code is below if it helps. Claudia
//variables needed to store values
long pulse, inches, cm;
//LED VARIABLES
int frontPin = 6; // front strip connected to PWN pin 5
long interval = 8000; // interval at which to do something (milliseconds)
int val;
void setup() {
//This opens up a serial connection to shoot the results back to the PC console
pinMode(frontPin, OUTPUT);
pinMode(pwPin, INPUT);
Serial.begin(9600);
}
void loop() {
//Used to read in the pulse that is being sent by the MaxSonar device.
//Pulse Width representation with a scale factor of 147 uS per Inch.
pulse = pulseIn(pwPin, HIGH);
//147uS per inch
inches = pulse/147;
//change inches to centimetres
cm = inches * 2.54;
if (inches < 36){
detect();
}
}
void detect(){
Serial.print(inches);
Serial.print("in, ");
Serial.println();
val = inches;
val = map(val, 6, 36, 0, 255);
analogWrite(frontPin, val);
Serial.print("mapped value is ");
Serial.print(val);
delay(500);
}