Skip to main content

Measuring Distance

A List of Shopping Parts

In this tutorial we will study how we can measure the distance accurately using a HC-SR04 Ultrasonic range sensor and Raspberry PI.For this work we want following materials:
  • HC-SR04 Ultrasonic range sensor :₹ 150
  • Resistors: ₹2
  • Raspberry Pi
  • Jumper Wires

Ultrasonic Ranging Module

HC-SR04 Ultrasonic module

Ultrasonic ranging module HC-SR04 provides 2cm-400cm non-contact measurement function ranging accuracy can reach to 3mm. The module includes ultrasonic transmitters, reciever, crystal and control unit. The basic priciple of work is:
  1. Using trigger for at least 10μs high level signal.
  2. The module automatically sends eight 40kHz and detect whether there is a pulsesignal back.
  3. If the signal back, through high level, time of high output IO duration is the time from sending ultrasonic to  returning.

Test distance=(high level time x velocity of sound)/2

From the pre-primary classes we are studied that the distance is time x distance. But in the above equation we can see a division by 2. Actualluy the HC-SR04 Ultrasonic range sensor's working principle is same as RADAR. The HC-SR04 transmits some ultrasonic sound and it hits on the obstacle. Then the echo of this sound is recieved by reciever. We know that the speed of sound on air(normally) 330 to 340 m/s. Consider this speed of transmitted sound and recieved echo is same. During this transmission of sound and reception of echo the time elpsed increases twice. That is why we want to devide time elapsed by two.

Connecting to the Pi

Powering up this module is very easy. According to the datasheet of HC-SR04 it want 5Vcc. But from personal experience it also works with 3.3Vcc. Since the raspberry Pi comes with  these Vcc options it easy to powering up this module. Also the trigger input of the ultrasonic range module works with TTL logic, you can directly connect this pin to GPIO header. Hear we are directly connected GPIO pin#16(GPIO 23) on the GPIO header.

The module's output is called the "echo". The output pin is LOW until the module has taken its distance measurement. It then sets the pin HIGH(+5V) for the same amount of time that it took the module uses a +5V level for a HIGH but this is too high for inputs on the GPIO header which only tolerates 3.3V as I mentioned in the previous post. In order to ensure the GPIO pins only gets hits with 3.3V,  we can use a voltage divider using two resistors.
Voltage Divider Circuit between Echo and Ground

If the resistances of R1 and R2 is same then the voltage splits in half(2.5V) since the Vcc is 5V.If the R2 is the twice the value of R1 then we get 3.33V approximately which is fine. So ideally we want R2 to be between R1 and R1 x 2. In this circuit we are using 330 Ω and 470 Ω resisistors. Alternatively you can use 270 Ω resistor and 330 Ω resistor or 1KΩ resistor and 1.5KΩ resistor.

Here is a diagram of final circuit. Actually I would like to draw the Raspberry Pi diagrams with Fritzing. But the HC-SR04 module is not on the older Fritzing library and new Fritzing is not installing on my computer due to missing of some files.
Ultrasonic Module Circuit

Creating coding snippets on the Blogger is not an easy job. So please visit my Github Blog for codes. You can also clone the codes from our Github repository.

import time
import RPi.GPIO as GPIO
while True:
    # Use BCM GPIO references
    # instead of physical pin numbers
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False) # Disable warnings about alternate isage of GPIO pins
    # Define GPIO to use on Pi
    GPIO_TRIGGER = 23
    GPIO_ECHO    = 24

    # Speed of sound in cm/s at temperature
    temperature = 20
    speedSound = 33100 + (0.6*temperature)

    print("Ultrasonic Measurement")
    print("Speed of sound is",speedSound/100,"m/s at ",temperature,"deg")

    # Set pins as output and input
    GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
    GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo

    # Set trigger to False (Low)
    GPIO.output(GPIO_TRIGGER, False)

    # Allow module to settle
    time.sleep(0.5)

    # Send 10us pulse to trigger
    GPIO.output(GPIO_TRIGGER, True)
    # Wait 10us
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)
    start = time.time()

    while GPIO.input(GPIO_ECHO)==0:
        start = time.time()

    while GPIO.input(GPIO_ECHO)==1:
        stop = time.time()

    # Calculate pulse length
    elapsed = stop-start

    # Distance pulse travelled in that time is time
    # multiplied by the speed of sound (cm/s)
    distance = elapsed * speedSound

    # That was the distance there and back so halve the value
    distance = distance / 2

    print("Distance : {0:5.1f}".format(distance))
    GPIO.cleanup()
    

