while loop not exiting

this is my code I’m not sure why the while loop won’t exit, i use this with a distance sensor and the serial monitor shows up with the correct distances, can anyone tell me what’s wrong?

unsigned long echo = 0;
unsigned long distance = 0;
int ccPin = 11;
int cPin = 10;
int trigPin=7;
int echoPin=5;
void setup()
{
Serial.begin(9600);
pinMode(trigPin,OUTPUT);
pinMode(echoPin, INPUT);
pinMode (cPin, OUTPUT);
pinMode (ccPin, OUTPUT);
}

unsigned long ping()
{
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/58.138) * .39;
return distance;
Serial.begin(9600);
}

void loop()
{
int x = 0;
x = ping();
Serial.println(x);
delay(250);
if (distance<=5)
{

digitalWrite (cPin, HIGH);
delay(2000);
digitalWrite (cPin, LOW);
delay(2000);
digitalWrite (ccPin, HIGH);
delay(2000);
digitalWrite (ccPin, LOW);
delay(2000);
}
do
{
int x = 0;
x = ping();
Serial.println(x);
delay(250);
}
while (distance<=5);
}

You've got two different variables called distance, one is global, the other is local to the ping function.

I changed the code to this and the same thing is happening,

do
{
int x = 0;
x = ping();
Serial.println(x);
delay(250);
while (x<=5);

never mind i managed to do it using this:

do
{
int x = 0;
x = ping();
Serial.println(x);
delay(250);
if (x>=5)
{
break;
}
}
while (x<=5);

    int x = 0;
  x = ping();

It is NOT necessary to use two lines of code here.

    int x = ping();

Of course, your ping() function doesn't return an int...

Count how many times you have defined "distance"!

Paul

Since you have declared a local variable ‘distance’ in the function ‘ping’, the changes that you do in the ping function only affects the local variable. and the global variable ‘distance’ remains ‘0’, which is the variable that you used in the loop.