I am setting up a sketch that controls the brightness of an LED based on the distance value sampled from a maxsonar lv sensor. Using the PWM signal using pulseIn() seems to generate much less noisy values than using the analog signal using analogRead(). Is that to be expected? The problem I am having with pulseIn, however, is that it seems to run much slower. Is there anything anyone can suggest to make it faster?
const int pwPin = 14;
long pwReading, cm;
int samples = 3;
int highestReading;
float time;
float previousIntensity;
float maxDist;
int led = 9; // the pin that the LED is attached to
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
pinMode(pwPin, INPUT);
Serial.begin(9600);
time = 0;
maxDist = 350;
previousIntensity = 0;
}
void loop(){
// print time spent since last loop
Serial.println(millis()-time);
time = millis();
// sample sensor value
highestReading = 0;
for(int i = 0; i < samples ; i++)
{
pwReading = pulseIn(pwPin, HIGH);
// get the highest value
if(pwReading > highestReading)
highestReading = pwReading;
}
// convert to centimeters
cm = highestReading/57.87;
// shape the curve of the result
float intensity = 1-constrain(float(cm),20,maxDist)/maxDist;
intensity = intensity*intensity*intensity;
intensity = previousIntensity*.75 + intensity*.25;
intensity = constrain(intensity,.005,1);
previousIntensity = intensity;
// set the brightness of pin 9:
float val= 200*intensity;
analogWrite(led, val);
}