Mid-Senior Engineers: Reinvent your career with Robotics, earning $100k-$200k+ in the next 90 days. Learn More

IR Sensor vs. Ultrasonic Sensor: What is the difference?

Liz Miller Learn Robotics

About the Author, Liz Miller, Founder/CEO @ Learn Robotics

Liz graduated with a degree in Robotics Engineering from Worcester Polytechnic Institute and researched drones at UPenn's GRASP Lab. Liz is a former Raytheon Engineer, where she managed major $MM automation projects worldwide. Today, she's the driving force behind Learn Robotics, offering the Robotics Career Blueprint for Engineering Professionals and beginner courses through the Online Robotics Class. Liz is a third-generation entrepreneur who is all about the application of innovation in robotics, automation, and AI. Follow Liz on LinkedIn and Facebook.

Disclosure: Some of the links below are affiliate links. This means that, at zero cost to you, Learn Robotics will earn an affiliate commission if you click through the link and finalize a purchase. Learn Robotics is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a way for websites to earn advertising revenues by advertising and linking to Amazon.com.

Join our Private Discord Server, MakeRobots! Sign Up

If you’re looking for a new sensor and you’re not sure which one to purchase, you might be considering the Infrared sensor (IR sensor) vs. the ultrasonic sensor. In this article, we’ll take a look at the IR sensor vs. the Ultrasonic Sensor.

What is the difference, and how do you choose which one to use? In this article, we’ll dive into the world of distance sensors and share a few real-world Arduino project examples you can follow to integrate an IR sensor or Ultrasonic Sensor into your projects.

What is the difference between IR sensors vs. Ultrasonic sensors?

The biggest difference between IR sensor vs. ultrasonic sensors is the way in which the sensor works. Ultrasonic sensors use sound waves (echolocation) to measure how far away you are from an object. On the other hand, IR sensors use Infrared light to determine whether or not an object is present.

Accuracy and reliability are also big differentiators in these sensors. Most often, ultrasonic sensors will provide you more reliable and accurate data than IR sensors. If you want an accurate, numerical representation of distance for your project, I’d almost always choose an Ultrasonic sensor.

However, if you only need to know if an object is present or not, then an IR sensor is easier to implement. Now, let’s talk a little bit more about both of these sensors and their technical specifications.

What are IR Sensors?

IR sensors use an infrared transmitter and receiver to emit and detect objects. Most IR obstacle avoidance sensors are less than $1 each, making them an affordable option for hobby projects. Here’s a close-up of an IR sensor module.

You can adjust the distance on the IR sensor by rotating the potentiometer. This will make the IR sensor more or less sensitive to objects.

IR Sensor with Arduino

Here’s how to connect an IR sensor to an Arduino Uno. The IR sensor has 3 pins: GND, Vcc, and Signal. The signal pin can be connected to a digital or analog pin on the Arduino.

Parts Required

IR Sensor pin diagram (Digital)

If you just want to know if the sensor is active or not, then I recommend using a digital reading. The sensor will read a 1 or 0 if it’s triggered or not.
IR Sensor fritzing diagram Arduino Uno

IR Sensor pin diagram (Analog)

Furthermore, if you want a full 10-bit range of readings, then you’ll want to wire the signal pin on the IR sensor into an analog pin on the Arduino. The sensor will provide a reading in the range of 0-1023 that you can use to make decisions or map the readings to a distance curve.
IR Sensor pin diagram

Code IR Sensor with Arduino

First, wire the IR Sensor to the Arduino. Then upload the IR sensor code example, below.

/*
 * Example code to read an IR sensor with Arduino
 */

int IR = 9;

void setup() {
  // put your setup code here, to run once:
  pinMode(IR, INPUT);
  Serial.begin(9600); //initialize the serial monitor
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalRead(IR);
  Serial.print("IR reading = ");
  Serial.println(IR);
  delay(2000);
}

Enter your email below to download the Arduino Sketch (.ino).

Here’s your download! IR Sensor Example (.ino)

Now, let’s review the code. You’ll start by defining the signal pin that the IR sensor is connected to. Next, declare your pin as an INPUT to the Arduino. We’ll be collecting data from the environment to the controller, which is known as an Input.

Finally, in the loop() method, read the signal pin every three seconds using the analogRead() or digitalRead() command. Open up the Serial Monitor to view the readings from your sensor. Lastly, you can adjust this code to best align with your application.

Applications for IR Sensors

Popular applications for IR sensors include line following (and avoiding) for mobile robots, Tripwires, Flame Detection, and even motion detection (PIR). For flame detection and motion detection, you’ll have to buy a specific flame sensor and PIR sensor, respectively.
detect fire with Arduino

What are Ultrasonic Sensors?

Ultrasonic sensors use soundwaves to transmit and receive information over a duration. The duration is then converted to a distance measurement based on the Speed of Sound (340 m/s). There are ultrasonic sensors at every price point. If you’re looking for something affordable for your hobby project, I recommend the HC-SR04. Here’s a close-up of an ultrasonic sensor module.

how HC-SR04 ultrasonic sensor works

Ultrasonic Sensor with Arduino

