PSoC5LP Lab 04: Ultrasonic Module HC-SR04

HC SR04 UltrasonicRangeFinder

Objective

  • Measure distance using the HC-SR04 ultrasonic sensor.
  • Understand the principles of ultrasonic echo-ranging.

Overview

Ultrasonic Module in Embedded Systems

Ultrasonic modules are commonly used in embedded systems for measuring distance, object detection, and other non-contact sensing applications. These modules leverage ultrasonic waves, which are sound waves with frequencies higher than the upper audible limit of human hearing, typically above 20 kHz. This background will cover ultrasonic theory, the working principle of ultrasonic modules, common types of ultrasonic sensors, and their applications in embedded systems.

Ultrasonic Theory

Ultrasonic waves are mechanical vibrations that propagate through a medium (such as air, water, or solid objects) in sound waves with frequencies beyond the human hearing range. Ultrasonic waves can be reflected, refracted, or absorbed depending on the material they interact with, making them useful for various sensing applications.

Key Characteristics:

  • Frequency Range: Ultrasonic waves are typically those above 20 kHz, but industrial applications often use frequencies between 40 kHz and 400 kHz.
  • Velocity of Sound: The speed at which ultrasonic waves travel through a medium depends on the medium's physical properties (density, temperature, etc.). For example, the speed of sound in air at 20°C is approximately 343 meters per second (m/s).
  • Reflection: Ultrasonic waves reflect off surfaces, and the time taken for the wave to return can be used to calculate the distance of an object.
  • Wavelength: The wavelength of the ultrasonic wave determines its ability to detect small objects; higher frequencies have shorter wavelengths, which allows for the detection of smaller objects.

Working Principle of Ultrasonic Modules

In embedded systems, ultrasonic modules generally function by emitting an ultrasonic pulse and then measuring the time it takes for the echo to return after hitting an object (echo-ranging technique). The time-of-flight (TOF) of the sound wave is used to calculate the distance to the object.

Working Steps:

  1. Emission of Ultrasonic Pulse: The module sends out a short burst of ultrasonic waves (often 40 kHz) using a piezoelectric transducer.
  2. Wave Propagation: The waves travel through the air, reflecting off any object in their path.
  3. Echo Reception: The transducer switches to "receive" mode and detects the reflected waves (echo).
  4. Time Measurement: The embedded system records the time interval between the pulse's emission and the echo's reception.
  5. Distance Calculation: Based on the speed of sound and the time delay, the distance to the object can be calculated using the formula:
    \(Distance = {{Speed Of Sound \times Time Of Flight} \over 2}\)
    The division by 2 accounts for the wave traveling to the object and back.

Ultrasonic diagram 01

Common Components:

  • Transmitter and Receiver: In some modules, there are separate units for transmission and reception, while in others, a single transducer is used for both purposes.
  • Signal Processor: Embedded systems usually include a microcontroller to process the received signal and calculate the distance.
  • Voltage Regulator: To ensure stable operation, modules often include a voltage regulator.

Common Ultrasonic Module: HC-SR04

One of the most commonly used ultrasonic modules in embedded systems is the HC-SR04. It operates at a frequency of 40 kHz and can measure distances from 2 cm to 400 cm with an accuracy of about 3 mm.

Applications of Ultrasonic Modules in Embedded Systems

Ultrasonic modules are widely used in various applications in embedded systems. Their ability to measure distance, detect objects, and work in various environmental conditions makes them versatile. Here are some key applications:

Distance Measurement

Ultrasonic modules are primarily used to measure distances in embedded systems. Typical applications include:

  • Obstacle Detection in Robotics: Robots often use ultrasonic sensors to detect obstacles in their path, allowing them to navigate safely.
  • Parking Assistance Systems: Cars use ultrasonic sensors in parking assistance systems to detect nearby objects and provide alerts to drivers.
  • Level Sensing: Ultrasonic modules measure the level of liquids or solids in tanks by calculating the distance from the sensor to the material's surface.

Object Detection

