I wanted to make a suitable program for measuring distance using a Hc-sr04 (ultrasonic sensor) and Arduino Uno . The arduino board is showing a HIGH reading even when no LOAD is connected.Please also explain why cm and inch are return right after the variable long .
I used the following code:
int trigPin = 11;
int echoPin = 12;
long duration, cm, inches;
void setup() {
//Serial Port begin
Serial.begin (9600);
//Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
// convert the time into a distance
cm = (duration/2) / 29.1;
Serial.print(cm);
Serial.print("cm");
delay(250);
}
codeultrasonic.ino (947 Bytes)