Distance sensor repetition

For some reason, the printing on the serial monitor is not repeating when I put in this code:

const int buzzPin = 11;
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;


void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
  pinMode(buzzPin, OUTPUT);
}

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance= duration*0.034/2;

  // Prints the distance on the Serial Monitor.  Click on the button on the top right corner of the Arduino screen.
  Serial.print("Distance: ");
  Serial.println(distance);


  //Buzzer sound making

  do {
    tone(buzzPin, distance, 1);
    delayMicroseconds(2);
  }
  while (1);


}

Does anyone know what I am doing wrong?

That

you will never leave this local loop.

So what should I do to correct it?

It depends what you were trying to accomplish with it. What do you want it to do?

I took that part of the code out, and now it just displays "?" on the serial monitor. Here is my code:

const int buzzPin = 11;
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;


void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
  pinMode(buzzPin, OUTPUT);
}

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance= duration*0.034/2;

  // Prints the distance on the Serial Monitor.  Click on the button on the top right corner of the Arduino screen.
  Serial.print("Distance: ");
  Serial.println(distance);


  
  
  }
  

Does this match the value on the serial monitor?

Try putting a "delay (50);" before the closing } of loop().

You still haven't said what you want to do.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.