The ability of ultrasonic sensors to detect objects makes them valuable in a range of industries:

  • Security Systems: Ultrasonic modules are used in intrusion detection systems to detect unauthorized access in secured areas.
  • Industrial Automation: Automated manufacturing systems use ultrasonic modules to detect the presence of parts or obstacles on conveyor belts.
  • Agriculture: In agricultural robots, ultrasonic sensors can help detect objects such as plants, animals, or farm machinery.

Proximity Sensing

Ultrasonic sensors are widely used for proximity detection in various embedded applications:

  • Mobile Devices: Some smartphones use ultrasonic sensors for proximity detection, such as turning off the display during a call when the phone is near the user's ear.
  • Touchless Switches: Ultrasonic sensors enable touchless activation of smart home systems' lights, doors, or appliances by detecting hand movements within a specific range.

Autonomous Vehicles

In autonomous vehicles (drones, self-driving cars), ultrasonic sensors assist in obstacle avoidance, especially in close-range scenarios. These sensors work alongside other technologies like cameras and LIDAR to ensure the vehicle's environment is accurately mapped and navigated.

Medical Applications

Ultrasound technology is also applied in medical devices for non-invasive diagnostics, imaging (such as ultrasound scans), and therapy. While not directly related to embedded systems, ultrasound imaging relies on the same principles of ultrasonic wave propagation and reflection.

Advantages and Limitations of Ultrasonic Modules

Advantages:

  • Non-Contact Measurement: Ultrasonic modules can measure distance and detect objects without physical contact, reducing wear and tear.
  • Works in All Lighting Conditions: Unlike infrared sensors, ultrasonic sensors are not affected by lighting conditions, making them suitable for outdoor applications.
  • Wide Range of Applications: Ultrasonic sensors can work in various media, such as air, water, and even certain solids.
  • High Accuracy: Ultrasonic modules provide accurate measurements, typically within a few millimeters for common modules like the HC-SR04.

Limitations:

  • Environmental Sensitivity: The performance of ultrasonic modules can be affected by environmental conditions such as temperature, humidity, and wind, which influence the speed of sound.
  • Limited Detection Range: Ultrasonic modules typically have a limited range (up to several meters), which may not be sufficient for some applications.
  • Surface Limitations: Some surfaces (e.g., soft materials) absorb sound rather than reflect it, leading to inaccurate readings.
  • Beam Divergence: The sound beam emitted by an ultrasonic sensor can spread out, which might cause issues in detecting small or narrow objects.

Ultrasonic modules are crucial in embedded systems, offering reliable and accurate distance measurement and object detection. The versatility of these sensors, combined with their ability to operate in various environments and detect a wide range of materials, makes them invaluable in fields ranging from robotics and automation to automotive and medical applications. Developers can build multiple applications that enhance automation, safety, and convenience by understanding ultrasonic theory and leveraging the technology in embedded systems.

Required Reading Material

Required Components

NTC Thermistor s HC-SR04 Ultrasonic Module × 1
CharacterLcdDisplay s Character LCD Module × 1
Potentiometer 10K s 10 KΩ Potentiometer × 1

Circuit / Schematic

  • Connection for Character LCD Module
    LCDConnection
  •  Connection for HC-SR04 Ultrasonic module
    Schematic 01

Procedure

Creating a New Project

  1. Launch PSoC Creator.
  2. Got to File ➤ Open Project ➤ Project/Workspace.
  3. Open the PSoC5LP workspace in the EE4450 folder.
  4. After PSoC Creator opens the workspace, right-click on Workspace 'PSoC5LP' in the Workspace Explorer and select Add ➤ New Project...
  5. Select the correct PSoC5LP device model number, use the "Empty schematic" template, and enter the project name 04_Ultrasonic.

Adding PSoC Creator Components

Follow these detailed steps to add components to the PSoC Creator project by modifying the TopDesign.cysch schematic file::

  1. Add a Character LCD component:
    • Navigate to the Display catalog in the component selection panel.
    • Drag and drop the Character LCD onto the schematic.
  2. Add a Timer component:
    • Navigate to the Digital ➤ Functions catalog in the component selection panel.
    • Drag and drop the Timer onto the schematic.
  3. Add a Digital Input Pin:
    • Navigate to the Ports and Pins catalog in the component selection panel.
    • Drag and drop the Digital Input Pin onto the schematic.
  4. Add a Digital Output Pin:
    • Similarly, go to the Ports and Pins catalog.
    • Drag and drop the Digital Output Pin onto the schematic.
  5. Add a Control Register:
    • Navigate to the Digital ➤ Registers catalog in the component selection panel.
    • Drag and drop the Character LCD onto the schematic.

