What is Ultrasonic Sensor |How to Use it with ESP32 for water level controller?

What is Ultrasonic Sensor|How to Use it with ESP32?


Ultrasonic sensors are a type of sensor that use sound waves to detect the presence and distance of objects. They emit high-frequency sound waves that bounce off objects and are then detected by the sensor. By measuring the time it takes for the sound waves to bounce back, the sensor can determine the distance to the object. Ultrasonic sensors are commonly used in a wide range of applications, including object detection, distance measurement, flow measurement, positioning, collision avoidance, medical imaging, and cleaning applications. They offer a number of advantages, such as high accuracy, low cost, and ease of integration, but also have some limitations, such as limited range in certain environments and limited resolution compared to other types of sensors. Overall, ultrasonic sensors are a versatile and reliable sensing solution, and are widely used across many different industries.

What is Ultrasonic Sensor?

An ultrasonic sensor is a type of sensor that uses sound waves to detect the presence and distance of objects. It works by emitting high-frequency sound waves (typically in the range of 20 to 200 kHz) from a transducer, and then measuring the time it takes for the sound waves to bounce back to the sensor after reflecting off an object. The sensor then calculates the distance based on the time it took for the sound waves to return.

Ultrasonic sensors are commonly used in applications such as object detection, distance measurement, and obstacle avoidance. They are often found in robotics, automation, and automotive industries, as well as in home security systems and medical devices.

There are several types of ultrasonic sensors available, including single transducer sensors and dual transducer sensors. Single transducer sensors emit and receive sound waves from the same transducer, while dual transducer sensors use separate transducers for emitting and receiving sound waves. Dual transducer sensors are generally more accurate and reliable, but also more expensive.

How Ultrasonic Sensors work?

Ultrasonic sensors work by emitting high-frequency sound waves and then detecting the echo that bounces back from nearby objects. Here's a more detailed explanation of how ultrasonic sensors work:

The ultrasonic sensor emits a burst of high-frequency sound waves, typically in the range of 20 to 200 kHz. These sound waves are emitted by a transducer, which converts electrical energy into mechanical energy in the form of sound waves.

The sound waves travel through the air and bounce off any nearby objects. The sound waves that bounce back are called echoes.

The ultrasonic sensor then listens for these echoes using the same transducer that emitted the sound waves. The transducer now acts as a receiver, converting the mechanical energy of the echoes back into electrical energy.

The time it takes for the sound waves to travel from the sensor to the object and back is measured. This time can be used to calculate the distance to the object using the speed of sound in air (approximately 343 meters per second at room temperature).

The distance measurement is then processed by a microcontroller or other electronic circuitry, which can trigger an alarm, activate a motor, or perform other actions based on the detected distance.

The ultrasonic sensors are a simple but effective way to detect the presence and distance of objects using sound waves. They are widely used in applications such as parking sensors, level sensors, robotics, and security systems.

Advantages of using ultra sonic sensor

There are several advantages to using ultrasonic sensors, including:

  1. Non-contact: Ultrasonic sensors can detect objects without physically touching them, which makes them ideal for applications where contact might cause damage or be undesirable.
  2. Wide detection range: Ultrasonic sensors can detect objects at distances ranging from a few centimeters to several meters, depending on the model and frequency used.
  3. High accuracy: Ultrasonic sensors are capable of measuring distance with high accuracy, typically within a few millimeters.
  4. Versatility: Ultrasonic sensors can be used in a wide range of applications, including object detection, distance measurement, level sensing, and flow measurement.
  5. Immunity to color and transparency: Ultrasonic sensors can detect objects regardless of their color or transparency, which makes them useful in applications where other types of sensors might be affected by these factors.
  6. Low power consumption: Ultrasonic sensors consume relatively little power, which makes them suitable for battery-powered applications.
  7. Reliability: Ultrasonic sensors are robust and can operate in harsh environments without being affected by factors such as dust, humidity, or temperature.