Here’s how to connect an ultrasonic sensor to an Arduino Uno. The ultrasonic sensor has two versions: PING (3-pin) or HC-SR04 (4-pin). Both versions have GND and Vcc pins. PING has a dual signal pin that can be used as both an INPUT and an OUTPUT. The HC-SR04 has two separate signal pins: one for the transmitter (Trig) and one for the receiver (Echo). The signal pins are connected to digital pins on the Arduino.

Parts Required

HC-SR04 Ultrasonic Sensor (4-pin)

The HC-SR04 Ultrasonic sensor works with 4 pins: GND, Vcc, Trig (OUTPUT), and Echo (INPUT). Here’s a pin diagram for Arduino using the HC-SR04.

HC-SR04 ultrasonic sensor pin diagram

PING Ultrasonic Sensor (3-pin)

The PING ultrasonic sensor works with 3 pins: GND, Vcc, and Signal. Here’s a pin diagram for Arduino using the PING sensor.
PING ultrasonic sensor pin diagram

Code Ultrasonic Sensor with Arduino

Once you have your sensor wired, you’ll write some code to send out a pulse, calculate the duration, and then convert it to a distance measurement. Here’s some example code for the PING sensor, below.

/*
* Example Code for Parallax PING Sensor
*/
const int sig = 9;

void setup() {
  Serial.begin(9600);
}

void loop() {
  long duration, inches, cm;

  // The PING sensor is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(sig, OUTPUT);
  digitalWrite(sig, LOW);
  delayMicroseconds(2);
  digitalWrite(sig, HIGH);
  delayMicroseconds(5);
  digitalWrite(sig, LOW);

  //read duration from the original pulse
  pinMode(sig, INPUT);
  duration = pulseIn(sig, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(100);
}

long microsecondsToInches(long microseconds) {
  // According to Parallax's datasheet for the PING))), there are 73.746
  // microseconds per inch (i.e. sound travels at 1130 feet per second).
  // This gives the distance travelled by the ping, outbound and return,
  // so we divide by 2 to get the distance of the obstacle.
  // See: https://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the object we
  // take half of the distance traveled.
  return microseconds / 29 / 2;
}

Now, let’s review the code. You’ll start by defining the signal pin(s) that the ultrasonic sensor is connected to. Next, declare your signal (trig) pin as an OUTPUT to the Arduino. Set the pin to LOW for 2 microseconds, then HIGH for 5 microseconds, and then LOW for 2 microseconds. Then, declare the signal pin (echo) as an INPUT and capture the time duration using the pulseIn() method.

Once you have the duration, you’ll need to convert it to a distance. This can be done using the speed of sound conversion factors in inches or centimeters. The datasheet for your sensor should outline these conversion factors. You can adjust this code to best align with your application.

Download both Ultrasonic Sensor Code Examples for Arduino, below.

Here’s your download! Here’s your download!
PING Sensor code (.ino)
>HC-SR04 Sensor code (.ino)

Applications for Ultrasonic Sensors

Mobile Robot Object Avoidance

Ultrasonic sensors are often used on mobile robots to avoid objects. You can use an array of HC-SR04 sensors and determine which way to move depending on which sensor has the highest distance reading. This will tell you that objects are farther away and it’s therefore, safer to move in that direction.

robot tank ultrasonic sensor

Distance or Height Calculations

The HC-SR04 is great for measuring levels. For example, you can determine how much snow is on the ground or the level of a tank.
ultrasonic sensor application tank level

Wrapping Up

In this article, we explored two popular sensors: IR sensor vs. ultrasonic sensor. At this point, you should have a better understanding of what these sensors are used for and how to apply them to your next project.

Are you a beginner to Arduino? Then I recommend checking out my Arduino for Beginners course. It’s designed to get you up-to-speed with all-things Arduino by guiding you through a prototyping project.

If you enjoyed this article, consider sharing it with a friend! And, if you have questions, be sure to comment them below.

Experienced Engineer (Mechanical, Electrical, Computer, Software): If I offered to help you upgrade your engineering career to robotics, earning $100k-$200k+ in the next 90 days, would you take me up on that offer? Click here for details.
Liz Miller Learn Robotics

🚀 Pre-Launch: Become a "MakeR" with MakeRobots!

Hey Reader, 👋

Liz Miller, Founder/CEO, here with some Exciting News!

Learn Robotics just acquired MakeRobots™, an Online Robotics Community, and are prepping its Official Learn Robotics Debut in Late 2023.

MakeRobots™ is your one-stop-shop for learning, gaining coding, electronics, and robotics skills, connecting, and building robots for one low monthly membership!

Join MakeRobots™ at our Special Pre-launch Rate!
🤖 Access our Private Community & Robotics Courses
💬 Network, Collaborate, Connect with Other Makers
🔓 Only $5.99/month – locked in for life
⏱️ Pre-launch deal is Limited to the first 1,000 subscribers

This is a perfect opportunity for you to get into the fastest growing robotics community on the internet, at our ground-level, pre-launch membership rates.

👇 Click the button below to Claim your Pre-launch Membership and become a MakeR in the MakeRobots Community, today!

Learn Robotics Botly Favicon

MORE LEARN ROBOTICS ARTICLES