Ultrasonic distance meter using HC-SR04 and 8051

ultrasonic-range-detector-project

Ultrasonic waves are of great use and holds key in fields such as automation, marine and so. One of the familiar and trusted application of Ultrasonic waves are range and distance detection, you might have seen some of these in robots to detect obstacles and in automated factories. Similarly we are going to build Ultrasonic distance meter to measure the distance between the module and an object, this will be extremely useful for robotic applications.

SCHEMATIC DESIGN OF ULTRASONIC DISTANCE METER:

ultrasonic-interface-8051-microcontroller

PARTS REQUIRED:

Here is a list of parts required to build this project. We have added direct links to buy these parts in the below table. Since we are an affiliate marketing partner of “Amazon.in” we will get a referral fee for every purchase you make, which would make you a contributor for our development.

PART NAME COUNT LINK TO BUY
AT89S52 1 Buy here
HC-SR04 1 Buy here
LCD 1 Buy here
Connecting Wires As Required
Resistors As Required
Capacitors As Required

HC-SR04 ULTRASONIC MODULE:

hc-sr04-ultrasonic-module

HC-SR04 is an  ultrasonic ranging module designed for embedded projects like this. It has a resolution of 0.3cm and the ranging distance is from 2cm to 400cm. This module transmits an ultrasonic signal, picks up its echo, measures the time elapsed between the two events and outputs a waveform whose high time is modulated by the measured time which is proportional to the distance.

1) VCC :  5V DC supply voltage is connected to this pin.

2) Trigger : The trigger signal is to start the transmission of waves which must be a pulse with 10uS high time. When the module receives a valid trigger signal it issues 8 pulses of 40KHz ultrasonic sound from the transmitter. The echo of this sound is picked by the receiver.

3)Echo : At this pin, the  module outputs a waveform with high time proportional to the distance.

4) GND: Ground is connected to this pin.

timing-diagram-ultrasonic-module

This timing diagram explains the way this module measures the distance. A pulse trigger input to the module will enable it to produce a burst of 8 sonic pulse of 40Khz. When the pulse hits the obstacle it reflects the ultrasonic waves as echo which is sensed by the echo pin of the module. The echo signal can be obtained from the Echo pin of the Ultrasonic module. The length of the of echo pulse is proportional to the distance of the object/obstacle. Refer the “Data Sheet” for more information about this module.

USING 8051 TO MEASURE ECHO PULSE:

Now we are clear about the module pins and its operation let’s see how to make this work with 8051 to measure distance. The measurement of Echo pulse can be done with the help of external Interrupt and Timer modules of AT89S52 Microcontroller. In capture mode when external pulse is fed to the interrupt the timer starts counting and will stop only after the state of pulse is changed. Steps to follow to program controller as a capture device.

  1. Initialize Timer0 module as 16 bit timer with Gate bit as 1.
  2. Making Gate bit as 1 will transfer the control of timer to external interrupt pin INT0.
  3. When there is an interrupt pulse timer 0 starts counting and stops as soon as the interrupt disappears.
  4. The value in the Timer 0 (TH0 and TL0) gives the time period or length of the pulse.

OPERATION:

  1. Connect the Trigger pin of the HC-SR04 module to any I/O pins of 8051 controller.
  2. Connect the Echo pin of the module to interrupt pin INT0 of the Microcontroller.
  3. Send a pulse of minimal timer period 10us, this will make the Ultrasonic module to send burst of data.
  4. The reflected waves will be sensed by the module and it exhibits the output in Echo pin logic high or 1 to INT0 pin of Microcontroller.
  5. This creates an interrupt and Timer 0 will start counting.
  6. When the pulse from echo pin alters its state to logic 0 or low the timer 0 stops counting
  7. The length of pulse from echo pin is proportional to the distance at which the object is located.
  8. The value in the Timer 0 gives the distance of course with some simple calculations.

CALCULATION:

According to the data sheet the distance can be given by the formula :

Distance in cm = Timer 0/58

Distance in inch = Timer 0/148

CODE:

#include<REGX52.h>
#define port P2
#define dataport P0
int cms;
sbit trig=P3^5;
sbit rs=port^0;
sbit rw=port^1;
sbit e=port^2;

void delay(unsigned int msec)
{
  int i,j;
  for(i=0;i<msec;i++)
  for(j=0;j<1275;j++);
}

void lcd_cmd(unsigned char item) // Function to send command to LCD
{
  dataport = item;
  rs= 0;
  rw=0;
  e=1;
  delay(1);
  e=0;
  return;
}

void lcd_data(unsigned char item) // Function to send data to LCD
{
  dataport = item;
  rs= 1;
  rw=0;
  e=1;
  delay(1);
  e=0;
  return;
}

void lcd_data_string(unsigned char *str) // Function to send string to LCD
{
  int i=0;
  while(str[i]!='\0')
   {
    lcd_data(str[i]);
    i++;
    delay(1);
   }
return;
}

