# Distance Readings Getting Manipulated When Calling Unrelated Function

I'm using a Lidar Lite v3 to measure the distance from one object to another. I pass the results to the serial monitor to see what that distance is. It appears that when I call an unrelated function, the distance that's being printed seems to be roughly subtracted by 512.

To describe exactly what I mean, this is my function:

``````int pulseWidth = pulseIn(monitorPin, HIGH); //begin measurement of time
int distanceConverted = (pulseWidth / 10); // 10usec = 1 cm of distance
Serial.println(distanceConverted); // Print the distance
``````

and it gives me an output of this (which is correct):

``````780 cm
787 cm
790 cm
794 cm
782 cm
787 cm
790 cm
786 cm
790 cm
780 cm
788 cm
784 cm
``````

I'm using these distances to control LED lights and a speaker, and call this function to do so:

``````void lights(int distanceConverted)
{
if (distanceConverted < 1000 && distanceConverted > 500)
{
digitalWrite(yellowLEDPin, HIGH);
delay(20);
tone(8, 35000, 250);
}

else if (distanceConverted <= 500)
{
digitalWrite(redLEDPin, HIGH);
delay(20);
tone(8, 40000, 250);
}
}
``````

However, when this is called (and I call the function after I print the distance values), these are the results I get:

``````268 cm
267 cm
266 cm
267 cm
269 cm
267 cm
265 cm
267 cm
266 cm
266 cm
267 cm
264 cm
269 cm
``````

When I try to account for this and multiply by three, my values become even more off and seem to be multiplied by ten:

``````int distanceConverted = (pulseWidth / 10)*3; // 10usec = 1 cm of distance

New Values:
2640 cm
2673 cm
2634 cm
2649 cm
2592 cm
2619 cm
2631 cm
2628 cm
2631 cm
2673 cm
2634 cm
``````

At first I thought it might have been the delays within the lights() function manipulating the readings, but even after commenting them out I still get the same results. I don't know how the function could be throwing my values off.

Edit: I noticed at when the program is first looping, the 512 gets subtracted after the first time I run through the lights() function.

``````761 cm <- first value from sensor, correct
312 cm
308 cm
308 cm
309 cm
308 cm
307 cm
307 cm
309 cm
308 cm
308 cm
``````

When I comment out the tone() function, that seems to fix my problem. Could that function be overwriting a bit in the memory register causing it to subtract 512 from my distanceConverted variable?

• Messing up a single bit in a register seems quite far fetched to me. Could you also post this `tone` function - as you seem to indicate it being the culprit? Apr 29 '17 at 20:54
• Tone is a standard arduino function.
– Majenko
Apr 29 '17 at 21:51