// LAB 3 ; TASK 2 ; ADRIANA SARAH BINTI AHMAD FAIZA ; 52224123439
int trigPin = 9;
int echoPin = 10;
int buzzerPin = 11;
int distanceThreshold = 80; // distance threshold in cm
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// generate ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// read the echo pulse
long duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
int distance = duration * 0.034 / 2;
// print distance to serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// check if distance is below threshold and control the buzzer
if (distance < distanceThreshold) {
tone(buzzerPin, 2000);
} else {
noTone(buzzerPin);
}
delay(100);
}