Showing posts with label Analog. Show all posts
Showing posts with label Analog. Show all posts

Wednesday, October 21, 2026

How to Use the HC-SR04 Ultrasonic Sensor with Arduino: Complete Beginner’s Guide

The HC-SR04 ultrasonic sensor is a popular, affordable component used to measure distance in Arduino projects. It uses ultrasonic sound waves to detect objects without physical contact. This sensor is useful for robotics, obstacle avoidance, parking assistance prototypes, water-level monitoring, and many other DIY electronics projects.

In this guide, you will learn how the HC-SR04 works, how to connect it to an Arduino Uno, and how to write a simple program to measure distance in centimetres.

How to Use HC-SR04.

What Is the HC-SR04 Ultrasonic Sensor?

The HC-SR04 is an electronic distance-measuring module with two round ultrasonic transducers.

  • Transmitter: Sends out an ultrasonic sound pulse.

  • Receiver: Detects the returning echo.

  • Control circuitry: Helps generate the pulse and produce an echo signal for the Arduino to measure.

The sensor typically operates at around 40 kHz, which is above the range of human hearing.

Many HC-SR04 modules specify a nominal measuring range of approximately 2 cm to 400 cm. Actual performance depends on the target, environment, sensor alignment, and module quality.

How Does the HC-SR04 Work?

The sensor measures the time taken for an ultrasonic pulse to travel to an object and return.

The basic process is:

  1. The Arduino sends a short trigger pulse to the sensor’s TRIG pin.

  2. The sensor transmits an ultrasonic burst.

  3. The sound waves reflect from an object.

  4. The sensor’s ECHO pin produces a pulse whose duration represents the round-trip travel time.

  5. The Arduino calculates the distance using the speed of sound.

Because the sound travels to the object and back, the measured time must be divided by two when calculating one-way distance.

The approximate formula at room temperature is:

Distance (cm) = Echo duration (ยตs) × 0.0343 ÷ 2

For example, if the measured echo duration is 1,000 microseconds:

Distance = 1,000 × 0.0343 ÷ 2

Distance ≈ 17.15 cm

This is an approximate result because the speed of sound changes with air temperature.

HC-SR04 Pin Configuration

The standard HC-SR04 module has four pins:

PinFunction
VCCPower supply, typically 5V
TRIGTrigger input
ECHOEcho output
GNDGround

Check the labels on your actual module before connecting it. Pin layouts and markings can vary between products.

How to Connect the HC-SR04 to Arduino Uno

For this example, use an Arduino Uno and the following connections:

HC-SR04 PinArduino Uno
VCC5V
TRIGDigital pin 9
ECHODigital pin 10
GNDGND

Make sure the wiring is secure before powering the circuit.

Important: The standard HC-SR04 ECHO output is typically a 5V logic signal. If you use a 3.3V-only microcontroller, such as many ESP32 boards, use an appropriate voltage divider or logic-level interface on ECHO unless the specific board or module supports 5V input.

Arduino Code for Measuring Distance

Connect the sensor according to the wiring table, then upload this example to your Arduino Uno.

const int trigPin = 9;
const int echoPin = 10;

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

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // Ensure the trigger starts LOW
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Send a 10-microsecond trigger pulse
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the echo pulse, with a timeout
  long duration = pulseIn(echoPin, HIGH, 30000);

  if (duration == 0) {
    Serial.println("No echo detected");
  } else {
    float distance = duration * 0.0343 / 2.0;

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

  delay(500);
}

This program sends a trigger pulse, measures the echo duration, calculates the distance, and prints the result to the Serial Monitor.

The pulseIn() timeout prevents the program from waiting indefinitely when no echo is received.

How to View the Distance Reading

After uploading the code:

  1. Connect the Arduino to your computer using a USB cable.

  2. Open the Arduino IDE.

  3. Select the correct board and COM port.

  4. Open the Serial Monitor.

  5. Set the baud rate to 9600.

  6. Place an object in front of the sensor and observe the readings.

Example output:

Distance: 23.5 cm
Distance: 24.1 cm
Distance: 22.8 cm
Distance: 23.0 cm

These are illustrative readings. Your actual results will depend on the distance, target surface, and surrounding conditions.

Common Applications of the HC-SR04

1. Obstacle Avoidance Robot

A robot can use the sensor to detect objects in front of it and trigger a stop, turn, or avoidance routine.

2. Water-Level Monitoring

The sensor can measure the distance from a fixed mounting point to a water surface. A suitable enclosure and installation are important to protect the electronics from moisture.

3. Parking Assistance Prototype

A project can estimate the distance between a vehicle model and an obstacle, then use LEDs or a buzzer to indicate proximity.

4. Robotics and Automation

The HC-SR04 is useful for learning distance measurement, object detection, and basic automation control.

5. General Distance Measurement

It can measure the distance to suitable objects in science experiments, DIY projects, and educational demonstrations.

Tips for Better Measurement Accuracy

For more reliable readings:

  • Keep the sensor firmly mounted.

  • Aim it directly toward the target.

  • Use a large, reasonably flat target when testing.

  • Avoid soft materials that absorb sound.

  • Be aware that angled surfaces may reflect sound away from the receiver.

  • Allow enough time between measurements to avoid confusing echoes.

  • Consider temperature changes when higher accuracy is required.

The HC-SR04 is not a precision industrial measuring instrument. For demanding environments or high-reliability applications, choose a sensor designed for those requirements.

Troubleshooting Common Problems

Problem: The Serial Monitor always shows zero or no echo.

Check the TRIG and ECHO wiring, power supply, ground connection, and target position. Make sure the correct COM port and baud rate are selected.

Problem: The readings fluctuate.

Try using a larger, flat target, mounting the sensor securely, and taking several readings to calculate an average.

