Пт май 19, 2023 16:08:30
Вс май 21, 2023 22:03:59
// Constants for ultrasound sensor pins
const int trigPin = 2; // Trigger pin of ultrasound sensor
const int echoPin = 3; // Echo pin of ultrasound sensor
// Constants for LED pin
const int ledPin = 13; // Pin connected to the LED
// Constants for distance threshold
const int thresholdDistance = 100; // Threshold distance in mm
// Variables for duration and distance
long duration;
int distance;
void setup() {
// Initialize the LED pin as an output
pinMode(ledPin, OUTPUT);
// Initialize the ultrasound sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Start serial communication
Serial.begin(9600);
}
void loop() {
// Generate ultrasound pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo signal
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in mm
distance = duration * 0.034 / 2;
// Print the distance for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" mm");
// Check if obstacle is closer than the threshold distance
if (distance < thresholdDistance) {
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
digitalWrite(ledPin, LOW); // Turn off the LED
}
// Wait for a short delay before taking the next measurement
delay(100);
}
Make sure you have connected the ultrasound sensor's trigger pin to pin 2, echo pin to pin 3, and the LED to pin 13 on your Arduino board. Upload the code to your Arduino and observe the LED. It will light up if an obstacle is detected closer than 100 mm, based on the readings from the ultrasound sensor.