//Nama : Novia R TI 5B
#define ECHO_PIN 2
#define TRIG_PIN 3
int Buzzer= 12;
void setup(){
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(Buzzer, OUTPUT);
}
float readDistanceCM(){
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN,HIGH);
return duration * 0.034 / 2;
}
void loop(){
float distance = readDistanceCM();
bool isNearby = distance < 100;
digitalWrite(LED_BUILTIN,isNearby);
if (distance < 80){
digitalWrite(Buzzer, HIGH);
delay(100);
digitalWrite(Buzzer, LOW);
delay(100);
}
else{
digitalWrite(Buzzer, LOW);
}
Serial.print("Jarak = ");
Serial.println(readDistanceCM());
delay(100);
}