/**
HC-SR04 Distance Sensor Example
https://wokwi.com/arduino/projects/304444938977804866
*/
#define PIN_TRIG 3
#define PIN_ECHO 2
void setup() {
Serial.begin(115200);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
pinMode(4, OUTPUT);
}
void loop() {
// Start a new measurement:
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// Read the result:
int duration = pulseIn(PIN_ECHO, HIGH);
Serial.print("Distance in CM: ");
Serial.println(duration / 58);
Serial.print("Distance in inches: ");
Serial.println(duration / 148);
int jarak = duration / 58;
if(jarak<=100 && jarak>50)
{
tone(4,500);
delay(500);
noTone(4);
delay(500);
}
else if(jarak<=50)
{
tone(4,400);
delay(200);
noTone(4);
delay(200);
}
else
{
noTone(4);
}
}