- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
Description of the Arduino Ultrasonic Distance Sensor with LED Code
This Arduino code interfaces an ultrasonic distance sensor with an Arduino Uno to detect nearby objects and control an LED based on the detected distance. The code defines three pins: trigPin (to trigger the ultrasonic pulse), echoPin (to receive the reflected pulse), and ledPin (to control an LED). A distance threshold of 50 cm is set, which can be adjusted according to your needs.
In the setup()
function, the pin modes are initialized, and the Serial Monitor is started for debugging purposes. The program continuously triggers the ultrasonic sensor to send out a pulse and measures the duration of the received pulse to calculate the distance to the nearest object in centimeters.
In the loop()
function, if an object is detected within the specified threshold distance, the LED is turned on, and a message is printed to the Serial Monitor. If no object is detected or it is beyond the threshold, the LED is turned off. A short delay is included to prevent overwhelming the sensor with frequent readings.
This project is a great introduction to using ultrasonic sensors and controlling output devices with Arduino, making it suitable for beginners interested in electronics and programming.
SCHEMATIC:

CODE:
// Define pin connections
const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 8;
// Set a distance threshold for detecting movement (in cm)
const int movementThreshold = 50; // Adjust this to your desired distance
void setup() {
// Initialize pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
// Start Serial Monitor for debugging
Serial.begin(9600);
Serial.println("Starting distance sensor...");
}
void loop() {
// Trigger the sensor to send out a pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse
long duration = pulseIn(echoPin, HIGH);
// Calculate distance (in cm)
int distance = duration * 0.034 / 2;
// Print distance to Serial Monitor for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if an object is within the threshold distance
if (distance > 0 && distance <= movementThreshold) {
Serial.println("Object detected within range. Turning LED on.");
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
Serial.println("No object detected or out of range. Turning LED off.");
digitalWrite(ledPin, LOW); // Turn off the LED
}
// Delay to avoid overwhelming the sensor
delay(200);
}
Comments
Post a Comment