Ultrasonic sensors offer a reliable and versatile solution for many sensing applications, and their non-contact nature, wide detection range, and high accuracy make them ideal for a range of different use cases.

Limitations of ultrasonic sensor

While ultrasonic sensors have many advantages, they also have some limitations, including:

  1. Limited detection in certain materials: Ultrasonic sensors have difficulty detecting objects that are made of soft, porous, or absorbent materials, such as cloth, foam, or some plastics, as the sound waves can be absorbed or scattered by these materials.
  2. Limited resolution: While ultrasonic sensors can detect distance with high accuracy, their resolution is limited by the frequency of the sound waves used. Higher frequency sound waves can provide better resolution, but are more easily absorbed or scattered by materials.
  3. Limited range in air: Ultrasonic sensors are most effective at detecting objects in air, but their range can be limited in humid or dusty environments where the sound waves can be absorbed or scattered by the particles in the air.
  4. Limited range in liquids: Ultrasonic sensors are also used for level measurement in liquids, but their range can be limited by the acoustic properties of the liquid and the container it is in.
  5. Interference with other ultrasonic sensors: If multiple ultrasonic sensors are used in the same environment, they can interfere with each other's signals, which can lead to false readings or reduced accuracy.
  6. Angle of incidence: Ultrasonic sensors require a direct line of sight to the object being measured, and the angle of incidence of the sound waves can affect their accuracy.
  7. Ultrasonic sensors are a reliable and versatile sensing solution, but their limitations need to be taken into account when designing and implementing a sensing system.

Compare Ultrasonic Sensors with other Sensors

Ultrasonic sensors are often compared to other types of sensors, such as infrared sensors, laser sensors, and radar sensors. Here are some of the key differences between ultrasonic sensors and these other sensor types:

Infrared sensors: Infrared sensors use infrared radiation to detect the presence of objects. While infrared sensors are inexpensive and widely available, they have a limited range and can be affected by factors such as ambient temperature and the reflectivity of the object being detected. Ultrasonic sensors, on the other hand, can detect objects at greater distances and are less affected by environmental factors.

Laser sensors: Laser sensors use laser beams to detect the presence and distance of objects. While laser sensors are highly accurate and can detect objects with very high resolution, they are also expensive and can be difficult to integrate into systems due to their complexity. Ultrasonic sensors, on the other hand, are less expensive and easier to integrate, but have lower resolution and accuracy compared to laser sensors.

Radar sensors: Radar sensors use radio waves to detect the presence and distance of objects. While radar sensors are highly accurate and can detect objects at very long distances, they are also complex and expensive. Ultrasonic sensors are more affordable and easier to integrate, but have a shorter range and lower accuracy compared to radar sensors.

In general, the choice of sensor will depend on the specific requirements of the application, such as the range and accuracy required, the environmental factors that will be present, and the budget available. Ultrasonic sensors offer a good balance of cost, accuracy, and ease of use, and are suitable for a wide range of applications.

Applications of Ultrasonic Sensors

Ultrasonic sensors are used in a wide range of applications across many different industries. Here are some common applications of ultrasonic sensors:

Object detection: Ultrasonic sensors can detect the presence of objects, and are commonly used in industrial automation, robotics, and security systems.

Distance measurement: Ultrasonic sensors can accurately measure the distance between the sensor and an object, making them useful in applications such as parking sensors, level sensors, and material handling.

Flow measurement: Ultrasonic sensors can be used to measure the flow rate of liquids and gases, and are commonly used in the oil and gas industry, as well as in water treatment and environmental monitoring.

Positioning: Ultrasonic sensors can be used to determine the position of objects, and are commonly used in position control systems for robots and other machines.

Collision avoidance: Ultrasonic sensors are commonly used in automotive and mobile robot applications to detect obstacles and prevent collisions.

Medical applications: Ultrasonic sensors are used in medical imaging, such as ultrasound machines used for prenatal imaging and other diagnostic purposes.

Level measurement: Ultrasonic sensors are used to measure the level of liquids in tanks and other containers, and are commonly used in industrial and environmental applications.

