#define trigPin 3
#define echoPin 2
#define buzz 4
int duration, distance;
int time;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(buzz, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = 0.034 * duration / 2;
Serial.print("jarak: ");
Serial.print(distance);
Serial.println(" cm");
delay(200);
time = map(distance, 0, 30, 50, 1000);
if (distance <= 30) {
tone(buzz, 500);
delay(time);
noTone(buzz);
}
if (distance < 10) {
tone(buzz, 500);
delay(50);
}
else{
noTone(buzz);
}
}