Problem reading ultrasonic sensor

so, I'm a compleetly new to arduino and I am trying to figure out a HC-SR04 ultrasonic sensor.
I have this easy code:

const int trig = 6;
const int echo = 5;

long totaltime;
int distance;

void setup ()
{
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);

}

void loop()
{
  digitalWrite(trig, LOW);
  delayMicroseconds(2);

  digitalWrite(trig, HIGH);
  delayMicroseconds (20);
  digitalWrite(trig, LOW);

  totaltime = pulseIn(echo, HIGH);

  distance= totaltime*0.034/2;

  Serial.print("Distance:");
  Serial.println(distance);
}

But there is a problem reading, inbetween every read it does he turns off or something and reads a zero. I cannot figure out the problem, so has anyone else an idea of a solution?

Seems like I just answered this question on another thread.

Read the documentation for pulseln() and you will see the source of your problem.

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