/*
Ultrasonic Sensor HC-SR04 and Arduino Tutorial
by Dejan Nedelkovski,
www.HowToMechatronics.com
*/
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
const int Buz = 46;
const int LedPin = 12;
// defines variables
float duration;
float distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(LedPin, OUTPUT);
pinMode(Buz, OUTPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delay(10);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delay(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = (duration/2) / 19.1;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
if( distance < 30)
{
digitalWrite(Buz, HIGH);
for(int i=0; i<5; i++)
{
digitalWrite(Buz, HIGH);
delay(50);
digitalWrite(Buz, LOW);
}
digitalWrite(LedPin, LOW);
}
else
{
digitalWrite(Buz, LOW);
digitalWrite(LedPin, HIGH);
}
}