so I've got a sensor that is mapped to lead's. as i transition into the next range of my mapped values, the sensor readings flicker, causing the LED to glitch out a bit. heres my code:
int ledVal;
const int pingPin = 7;
const int ledG1 = 11;
const int ledY1 = 10;
const int ledR1 = 9;
int outputValue1;
int outputValue2;
int outputValue3;
int outputValue4;
void setup() {
Serial.begin(9600);
pinMode(ledG1, OUTPUT);
pinMode(ledR1, OUTPUT);
pinMode(ledY1, OUTPUT);
}
void loop()
{
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// delay(5);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
//
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
//delay(10);
int ledVal = cm;
for(int value = 0; value <=0; value +=15) // ramp the number in "value" from 0 to 255
{
//forwrd fade
outputValue1 = map(ledVal,28, 37, value, 255);
outputValue2 = map(ledVal, 34, 23, value, 255);
//delay(100);
outputValue3 = map(ledVal, 15, 23, value, 255);
//delay(100);
outputValue4= map(ledVal, 17, 2, value, 255);
}
if(ledVal <=37 && ledVal >= 28){
analogWrite(ledG1, outputValue1);
digitalWrite(ledR1, LOW);
}
if(ledVal <=34 && ledVal >=23 ){
analogWrite(ledY1, outputValue2 );
digitalWrite(ledR1, LOW);
}
if(ledVal <= 23 && ledVal >=15)
{
analogWrite(ledY1, outputValue3);
digitalWrite(ledG1, LOW);
if(ledVal <= 17 && ledVal >=2)
analogWrite(ledR1, outputValue4 );
digitalWrite(ledG1, LOW);
}}
long microsecondsToInches(long microseconds)
{
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}