Hi, I’m looking for code that might already be written to obtain a distance from an ultrasonic rangefinder. The one in specific that I have is at the following link.
I could write the code myself, but I would rather see what is already out there so that I don’t need to make the same mistakes that others have gone through.
If you are willing to try a different ultrasonic, the MaxBotix one requires practically no coding at all; it can output distance as an analog signal, which requires no interrupts, and all you need to do is read from an analog input. The two ultrasonics cost about the same too ($0.45 difference).
We aren’t using EasyC or WPILIB, but we have used the Maxbotic sensor using analog with good results. The current models use a 9.8mV to an inch scaling.
The code was simple as well.
Here’s a sample for it that I just typed from memory using analog port 1:
unsigned int sonic;
unsigned int mV;
unsigned int inches;
sonic = Get_Analog_Value(rc_ana_01);
mV =( (sonic * 5000) / 1024 );
inches = mV * 10 / 98;
Well you can do that, if you don’t mind the small error that is introduced from it, and that the version of the sensor uses 10mV per inch scaling. All the newer models use 9.8mV per inch scaling so your range readings will be off even more.
For example a reading of 512 would be 2.5mV which is very close the 2.55mV maximum range that this device uses. So dividing by 2 would give you 256, which is close to 250 inches the device is reporting, but 6 inches off at that range(using 10mV inch). As you get closer it becomes less of an issue.
It all depends on the level of precision you need or want.
There’s no particular reason for the software to deal with distance in inches, or centimeters, or any “engineering” unit. We’ve usually done all the navigation using the equivalent of raw encoder or analog input counts.
For something like autonomous scripting we typically convert in the other direction, to turn familiar units like inches into the values the program likes.