Skip to content

Instantly share code, notes, and snippets.

@futureshocked
Created January 6, 2020 05:49
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 futureshocked/1289b789e668f099d0d32beb067658be to your computer and use it in GitHub Desktop.
Save futureshocked/1289b789e668f099d0d32beb067658be to your computer and use it in GitHub Desktop.
This sketch uses an ultrasonic distance sensor to calculate the distance between the sensor and an object in front of it
#define trigPin 13
#define echoPin 12
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0)
{
Serial.println("Out of range”);
}
else {
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