Problem: The sensor does not detect soft or angled objects reliably.

Some materials absorb ultrasonic energy, while angled surfaces may reflect sound away from the receiver. Try a different target orientation.

Problem: The sensor does not work with a 3.3V microcontroller.

Check the module’s voltage requirements and ensure that the ECHO signal is safe for the controller’s input pins.

Conclusion

The HC-SR04 ultrasonic sensor is an accessible way to learn distance measurement with Arduino. With four simple connections and a short program, you can build projects involving obstacle detection, robotics, water-level monitoring, and basic automation.

Once you understand how the trigger pulse, echo duration, and distance formula work together, you can adapt the same principles to more advanced electronics projects.

Explore more electronics parts and project ideas with MY CREATIVE ENGINEERING — Your Electronics Parts & Projects Partner.

Follow us for more practical electronics tutorials, component guides, and automation projects.

Monday, July 21, 2025

LED Auto ON/OFF Using LDR and Arduino | Light Sensor Project for Beginners

Have you ever wanted a light that turns ON automatically when it’s dark and OFF when it’s bright? In this beginner-friendly project, we’ll show you how to build a simple light-sensitive LED control system using an Arduino and an LDR (Light Dependent Resistor) module.

Simple LED Auto ON/OFF

๐Ÿ“ฆ What You’ll Need

To get started, you will need the following components:

Components required for this tutorial

✅ Arduino UNO × 1
✅ 3-pin LDR Module × 1
✅ Jumper Wires × 1
✅ USB cable for Arduino × 1
✅ Resistor 220ฮฉ × 1
✅ Breadboard × 1

๐Ÿ› ️ Circuit Wiring

Here’s how to connect each component to the Arduino:

3-pin LDR module wiring

3-pin LDR Module 
✅ VCC → 5V on Arduino
✅ GND → GND on Arduino
✅ A0 → Analog pin A0 on Arduino

LED and resistor wiring

LED and Resistor
✅ LED Anode (long leg) → Digital pin 9 on Arduino
✅ LED Cathode (short leg) → 220ฮฉ resistor → GND on Arduino

The connection between components and Arduino

๐Ÿ’ป Uploading the Code

After wiring everything up, connect the Arduino to your computer using a USB cable.  Then, upload the following code, or you can download the code HERE.
int ldrPin = A0;
int ledPin = 9;
int threshold = 500;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int ldrValue = analogRead(ldrPin);
  Serial.println(ldrValue);

  if (ldrValue < threshold) {
    digitalWrite(ledPin, HIGH);  // It's dark, turn on LED
  } else {
    digitalWrite(ledPin, LOW);   // It's bright, turn off LED
  }

  delay(200);
}

Open Arduino IDE and copy-paste the code

The value 500 is the light threshold. You can check the actual LDR readings via the Serial Monitor and adjust this number depending on your room lighting conditions.

๐Ÿงช Test the System

In low light, the LED should turn ON.

In bright light, the LED should turn OFF.

๐Ÿ“Œ Conclusion

This project is a simple yet powerful introduction to sensor-based automation using Arduino. By combining a Light Dependent Resistor (LDR) with an LED, you’ve created a system that can react to ambient light—automatically turning the light ON in the dark and OFF in bright conditions.

๐ŸŽฅ Watch the Full Video Tutorial


๐Ÿ”” If you found this guide helpful, share it with fellow makers! For more tutorials, subscribe to our YouTube channel and follow us on social media. ๐Ÿš€

#Arduino #DIYElectronics #LDREngineering #SmartLighting #BeginnerProject #IoT #Maker

Tuesday, October 3, 2017

Arduino : Analog - Smoothing

Description
Reads repeatedly from an analog input, calculating a running average and printing it to the computer. Keeps ten readings in an array and continually averages them.

List Item
  1. Arduino Uno 
  2. Potentiometer
  3. Wire jumper

Wiring Diagram

Video

Arduino : Analog - Fading

Description
This example shows how to fade an LED using the analogWrite() function.

List Item
  1. Arduino Uno 
  2. LED
  3. 1 Resistor (150 ohm to 330 ohm) 
  4. Wire jumper

Wiring Diagram

Video

Arduino : Analog - Calibration

Description
Demonstrates one technique for calibrating sensor input. The sensor readings during the first five seconds of the sketch execution define the minimum and maximum of expected values attached to the sensor pin.

The sensor minimum and maximum initial values may seem backwards. Initially, you set the minimum high and listen for anything lower, saving it as the new minimum. Likewise, you set the maximum low and listen for anything higher as the new maximum.

List Item
  1. Arduino Uno 
  2. LED
  3. 1 Resistor (150 ohm to 330 ohm) and 1 Resistor (10k ohm)
  4. Potentiometer
  5. Wire jumper

Wiring Diagram

Video

Arduino : Analog - Analog Input

Description
Demonstrates analog input by reading an analog sensor on analog pin 0 and turning on and off a light emitting diode(LED)  connected to digital pin 13. The amount of time the LED will be on and off depends on the value obtained by analogRead().

List Item
  1. Arduino Uno 
  2. LED
  3. 1 Resistor (150 ohm to 330 ohm) and 1 Resistor (10k ohm)
  4. Potentiometer
  5. Wire jumper

Wiring Diagram

Video

Arduino : Analog - Analog In Out Serial

Description
Reads an analog input pin, maps the result to a range from 0 to 255 and uses the result to set the pulsewidth modulation (PWM) of an output pin. Also prints the results to the serial monitor.

List Item
  1. Arduino Uno 
  2. LED
  3. 1 Resistor (150 ohm to 330 ohm) and 1 Resistor (10k ohm)
  4. Potentiometer
  5. Wire jumper

Wiring Diagram

Video