void send_pulse(void) 
{
  TH0=0x00;TL0=0x00;
  trig=1;                  //Sending trigger pulse
  delay(5);                //Wait for about 10us
  trig=0;                  //Turn off trigger
}

unsigned int get_range(void)
{
  long int timer_val;
  send_pulse();
  while(!INT0);          //Waiting until echo pulse is detected
  while(INT0);           //Waiting until echo pulse changes its state
  timer_val=(TH0<<8)+TL0;
  lcd_cmd(0x81);
  lcd_data_string("output:");
  lcd_cmd(0x8a);
  if(timer_val<38000)
   {
    cms=timer_val/59;
    if (cms!=0)
     {
      lcd_data(cms+48);
     }
   }
  else
  {
   lcd_cmd(0x06);
   lcd_data_string("Object out of range");
  }
  return cms;
}

void main()
{
  lcd_cmd(0x38);
  lcd_cmd(0x0c);
  delay(2);
  lcd_cmd(0x01);
  delay(2);
  lcd_cmd(0x81);
  delay(2);
  lcd_data_string("start");
  delay(20);
  TMOD=0x09;//timer0 in 16 bit mode with gate enable
  TR0=1;//timer run enabled
  TH0=0x00;
  TL0=0x00;
  P3|=0x04;//setting pin P3.2
  while(1)
  {
   get_range();
   delay(2);
  }
}

WORKING VIDEO:

NOTE:

  • You can use this method to any robotic path guidance application.
  • You can get more range by replacing the sensor module we used above.

27 Comments

  1. Loki

    the LCD is only displaying ‘start’
    what to do now?

    Reply
    1. Frank DonaldFrank Donald

      Check if your Sensor is working properly, see if the wiring is right and try to create any obstruction and see if it is responding. Sounds like the code is running within the while(1) loop. If the sensor doesn’t sense any obstruction it gonna repeat the loop ( Send pulse -> wait for deflected pulse ) forever.

      Reply
      1. santosh

        how to chech in proteus??

        Reply
        1. Frank DonaldFrank Donald

          Hi Santosh,

          I don’t think we have Ultrasonic sensor simulation in Proteus.

          Reply
  2. JUGAL

    ULTRASONIC DISTANCE MEASERMENT.c(101): error C202: ‘TL0’: undefined identifier
    ULTRASONIC DISTANCE MEASERMENT.c(102): error C202: ‘P3’: undefined identifier
    ULTRASONIC DISTANCE MEASERMENT.c – 27 Error(s), 2 Warning(s).
    I GET THIS KIND OF ERROR PLZ HELP ME TO SOLVE I AM USING KEIL uVISION 5

    Reply
  3. V.joel jebaraj

    ITS SHOWING CHARACTER INSTEAD OF NUMERIC HOW TO COVERT FROM ASCII TO DECIMAL &HEXA DECIMAL.

    Reply
    1. PATNI SHIVAM ARUNKUMAR

      You have to add some additional progra. In it.

      Reply
  4. Unknown

    Can anyone help me .. i want to edit the code as such that if range is less than 10cm then output should be available at any one port pin…HELP

    Reply
  5. chinmay

    as timer is in auto mode i.e GATE bit is = 1;
    why you are again starting timer in main loop()
    I believe gate will start and stop the timer

    Reply
  6. Unknown

    I’m Getting characters A B C D in place of numerics….Help plz

    Reply
    1. Frank DonaldFrank Donald

      Are you using the same module as mentioned in the above article? Pulse timing is actually the output delivered from this module, the pulse timing will then be modified to distance values by MCU. Kindly check your module and modify the distance to see if it varies what you see in the LCD

      Reply
      1. Unknown

        yes i am using the same module

        Reply
  7. DABID MCINERNEY

    this CODE does not work?
    it says “INT” “INT0” is undefined identifier???

    Reply
    1. Frank DonaldFrank Donald

      Dabid,
      INT and INT0 stands for interrupts. Which compiler you are using? This code was building Keil.

      Reply
    2. Prashant Shinde

      8051 has external hardware interrupt 0. Use it to control timer 0.

      Reply
  8. gokul

    we r planning to operate uv sensor to sense obstacles and stop the dc motor…how can we do..plss give me suggestion

    Reply
    1. Frank DonaldFrank Donald

      UV sensor???

      Reply
  9. prasanna jethi

    the output showing A B C D instead of numbers, plzz help

    Reply
    1. Frank DonaldFrank Donald

      Hi Prasanna,
      That is weird, does the characters change when you bring any obstacles in and out of range?

      Reply
    2. Prashant Shinde

      Int cms cannon be used to display values. Need to convert hex into decimal digits and then into ASCII codes.

      Reply
  10. Vidyasagar

    The given code does not work. It shows error in AVR studio 4

    Build target ‘Target 1’
    Target has no object modules
    Target not created

    Reply
    1. Frank DonaldFrank Donald

      Vidyasagar,
      I believe the code is built using Keil Uvision. Kindly try the above code in that compiler

      Reply

Leave a Comment

Your email address will not be published. Required fields are marked *