Ultrasonic sensor is a ranging sensor used to measure the distance of an object. It has a ping emitter and a receiver. Emitter radiates the sound waves. Receiver receives the same. Distance is calculated by measuring the time interval. The formula to find distance is
Distance = time interval * speed of sound waves/2.
Ultrasonic sensor
Connecting wires
Grnd - 0v
Dout - any digital pin
Step 1. Make the connection as specified above.
Step 2: upload the below sketch
Step 3. Open the serial monitor to see the output.
Distance = time interval * speed of sound waves/2.
Components Required:
Arduino boardUltrasonic sensor
Connecting wires
Pin connection.
Vcc- 5vGrnd - 0v
Dout - any digital pin
Step 1. Make the connection as specified above.
Step 2: upload the below sketch
Arduino code
- #define trigPin 13
- #define echoPin 12
- #define led 11
- #define led2 10
- void setup() {
- Serial.begin (9600);
- pinMode(trigPin, OUTPUT);
- pinMode(echoPin, INPUT);
- pinMode(led, OUTPUT);
- pinMode(led2, OUTPUT);
- }
- void loop() {
- long duration, distance;
- digitalWrite(trigPin, LOW); // Added this line
- delayMicroseconds(2); // Added this line
- digitalWrite(trigPin, HIGH);
- // delayMicroseconds(1000); - Removed this line
- delayMicroseconds(10); // Added this line
- digitalWrite(trigPin, LOW);
- duration = pulseIn(echoPin, HIGH);
- distance = (duration/2) / 29.1;
- if (distance < 4) { // This is where the LED On/Off happens
- digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off
- digitalWrite(led2,LOW);
- }
- else {
- digitalWrite(led,LOW);
- digitalWrite(led2,HIGH);
- }
- if (distance >= 200 || distance <= 0){
- Serial.println("Out of range");
- }
- else {
- Serial.print(distance);
- Serial.println(" cm");
- }
- delay(500);
- }
Step 3. Open the serial monitor to see the output.
No comments:
Post a Comment