Cleaning applications: Ultrasonic sensors are used in cleaning applications, such as ultrasonic cleaning baths, where they help to improve the cleaning efficiency and effectiveness.

The ultrasonic sensors are a versatile and reliable sensing solution, and their wide range of applications makes them useful in many different industries and contexts.

Example code for using Ultrasonic Sensor with ESP32 for water level controller Application using Wokwi Simulator


Water Level controller using ESP32

Code

#define PIN_TRIG 26
#define PIN_ECHO 25
#define LOWLED   18
#define MIDLED   19
#define HIGHLED  21
#define MOTOR    27

unsigned int level = 0;

void setup() {

  pinMode(LOWLED,OUTPUT);
  pinMode(MIDLED,OUTPUT);
  pinMode(HIGHLED,OUTPUT);
  pinMode(MOTOR,OUTPUT);
  digitalWrite(LOWLED,HIGH);
  digitalWrite(MIDLED,HIGH);
  digitalWrite(HIGHLED,HIGH);
  digitalWrite(MOTOR,LOW);

  Serial.begin(115200);
  pinMode(PIN_TRIG, OUTPUT);
  pinMode(PIN_ECHO, INPUT);
}

void loop() {
  // Start a new measurement:
  digitalWrite(PIN_TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(PIN_TRIG, LOW);

  // Read the result:
  int duration = pulseIn(PIN_ECHO, HIGH);
  Serial.print("Distance in CM: ");
  Serial.println(duration / 58);
  Serial.print("Distance in inches: ");
  Serial.println(duration / 148);
 
  level = duration / 58;

  if (level < 100)
  {

        digitalWrite(LOWLED,LOW);
        digitalWrite(MOTOR,HIGH);
        digitalWrite(HIGHLED,HIGH);
        digitalWrite(MIDLED,HIGH);

  }
  else if ((level > 200) && (level <400))
  {
        digitalWrite(LOWLED,HIGH);
        digitalWrite(HIGHLED,HIGH);
        digitalWrite(MIDLED,LOW);

  }
  else if (level >= 400 )
  {
        digitalWrite(HIGHLED,LOW);
        digitalWrite(MIDLED,HIGH);
        digitalWrite(LOWLED,HIGH);
        digitalWrite(MOTOR,LOW);

  }
  delay(1000);
}


MicroPython Code to Integrate ultrasonic Water level Controller with Home Assistant|Wokwi Simulator


import network
import time
from machine import Pin
import ujson
from umqtt.simple import MQTTClient

from machine import Pin, time_pulse_us
from time import sleep_us, sleep

SSID = "SSID of WIFI Network"
PASSWORD = "Password of WIFI Network"

# MQTT Server Parameters
MQTT_CLIENT_ID = "Mqtt"
MQTT_BROKER    = "broker.mqttdashboard.com";#"broker.emqx.io"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "status/out"

# Define the GPIO pin numbers for the trigger and echo pins
ECHO_PIN = 25
TRIGGER_PIN = 26

LOWLED = 18
MIDLED = 19
HIGHLED = 21
MOTOR = 27


# Initialize trigger and echo pins
trigger = Pin(TRIGGER_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)

lowLed = Pin(LOWLED, Pin.OUT)
midLed = Pin(MIDLED, Pin.OUT)
highLed = Pin(HIGHLED, Pin.OUT)

motor = Pin(MOTOR, Pin.OUT)
motorStatus = "OFF"

lowLed(1)
midLed(1)
highLed(1)
motor(0)

def initWifi():
   
    print("Connecting to WiFi", end="")
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    #sta_if.connect(SSID, PASSWORD)
    sta_if.connect('Wokwi-GUEST', '')
    while not sta_if.isconnected():
        print(".", end="")
        time.sleep(0.1)
    print(" Connected!")


def measure_distance():

    # Ensure trigger is low initially
    trigger(0)
    sleep_us(2)

    # Send a 10 microsecond pulse to the trigger pin
    trigger(1)
    sleep_us(10)
    trigger(0)

   # Measure the duration of the echo pulse (in microseconds)
    pulse_duration = time_pulse_us(echo, 1)
    distance = pulse_duration / 58;

    return distance

def on_message(topic, message):
    #print("received message: " ,str(message.payload.decode("utf-8")))
    global motorStatus
    print("received message: " ,topic, message)
    if (topic == b'status/in') & (message == b'ON'):

        motor(1)
        motorStatus = "ON"
        print("ON")


    elif (topic == b'status/in') & (message == b'OFF'):
       
        motor(0)
        motorStatus = "OFF"
        print("OFF")


def main():
       global motorStatus
       level = "LOW"
       motorStatus = "OFF"
       initWifi()
       #connectMqtt()
       print("Connecting to MQTT server... ", end="")
       client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER,port=1883, user=MQTT_USER, password=MQTT_PASSWORD)
       client.connect()
       print("Connected!")
       client.set_callback(on_message)
       client.subscribe("status/in")
       #

       while True:
           
            # Measure the distance and print the value in centimeters
            client.check_msg()
            distance = measure_distance()
            print("Distance: cm",int(distance))

            if (distance < 150):

                lowLed(0)
                level = "LOW"
                motorStatus = "ON"
                midLed(1)
                highLed(1)
                motor(1)

            elif ((distance > 160) & (distance < 400)):
               
                level = "MIDDLE"
                #motorStatus = "ON"
                lowLed(1)
                midLed(0)
                highLed(1)
                #motor(1)

            elif (distance >= 400 ):

                level = "HIGH"
                lowLed(1)
                midLed(1)
                highLed(0)
                motor(0)
                motorStatus = "OFF"
           
            message = ujson.dumps({
            "WaterLevel": level,
            "MotorStatus": motorStatus,
            })
           
            client.publish(MQTT_TOPIC, message,True)
            print("WaterLevel",level)
            print("MotorStatus",motorStatus)