Following these steps, you will successfully add a Character LCD, Timer, Digital Input Pin, Digital Output Pin, and Control Register component to the schematic in PSoC Creator.

Lab04 TopDesign Original s

Configure the Components

  1. Config the Digital Input Pin (Pin_1):
    • Click on the Pin_1 component in the schematic.
    • Rename the component to Echo to reflect its connection to the ultrasonic's echo pin.
      DigitalInputPin Echo s
  2. Config the Digital Output Pin (Pin_2):
    • Click on the Pin_2 component in the schematic.
    • Rename the component to Trig to represent its connection to the ultrasonic sensor's trig pin.
    • Uncheck the box for ☐ HW connection to disable the hardware connection. This step ensures that the pin will be controlled manually in the software.
      DigitalInputPin Trig s
  3. Config the Timer (Timer_1):
    • Click on the Timer_1 component in the schematic.
    • Rename the component to TimerCapture.
    • Change the Implementation to UDB (Universal Digital Block).
    • Select the Resolution to 24-bit.
    • Click the Max button to set the maximum period value automatically.
    • Set the Trigger Mode to Rising Edge. This setting ensures that the timer starts on a rising signal edge.
    • Set the Capture Mode to Falling Edge, which ensures that the timer captures values when the falling edge of the signal occurs.
    • Change the Run Mode to the One Shot. This mode ensures that the timer runs once per trigger event, capturing a single measurement
      Timer TimerCapture s
  4. Config the Control Register (Control_Reg_1):
    • Click on the Control_Reg_1 component in the schematic.
    • Rename the component to TimerCapture_Reset.
    • Change the Outputs to 1.
    • Change the Initial value to 1. This ensures the reset control register is initialized properly.
      ControlRegister TimerCapture Reset s
  5. Config the Character LCD (LCD_Char_1):
    • Click on the LCD_Char_1 component in the schematic.
    • Rename the component to LCD for clarity and ease of identification.
      CharacterLCD LCD s

Wiring

  1. Delete the existing Logic 0 component connected to the TimerCapture module's reset pin. Delete this Logic 0 component to allow for a new connection.
  2. Connect a wire from the control_0 pin on the TimerCapture_Reset module to the reset pin of the TimerCapture module. This will enable the reset functionality to be controlled by the TimerCapture_Reset module.
  3. Connect the input Echo pin to the capture and trigger pins of the TimerCapture module. This will allow the TimerCapture module to detect the trigger signal and capture the timing based on the echo response.
  4. A detailed connection diagram illustrating the wiring setup, including the reset connection and pin wiring, is provided below. Use this diagram to verify your connections and ensure everything is correctly wired according to the system design.
    Lab04 TopDesign Final s

Pin Assignment

DevicePort.PinDirectionDrive Mode

Template Firmware Code


#include "project.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>

float measureDistance();

int main(void)
{
    float distance_cm;

    CyGlobalIntEnable; /* Enable global interrupts. */

    /* Place your initialization/startup code here (e.g. MyInst_Start()) */
    TimerCapture_Start();
    TimerCapture_Reset_Write(1);
    Trig_Write(0);

    LCD_Start();
    LCD_ClearDisplay();
    LCD_Position(0,0);
    LCD_PrintString("EE4450 PSoC5LP");
    LCD_Position(1,0);
    LCD_PrintString("Ultrasonic");
    CyDelay(2000);              // Delay for 2 second

    for(;;)
    {
        /* Place your application code here. */
        distance_cm = measureDistance();
        if (measureDistance < 0) {
            // Display out of range on the LCD screen

        } else {
            // Display the distance on the LCD screen

        }
    }
}
//------------------------------------------------------------------------------
float measureDistance()
{
    float distance_cm;
    float pw;

    return distance_cm;
}
/* [] END OF FILE */

Exercises

© 2024 Air Supply Information Center (Air Supply BBS)