Code:
#define trigPin 8
#define echoPin 7
#define buzzer 12
#define vibrationPin 2
void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(vibrationPin, OUTPUT);
}
void loop()
{
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration * 0.034 / 2);
Serial.print(distance);
Serial.println(" cm");
if (distance <= 30)
{
tone(buzzer, 500, 500);
digitalWrite(vibrationPin, HIGH);
}
else if (distance > 30 && distance < 62)
{
tone(buzzer, 500, 100);
digitalWrite(vibrationPin, LOW);
}
else
{
digitalWrite(buzzer, LOW); digitalWrite(vibrationPin, LOW);
}
delay(200);
}