2.Ultrasonic With One Led
Ultrasonic With One Led
Materials Needed:
- Arduino board
- Ultrasonic sensor (e.g., HC-SR04)
- Blue LED
- 220Ω resistor
- Jumper wires
- Breadboard (optional)
Connections:
Ultrasonic Sensor to Arduino:
- TRIG pin → Pin 9
- ECHO pin → Pin 10
- VCC pin → 5V
- GND pin → GND
LED to Arduino:
- Connect the anode (longer leg) of the blue LED to Pin 13 through a 220Ω resistor.
- Connect the cathode (shorter leg) to GND.
Procedure:
Connect the Ultrasonic Sensor and LED:
- Use jumper wires to connect the ultrasonic sensor as described above.
- Connect the blue LED to digital Pin 13 using the resistor.
Write the Arduino Code:
- Copy and paste the following code into the Arduino IDE:
C++ Code
const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 13;
int thresholdDistance = 20; // Set the distance threshold in centimeters
void setup() {
Serial.begin(9600); // Start the serial communication at 9600 baud rate
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
long duration;
int distance;
// Send a 10us pulse to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Turn on the LED if the object is closer than the threshold distance
if (distance <= thresholdDistance) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
delay(500); // Wait for a short while before the next measurement
}
Upload the Code:
- Connect the Arduino to your computer using a USB cable.
- Select the appropriate board and port in the Arduino IDE.
- Click the "Upload" button to upload the code to your Arduino.
Open the Serial Monitor:
- Once the code is uploaded, open the Serial Monitor in the Arduino IDE by clicking on Tools > Serial Monitor, or press Ctrl+Shift+M.
- Set the baud rate to 9600.
Observe the Distance Measurements:
- The serial monitor will display the distance readings from the ultrasonic sensor in centimeters.
- The measurements are updated every 500 milliseconds (0.5 seconds).
Explanation:
- The TRIG pin sends a pulse to start measuring distance.
- The ECHO pin receives the reflected pulse, and the time is used to calculate the distance.
- The LED is turned on if the measured distance is less than or equal to the specified threshold (
thresholdDistance
). - The LED remains off if the object is beyond that distance.
Comments
Post a Comment