So I have an ultrasound sensor. The kit in itself works fine. However, when I run it with the following code, sometimes distance returns the correct distance. Sometimes it returns a number above 32,000 (but which fluctuates). Can anyone see an obvious problem? I appreciate your help...
/* This function controls the panning servo for the ultrasound sensor
so that the arduino can decide which way it points.
*/
void pan(int degreEs) // determines the number of degrees the servo pans.
{
servoPan.writeMicroseconds(ccwLim - rtAngle + (degreEs * 10));
}
/* This function returns an accurate distance from the ultrasound sensor
using timings and geometry.
*/
int distanceFind(){ // finds the distance of an object
//int distance; // this is now a global variable.
distance = 0;
unsigned long echoTime; // this measures the length of the echo
echoTime = 0;
digitalWrite(trigPin, LOW); // sets the trigger pin to low to preven erraneous measurement
delay(20);
digitalWrite(trigPin, HIGH); // send a pulse to the trigger pin
delay(10); // must be a 10us pulse
digitalWrite(trigPin, LOW); // end of pulse
echoTime = pulseIn(echoPin, HIGH); // measures length of incoming pulse
echoTime = echoTime / 2; // which must be divided by two (as distance is there and back)
distance = int(echoTime / 2.9); // see maths in lab book
//converts the distance integer to a string for printing
String strOne = String(distance, DEC);
char dist[6];
strOne.toCharArray(dist, 6); //converts string to char array
codeBotLCD(dist); //prints the distance from the US sensor
return distance;
}