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);
}