I will be using the HC-SR04 ultrasonic sensor to measure sensor. I am using Arduino MEGA2560.
The speed of sound is 340.29 m/s then convert this to 29.38 us / cm.
340.29 m/s then 34029/1000000 cm/us then inverting 29.38 us/cm.
/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
*/
#define t 4
#define e 5
#define led_2 52
void setup() {
Serial.begin (9600);
pinMode(t, OUTPUT);
pinMode(e, INPUT);
pinMode ( led_2 , OUTPUT);
digitalWrite(led_2, LOW);
}
void loop() {
long duration, distance;
// The speed of sound is 340.29 m/s or 29.38 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled
// Trigger Pulse 10us
digitalWrite(t, LOW);
delayMicroseconds(2);
digitalWrite(t, HIGH);
delayMicroseconds(10);
digitalWrite(t, LOW);
// Reads a pulse (either HIGH or LOW) on a pin. if value is HIGH, pulseIn() waits for the pin to go HIGH,
// starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds.
// it returns an unsigned long datatype
duration = pulseIn(e, HIGH);
distance = (duration/2) / 29.38;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
if ( distance < 25 ){
digitalWrite( led_2 , HIGH);
} else {
digitalWrite ( led_2 , LOW );
}
}
delay(500);
}