Applications

  • We can use this in Robots to avoid obstacles.
  • We can use this ultrasonic module for water level monitor.

Reference

  • Raspberry-spy.co.uk
  • Raspberry Pi cookbook: Software and hardware problems and solutions by Simon Monk

Comments

Popular posts from this blog

8051 Simple Programs

Sum of 8-bit Numbers Stored in Memory Here  we will discuss about 8051 programs but we can't discuss about all of the 8051 instructions. For programming 8051 we should know about assembler directives as well as instruction set. Click  here to download Atmel c51 user guide that will discuss about 8051(c51 family microcontroller) instruction set, assembler directives, c51 cross assembler from Atmel.  Program ORG 00H MOV R0,#50H   ; get memory location in memory pointer R0 MOV R1,#51H   ; get memory location on memory pointer register R1 MOV A,@R0       ; get content of memory location 50H to accumulator ADD A,@R1        ; add content of A with content of memory location 51H and store result in A MOV R0,#52H    ; get 52H to memory pointer R0 MOV@R0,A         ; copy content of A to memory location 52H END Add 16-bit Numbers ...

Introduction to 8051 embedded C

For 8051 we need to include the file reg51.h. This file contains the all the definitions of 8051 registers. With this information C compiler produces hex file that can be downloaded into the ROM of the microcontroller. It is important to note that the size of the hex file produced by the assembly language is much larger than the hex file produced by C compiler. Apart from this fact, there is many reasons for writing programs in C instead of assembly: ●It is much easier and less time consuming to write programs in C assembly. ●C is more flexible; it is easier to modify and update. ●Programming in C allows to use code available in function libraries. ●Program written inC for one microcontroller is portable to other microcontrollers with little or no modifications. Data Types in 8051 Embedded C The table shown below lists the data types that are available in typical C51 compiler. The gives information about the size of the data variable and it's value range. Data type ...

Frequency of Oscillation of RC Phase Shift Oscillator

Derivation of Frequency of Oscillation We have to find out the transfer function of RC feedback network. Feedback Circuit of RC Phase Shift Oscillator Applying KVL to various loops on the figure, we get, $$I_1 \left(R+\frac{1}{j \omega C }\right) -I_2R=V_i \text{ ....(1)}$$ $$-I_1R+I_2\left (2R+\frac {1}{j\omega C}\right)-I_3R=0\text{ ... (2)}$$ $$0-I_2R+I_3\left(2R+ \frac{1}{j\omega C}\right)=0\text{ ...(3)}$$ Replacing \(j\omega\) with \(s\) and writing equations in the matrix form, $$\begin{bmatrix}R+\frac{1}{sC} & -R & 0 \\-R & 2R+\frac{1}{sC} & -R \\0 & -R & 2R+\frac{1}{2sC} \end{bmatrix}\begin{bmatrix}I_1\\I_2\\I_3\end{bmatrix}=\begin{bmatrix}V_i\\0\\0\end{bmatrix}$$ Using Cramer's rule to find out \(I_3\), $$\text{Let, }D=\begin{bmatrix}R+\frac{1}{sC} & -R & 0 \\-R & 2R+\frac{1}{sC} & -R \\0 & -R & 2R+\frac{1}{2sC} \end{bmatrix}$$ \(|D|=\begin{vmatrix}R+\frac{1}{sC} & -R & 0 \\-R & 2R+\frac{1}{...