Created
November 23, 2014 12:23
-
-
Save ringodin/543337240fca23d251a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const int Trig_pin = 12; // Triggers Pulse for THE Ultrasonic Sensor | |
const int Echo_pin = 10; // Recevies Echo for THE Ultrasonic Sensor | |
int led = 13; | |
long duration; // Time it takes for pulse to bounce back to THE Ultrasonic Sensor | |
void setup() { | |
pinMode(led, OUTPUT); | |
Serial.begin(9600); // Set up Serial library at 9600 bps | |
Serial.println("Initializing..."); // Print Initializing... to confirm code is working with Serial Library | |
Serial.println ("Starting"); | |
// initialize the pulse pin as output | |
pinMode(Trig_pin, OUTPUT); | |
// initialize the pulse pin as output: | |
pinMode(Echo_pin, INPUT); | |
// initialize the echo_pin pin as an input: | |
} | |
void loop() | |
{ | |
// establish variables for duration of the ping, | |
// and the distance result in inches and centimeters: | |
long duration, inches, cm; | |
// Pulse and Echo for THE only Ultrasonic Sensor ; Process for determining and printing the durations | |
// for THE Ultrasonic Sensor | |
digitalWrite(Trig_pin, LOW); | |
delayMicroseconds(2); | |
digitalWrite(Trig_pin, HIGH); | |
delayMicroseconds(5); | |
digitalWrite(Trig_pin, LOW); | |
duration = pulseIn(Echo_pin,HIGH); | |
inches = microsecondsToInches(duration); | |
cm = microsecondsToCentimeters(duration); | |
Serial.print(inches); | |
Serial.print("in, "); | |
Serial.print(cm); | |
Serial.print("cm"); | |
Serial.println(); | |
delay(100); | |
if (cm < 20) | |
{ | |
digitalWrite(led, HIGH); | |
} | |
else | |
{ | |
digitalWrite(led, LOW); | |
} | |
} | |
long microsecondsToInches(long microseconds) | |
{ | |
// According to Parallax's datasheet for the PING))), there are | |
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per | |
// second). This gives the distance travelled by the ping, outbound | |
// and return, so we divide by 2 to get the distance of the obstacle. | |
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf | |
return microseconds / 74 / 2; | |
} | |
long microsecondsToCentimeters(long microseconds) | |
{ | |
// The speed of sound is 340 m/s or 29 microseconds per centimeter. | |
// The ping travels out and back, so to find the distance of the | |
// object we take half of the distance travelled. | |
return microseconds / 29 / 2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment