Skip to content

Instantly share code, notes, and snippets.

@nkmk nkmk/HC_SR04.ino
Last active Aug 29, 2015

Embed
What would you like to do?
#define trigPin 8
#define echoPin 9
int duration;
float distance;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(1);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) * 0.03437;
if (distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(duration);
Serial.print(" us / ");
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.