Skip to content

Instantly share code, notes, and snippets.

@mskf1383
Created July 31, 2024 11:20
Show Gist options
  • Select an option

  • Save mskf1383/b4b1bf8401b73fb035f61b46f33b5388 to your computer and use it in GitHub Desktop.

Select an option

Save mskf1383/b4b1bf8401b73fb035f61b46f33b5388 to your computer and use it in GitHub Desktop.
#define triggerPin 7
#define echoPin 8
long duration;
int distance;
void setup() {
Serial.begin(9600);
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// get distance
getDistance();
// show resault
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("cm");
}
void getDistance() {
// reset ulterasonic
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// send signal
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
// recive signal
duration = pulseIn(echoPin, HIGH);
// calculate distance
distance= duration*0.034/2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment