#define PIN_ECHO 2
#define PIN_TRIG 3
#define RED_LED 4
#define GREEN_LED 5
#define BUTTON_PIN 6
#define BUZZER_PIN 7
void setup() {
Serial.begin(115200);
pinMode(3, OUTPUT);
pinMode(2, INPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
readDistanceCM();
// Example 1: Switch on a LED with a button press
if (digitalRead(BUTTON_PIN) == LOW) {
digitalWrite(4, HIGH); //RED_LED
} else {
digitalWrite(4, LOW);
}
// Example 2: Switch on a LED and a Buzzer with a button press, off otherwise
if (digitalRead(BUTTON_PIN) == LOW) {
digitalWrite(5, HIGH);
tone(BUZZER_PIN, 1000); // 1000 Hz tone
} else {
digitalWrite(5, LOW); //GREEN_LED
noTone(BUZZER_PIN);
}
// Example 3: Switch on a LED and make the Buzzer sound continuously with a button press, off otherwise
if (digitalRead(BUTTON_PIN) == LOW) {
digitalWrite(5, HIGH);
tone(BUZZER_PIN, 1000); // 1000 Hz tone
} else {
digitalWrite(5, LOW);
noTone(BUZZER_PIN);
}
}
void readDistanceCM() {
// Start a new measurement
digitalWrite(3, HIGH);
delayMicroseconds(10);
digitalWrite(3, LOW);
// Read the result
int duration = pulseIn(PIN_ECHO, HIGH);
int distanceCM = duration / 58;
// Output the distance
Serial.print("Distance in CM: ");
Serial.println(distanceCM);
// Example 4: Indicate through LED ON if the distance is less than 150 cm else LED OFF
if (distanceCM < 150) {
digitalWrite(4, HIGH); //RED_LED
} else {
digitalWrite(4, LOW);
}
// Example 5: Indicate through two LEDs
if (distanceCM < 150) {
digitalWrite(4, HIGH); //RED_LED
digitalWrite(5, LOW);
} else {
digitalWrite(4, LOW);
digitalWrite(5, HIGH); //GREEN_LED
}
}