The Best DIY STEM Tutorials and Projects

Basics of Ultrasonic Sensor

OVERVIEW

Discover how Ultrasonic Sensors work with Arduino! This sensor uses sound waves to measure distance, just like a bat finding its way in the dark. With this project, you can make your Arduino “see” without eyes! 🦇📏🚀

You can follow this video and the instructions below.

Video

Components Required

Here is a list of Components that we will need to make this Project.

Electronic-Dice_Componnets.
Sr #Item NameQuantity
1Arduino Uno1
2Breadboard1
3Ultrasonic sensor1
4Arduino cable1
5M-F Jumper Wires4

Wiring Diagram

Here is a Complete Wiring Diagram along with Instructions for this Project

Electronic-Dice_Circuit-diagram

Program / Code

Code is Explained in the Comments of the Code

const int trigPin = 3;
const int echoPin = 6;
const int distanceThreshold = 5; // cm

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  int distance = calculateDistance();

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  if (distance <= distanceThreshold) {
    Serial.println("Object detected within threshold");
  }

  delay(1000); // Print data every 1 second
}

int calculateDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  int duration = pulseIn(echoPin, HIGH);
  int distance = duration * 0.034 / 2;

  return distance;
}

Thank you so much for going through our tutorial, we hope it was easy to follow and you enjoyed it, please share your feedback and pictures of the project (if you have made it) in the comments below .!

Share your love

Leave a Reply

Your email address will not be published. Required fields are marked *