Skip to content

Instantly share code, notes, and snippets.

@imjacobclark
Created April 24, 2013 23:21
Show Gist options
  • Save imjacobclark/5456422 to your computer and use it in GitHub Desktop.
Save imjacobclark/5456422 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 Ranging Sensor, see: http://www.micropik.com/PDF/HCSR04.pdf
Read about this project: http://fusionstrike.com/arduino-ultrasonic-ranging-project/
I have used Analog Pins over Digital Pins for a possible port to an ATtiny85
VCC // 5v
GND // GND
TRIG // Analog Pin 5
ECHO // Analog Pin 4
LED // Analog Pin 3
LED1 // Analog Pin 2
LED2 // Analog Pin 1
(c) Jacob Clark 2013 - http://fusionstrike.com
*/
const int ledPin = 15;
const int ledPin1 = 16;
const int ledPin2 = 17;
const int trigPin = 18;
const int echoPin = 19;
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(100);
}
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