# Wait for 1 second before taking the next measurement
            sleep(2)

if __name__ == "__main__":
    main()

Configuration Yaml file for Home Assistant Integration


# Loads default set of integrations. Do not remove.
default_config:

# Load frontend themes from the themes folder
frontend:
  themes: !include_dir_merge_named themes

# Text to speech
tts:
  - platform: google_translate

automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml

# Example configuration.yaml entry
mqtt:
  sensor:
    - name: "Water level"
      state_topic: "status/out"
      #unit_of_measurement: "C"
      value_template: "{{ value_json.WaterLevel }}"


    - name: "Pump"
      state_topic: "status/out"
      #unit_of_measurement: "%"
      value_template: "{{ value_json.MotorStatus }}"

  switch:
    - name: "Switch"
      command_topic: "status/in"
      #unit_of_measurement: "%"
      payload_on: "ON"
      payload_off: "OFF"


Diagram.json Code  for Wokwi simulator


{
  "version": 1,
  "author": "Name",
  "editor": "wokwi",
  "parts": [
    {
      "type": "wokwi-esp32-devkit-v1",
      "id": "esp1",
      "top": 9.500000000114,
      "left": 91.000000000114,
      "attrs": {}
    },
    {
      "type": "wokwi-hc-sr04",
      "id": "ultrasonic1",
      "top": -3.2999999998860012,
      "left": -143.299999999886,
      "attrs": { "distance": "2" }
    },
    {
      "type": "wokwi-led",
      "id": "led1",
      "top": 25.200000000114,
      "left": 250.200000000114,
      "attrs": { "color": "red" }
    },
    {
      "type": "wokwi-led",
      "id": "led2",
      "top": 174.530000000114,
      "left": 253.530000000114,
      "attrs": { "color": "red" }
    },
    {
      "type": "wokwi-led",
      "id": "led3",
      "top": 115.20000000011399,
      "left": 252.200000000114,
      "attrs": { "color": "red" }
    },
    {
      "type": "wokwi-led",
      "id": "led4",
      "top": 68.530000000114,
      "left": 252.200000000114,
      "attrs": { "color": "red" }
    },
    {
      "type": "wokwi-resistor",
      "id": "r1",
      "top": 206.49000000011398,
      "left": 300.00000000011397,
      "attrs": { "value": "1000" }
    },
    {
      "type": "wokwi-resistor",
      "id": "r2",
      "top": 152.480000000114,
      "left": 302.670000000114,
      "attrs": { "value": "1000" }
    },
    {
      "type": "wokwi-resistor",
      "id": "r3",
      "top": 105.15000000011399,
      "left": 301.330000000114,
      "attrs": { "value": "1000" }
    },
    {
      "type": "wokwi-resistor",
      "id": "r4",
      "top": 61.150000000114,
      "left": 300.670000000114,
      "attrs": { "value": "1000" }
    },
    {
      "type": "wokwi-relay-module",
      "id": "relay1",
      "top": 173.000000000114,
      "left": -76.79999999988601,
      "attrs": {}
    },
    { "type": "wokwi-vcc", "id": "vcc1", "top": 88.83, "left": -119.46, "attrs": {} },
    { "type": "wokwi-gnd", "id": "gnd1", "top": 51.78, "left": 51.09, "attrs": {} },
    { "type": "wokwi-gnd", "id": "gnd2", "top": 208.95, "left": -164.69, "attrs": {} },
    { "type": "wokwi-vcc", "id": "vcc2", "top": -19.07, "left": 358.57, "attrs": {} }
  ],
  "connections": [
    [ "esp1:D25", "ultrasonic1:ECHO", "green", [ "h0" ] ],
    [ "ultrasonic1:TRIG", "esp1:D26", "green", [ "v0" ] ],
    [ "r3:2", "r4:2", "green", [ "v0" ] ],
    [ "r3:2", "r2:2", "green", [ "v0" ] ],
    [ "r1:2", "r2:2", "green", [ "v0" ] ],
    [ "esp1:D21", "led1:C", "green", [ "h0" ] ],
    [ "led4:C", "esp1:D19", "green", [ "v0.47", "h-17.77", "v-29.33" ] ],
    [ "esp1:D18", "led3:C", "green", [ "h45.2", "v1.7" ] ],
    [ "led3:A", "r2:1", "green", [ "v-0.87", "h31.57" ] ],
    [ "r3:1", "led4:A", "green", [ "v0.87", "h-18.56" ] ],
    [ "led1:A", "r4:1", "green", [ "v0" ] ],
    [ "r1:1", "led2:A", "green", [ "v0" ] ],
    [ "relay1:IN", "esp1:D27", "green", [ "h0.1", "v30.4", "h158", "v-121.33" ] ],
    [ "relay1:NO", "led2:C", "green", [ "h26.77", "v17.46" ] ],
    [ "ultrasonic1:GND", "gnd1:GND", "black", [ "v-0.78", "h84.07", "v-37.2" ] ],
    [ "vcc1:VCC", "ultrasonic1:VCC", "red", [ "v15.4", "h32.89" ] ],
    [ "relay1:VCC", "vcc1:VCC", "red", [ "h0" ] ],
    [ "gnd2:GND", "relay1:GND", "black", [ "v-7.86", "h76.59" ] ],
    [ "r4:2", "vcc2:VCC", "green", [ "v-0.56", "h9.97" ] ],
    [ "ultrasonic1:GND", "relay1:COM", "black", [ "v59.67", "h105.46", "v44.64" ] ]
  ],
  "dependencies": {}
}

Conclusion

In conclusion, ultrasonic sensors are a type of sensor that uses sound waves to detect the presence and distance of objects. They offer a number of advantages, including high accuracy, low cost, and ease of integration, and are used in a wide range of applications across many different industries. However, they also have some limitations, such as limited range in certain environments and limited resolution compared to other types of sensors. When choosing a sensing solution, it is important to consider the specific requirements of the application and to choose the type of sensor that offers the best balance of accuracy, cost, and ease of use.


Post a Comment

Previous Post Next Post