Ultrasonic sensor calculating distance


Wow, I haven’t been on here in a while. I’ve been programming in C++ (that’s different) for the FRC!

My question to you guys is how do I calculate distance using an ultrasonic sensor? I know that you have to calculate how much time it takes for the signal to get back to the robot, but I don’t know how to write that in C.

So, could someone please show me how to program the robot to start counting after it starts the encoder and then stops when it receives a signal?? Thanks!

I just use RobotC, which does that stuff auto-magically :confused:

We use the WPILibrary and the MPLabs compiler.

Once they get it working in a stock loop:

unsigned int distance;
while (1) {
   distance = GetUltrasonic(ping, listen);
   printf("Distance = %d",distance);

Then they start taking samples of what they get back for the distance numbers. They do the math, plot curves, etc. They then update the code to be:

unsigned int distance, inches;
while (1) {
   distance = GetUltrasonic(ping, listen);
   inches = distance / 5;  // tests show that there were 5 distances to an inch.
   printf("Distance = %d, which is %d inches",distance, inches);

So it’s more of a learning exercise.

(C code is not exact, but close)

I’m assuming that ‘ping’ and ‘listen’ are the interrupt and DigitalOutput ports??

In the manual it said something about a timing loop, and I was confused. But this looks like it’s going to help. Thanks!

Yes they are the same.

I teach the roboteers to use defines to set up ports, rather than using “magic numbers”

So code like this

Distance = GetUltrasonic(11,1);  


#define = frontSonar 11
#define = frontPing 1

distance = GetUltrasonic(frontSonar, frontPing); 

If I need to change the ports, I do it in the defines and not need to dig through 100’s of lines of code.