#define trigPin 7
#define echoPin 6
#define led 13
#define buzzer 11
int frekuensi = 250;
long jarak, waktu;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode (echoPin, INPUT);
pinMode (led, OUTPUT);
pinMode (buzzer, OUTPUT);
}
void loop () {
digitalWrite (trigPin,LOW);
delayMicroseconds(2);
digitalWrite (trigPin,HIGH);
delayMicroseconds(10);
digitalWrite (trigPin,LOW);
waktu = pulseIn (echoPin, HIGH);
jarak = (waktu/2) / 29.1;
if (jarak <= 150) {
digitalWrite (led, HIGH);
tone(buzzer, frekuensi);
Serial.print (jarak);
Serial.print (" cm \n");
}
else if (jarak > 150){
digitalWrite (led, LOW);
noTone (buzzer);
Serial.print("Jarak diluar jangkauan!\n");
}
delay(500);
}