Skip to content

Instantly share code, notes, and snippets.

@cmoz
Created March 30, 2022 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmoz/efa2cf0d2a3a778b1ad2874fee56d5c2 to your computer and use it in GitHub Desktop.
Save cmoz/efa2cf0d2a3a778b1ad2874fee56d5c2 to your computer and use it in GitHub Desktop.
int trigPin = A0;
int echoPin = A1;
long duration, cm, inches;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// Convert the time into a distance
cm = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343
inches = (duration/2) / 74; // Divide by 74 or multiply by 0.0135
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(250);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment