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?