Ultrasonic sensor sketch needs more precision

Hi All,

I ordered an ultrasonic sensor and received it ok. I plugged it real quick on the bread board and it works fine. Only thing is, the sample sketch I found to test it returns a 1 digit measurement ? I don't get it, the variables are Long.

Here it is:

int pingPin = 13; int inPin = 12;

long microseconds;

void setup() { Serial.begin(9600); }

void loop() {

long duration, inches, cm;

digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(10); digitalWrite(pingPin, LOW); delayMicroseconds(2); pinMode(pingPin, OUTPUT);

pinMode(inPin, INPUT); duration = pulseIn(inPin, HIGH);

inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration);

Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println();

delay(100); }

long microsecondsToInches(long microseconds) { return microseconds / 74 / 2; }

long microsecondsToCentimeters(long microseconds) { return microseconds / 29 / 2;

}

Any suggestions to get a few more decimal places ?

Change the long to float?

Or do the calculations in millimeter iso centimeter or in i/100 inch.

long microsecondsToCentiInches(long microseconds) { return microseconds *100 / 74 / 2; // return microseconds * 25 / 37; }

long microsecondsToMM(long microseconds) { return microseconds*10 / 29 / 2; // or microseconds*5 / 29; }

Be aware that having more digits doesn't directly mean that the quality - accuracy / precision - of the measurement increases. You may need to average multiple readings to improve the accuracy, see - http://arduino.cc/playground/Main/RunningAverage - for a helper class

Thanks, I will try the first suggestion, once I do the DFU reprogramming. This little sketch is even worse to re-upload because of the serial communication. =(