const int trigPin = 9; // Trigger pin of the ultrasonic sensor
const int echoPin = 10; // Echo pin of the ultrasonic sensor
const int ledPin = 11; // LED pin
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
int distance = duration * 0.034 / 2;
int blinkInterval = map(distance, 0, 200, 50, 500); // Adjust the range of the distance values to the desired LED blink interval range
digitalWrite(ledPin, HIGH);
delay(blinkInterval/2);
digitalWrite(ledPin, LOW);
delay(blinkInterval/2);
Serial.print("Distance: ");
Serial.print(distance);
Serial.print("cm");
Serial.print("\t");
Serial.print("Blink interval: ");
Serial.print(blinkInterval);
Serial.println("ms");
}
This code uses the pulseIn() function to measure the duration of the sound wave returned by the ultrasonic sensor and calculates the distance based on the speed of sound. It then maps the distance values to the desired LED blink interval range using the map() function and blinks the LED with the corresponding interval. The Serial commands are optional and are used for debugging purposes. You can adjust the pins and ranges to suit your needs.