Skip to content

Instantly share code, notes, and snippets.

@imjacobclark
Created April 24, 2013 21:48
Show Gist options
  • Save imjacobclark/5455864 to your computer and use it in GitHub Desktop.
Save imjacobclark/5455864 to your computer and use it in GitHub Desktop.
For use with the Ultrasonic Ranging Module HC-SR04 and 3 LEDs.
/*
For use with a 4 pin Ultrasonic Distance Sensor
VCC // 5v
GND // GND
TRIG // Pin 13
ECHO // Pin 12
(c) Jacob Clark 2013 - http://fusionstrike.com
*/
const int trigPin = 13;
const int echoPin = 12;
const int ledPin = 11;
const int ledPin1 = 10;
const int ledPin2 = 9;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
Serial.begin(9600);
}
void loop()
{
long duration, inches, cm;
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
if(cm < 10 && cm < 100 && cm < 1000){
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
}
if(cm > 10 && cm > 100 && cm < 1000){
digitalWrite(ledPin, LOW);
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, LOW);
}
if(cm > 10 && cm > 100 && cm > 1000){
digitalWrite(ledPin, LOW);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, HIGH);
}
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(1);
}
long microsecondsToInches(long microseconds){
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds){
return microseconds / 29 / 2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment