I am attempting to read an HC-SR04 ultrasonic sensor at the same time a couple of servos are running. Having a servo running is messing up the timing of the pulseIn() method.
The distance measurement will be correct for small distances (up to 24 cm or so), but anything larger sometimes read incorrectly. If a server is not attached to D2 or D3, the distance sensor works fine. How can I get both to play together? Maybe a library that doesn't rely on the same timers as a server on D2 and D3? This is on a Mega.
// read the distance sensor
// returns: distance in inches. -1 means out of range
float ReadDistance(int trigPin, int echoPin)
{
long duration;
float distance;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2.0) / 29.1 / 2.54;
if (distance >= 200 || distance <= 0)
return -1.0;
else
return distance;
}