Circuit 146 - Ultrasonic Distance Meter with PIC16F877A

distance

Ultrasonic Sensors act as the eyes and ears for all embedded applications, they help the digital Microcontroller to understand what is actually happening in this real Analog world. This article shows how to Interface the Ultrasonic Sensor HC-SR04 with a PIC microcontroller.

The HC-SR04 is an ultrasonic sensor which can be used to measure distances anywhere between 2cm to 450cm (theoretically). This sensor has worked well in many projects which involve obstacle detection, distance measuring, environment mapping etc. To better understand its operation, an LCD display has been installed to display the correct distance.

test1

How does an Ultrasonic Sensor work?

Before we get any further, we should know how an Ultrasonic sensor works. The ultrasonic sensor used in this project is shown in Figure below.

ultra

As you can see it has two circular eyes like projections and four pins coming out of it. The two eye-like projections are the Ultrasonic wave (hereafter referred as US wave) Transmitter and receiver. The transmitter emits a US wave at a frequency of 40Hz, this wave travels through the air and gets reflected back when it senses an object. The returning waves are observed by the receiver. Now we know the time taken for this wave to get reflected and come back and the speed of the US wave is also universal (3400cm/s). Using this information and the below high school formulae we can calculate the distance covered (Distance = Speed × Time).

Now that we know how an US sensor works, let us how it can be interfaced with any MCU/CPU using the four pins. These four pins are Vcc, Trigger, Echo and Ground respectively. The module works on +5V and hence the Vcc and ground pin is used to power the module. The other two pins are the I/O pins using which we communicate to our MCU. The trigger pin should be declared as an output pin and made high for a 10uS, this will transmit the US wave into the air as 8 cycle sonic burst. Once the wave is observed the Echo pin will go high for the exact interval of time which was taken by the US wave to return back to the sensor module. Hence this Echo pin will be declared as input and a timer will be used to measure how long the pin was high. For more details see diagram below

Example:

We know that the speed of sound is 343 m/s under conditions of 20 °C temperature, 50% humidity, and sea-level atmospheric pressure. Converting units results in:

formula

That is, sound takes 29.2 microseconds to travel one centimetre. Therefore, we can obtain the distance from the time between the emission and reception of the pulse using the following equation.

formula1

The reason for dividing the time by two (in addition to the speed of sound in the appropriate units, which we calculated before) is that we have measured the time it takes for the pulse to go and come back, so the distance traveled by the pulse is twice the distance we want to measure.

 

onda

test2

As shown in Figures above, the circuit involves nothing more than a LCD display and the Ultrasonic sensor itself. The US sensor can be powered by +5V and hence it is directly powered by the any 7805 voltage regulator. The sensor has one output pin (Trigger pin) which is connected to pin 20 (RD1) and the input pin (Echo pin) is connected to pin 21 (RD2). The complete pin connection is illustrated in the table below.

S.No:

PIC Pin Number

Pin Name

Connected to

 1  33 RB0 D0 of LCD
2 34 RB1 D1 of LCD
3 35 RB2 D2 of LCD
4 36 RB3 D3 of LCD 
5 37 RB4 D4 of LCD 
 6 38 RB5 D5 of LCD  
 7  39  RB6 D6 of LCD   
 8  40  RB7 D7 of LCD
 9  15 RC0 RS of LCD 
10 16 RC1 RW of LCD 
11 17 RC2 E of LCD 
 12  20 RD1 Trigger of US 
 13  21 RD2 Echo of US 

 

Programming your PIC Microcontroller

Inside, the main function we start with initializing the IO pins and other registers as usual. We define the IO pins for LCD and US sensor and also initiate the Timer 1 register by setting it to work on 1:4 pre-scalar and to use internal clock (Fosc/4)

processor 16f877A         ; indicates the processor type
radix DEC                              ; indicates that the system is in decimal
include "P16f84.INC"   ; gets the file from the library
errorlevel -302 ; 

 org 0x00          ;start Program

bsf STATUS,RP0 ; Active bank 1 to configure the PORTs
movlw b'00000000' ; all PORTB
movwf TRISB       ; as output
movlw b'00000110' ; Configure PORTD 1 and 2
movwf TRISD ; as input
bcf STATUS,RP0 ; close bank 1 and go back to bank0

movlw b'00000001' ;Prescaler=1:1(65535) TMR1=Internal (fosc/4) TMR1=ON

movwf T1CON ; configure T1CON

The Timer 1 is a 16-bit timer used in PIC16F877A, the T1CON register control the parameters of the timer module and the result will be stored in TMR1H and TMR1L since it a 16-bit result the first 8 will be stored in TMR1H and the next 8 in TMR1L. This timer can be turned on or off using TMR1ON=0 and TMR1ON=1 respectively.

Now, the timer is ready to use, but we have to send the US waves out of the sensor, to do this we have to keep the Trigger pin high for 40KHz, this is done by the following code.

;*************** Send 40KHz ****************
Enviar40KHZ
bcf INTCON,T0IF ;Clear the TMR0 interrupt flag
clrf TMR0 ;Clean timer0

;*** Check if there is a pulse detected
movfw PORTD ;Read port C
btfsc PORTD,ccp1 ;Is there a pulse detected?
goto detect_off ;If there is a pulse detected

msg 0x0b,0x0b,0x0b ; - - - error detection
;*** Skip detected pulse
detect_off
bcf PORTA,ra5 ;turns off pulse input
;*** Restart Capture mode
clrf TMR1H ;Clean TMR1H
clrf TMR1L ;Clean TMR1L
clrf CCPR1H ;Clean CCPR1H
clrf CCPR1L ;Clean CCPR1L
movlw b'00000101' ;CCP1M=0101(rising edge capture mode)
movwf CCP1CON ;Configure CCP1CON
bsf STATUS,RP0 ;Switch to bank1
bsf PIE1,CCP1IE ;CCP1 interrupt enabled
bcf STATUS,RP0 ;Switch to bank 0
bcf PIR1,CCP1IF ;Clear CCP1 interrupt flag

;*** Sends 0.5 msec pulse
bsf PORTD,2;Start sending 40KHz
movlw d'100' ;Delay 0.5mSec, t=(4/fxtal)(3*ret_05ms+1+2(ret_05ms-1)+2)
movwf ret_05ms ;t=(4/fxtal)(5*ret_05ms+1)
ret05
nop ;Time setting
nop ;Time setting
decfsz ret_05ms,f
goto ret05
bcf PORTD,2 ;Stop sending 40KH

As shown in the timing diagram above, the Echo pin will stay low till the wave returns back and will then go high and stay high for the exact time taken for the waves to return back. This time has to be measured by the Timer 1 module.

Once the time is measured the resulting value will be saved in the registers TMR1H and TMR1L, these registers have to be clubbed to gather to get the 16-bit value. This is done by using the line below

;16-bit/8-bit division
division
movfw divisor      ;Read adjustment data
subwf TMR1L,f     ;Capture - adjustment
btfsc STATUS,Z         ;Result = 0 ?
goto division2 ;Si.        "R = 0"
btfsc STATUS,C        ;Result = 0 ?
goto division1          ;No. "R > 0"
goto division3         ;Yes."R < 0"

division1           ;( R > 0 )
movlw d'1'         ;increase
addwf cociente_l,f         ;Add 1 to the low counter
btfss STATUS,C         ;overflow?
goto division         ;No. Continue with the division
incf cociente_h,f       ;If there is overflow, increase the high counter
goto division      ;the division continues

division2           ;( R = 0 )
movfw TMR1H    ;Read TMR1H
btfss STATUS,Z        ; TMR1H = 0 ?
goto division1        ;No.
movlw d'1'
addwf cociente_l,f       ;Increment the L counter
btfss STATUS,C        ;Overflow
goto digito_dec    ;Skip to decimal conversion
incf cociente_h,f     ;Increment the H counter
goto digito_dec      ;Skip to decimal conversion

division3 ;( R < 0 )
movfw TMR1H       ;Read TMR1H
btfss STATUS,Z       ;TMR1H = 0 ?
goto division4    ;No. loan process
goto digito_dec   ;Skip to decimal conversion

division4
decf TMR1H,f    ;TMR1H- 1
movlw d'255'   ;Loan value
addwf TMR1L,f   ;TMR1L + 255
incf TMR1LL,f    ;TMR1L + 1
goto division1    ;Next division

Once the time is measured the resulting value will be saved in the registers TMR1H and TMR1L, these registers have to be clubbed to gather to get the 16-bit value.

Next we have to find how to calculate the distance. As we know distance = speed * time. But here the result should be divided by 2 since the wave is covering both the transmitting distance and receiving distance. The speed of us wave (sound) is 34000cm/s.

digito_dec
clrf disp_u           ;Limpia primer dнgito (unidades)
clrf disp_d           ;Clear second digit (tens)
clrf disp_c          ;Clear third digit (hundreds)

;*** Centenas
digit_c
movlw d'100'                ;Divider
subwf cociente_l,f     ;Dнgito - divisor
btfsc STATUS,Z         ;Result = 0 ?
goto digit_c2 ;Si.          "R = 0"
btfsc STATUS,C       ;Result = 0 ?
goto digit_c1 ;No.     "R > 0"
goto digit_c3               ;yes "R < 0"

digit_c1                     ;( R > 0 )
incf disp_c,f                            ;Increases the hundreds register
goto digit_c ;                          Next division of hundreds

digit_c2 ;( R = 0 )
movfw cociente_h                   ;Read the high quotient
btfss STATUS,Z                         ;quotient_h = 0 ?
goto digit_c1                           ;No. go on
incf disp_c,f                         ;Increases the hundreds register
goto digit_d                         ;Skip to tens conversion

digit_c3 ;( R < 0 )
movfw cociente_h                 ;Read quotient_h
btfss STATUS,Z                       ;quotient_h = 0 ?
goto digit_c4                           No. loan process
movlw d'100'                           ;Divider
addwf cociente_l,f              ;Return with the loan
goto digit_d                            ;Skip to tens conversion

digit_c4
decf cociente_h,f                ;quotient_h - 1
movlw d'255'                        ;Loan value
addwf cociente_l,f          ;quotient_l + 255
incf cociente_l,f                    ;quotient_l + 1
goto digit_c1                        ;following

;***dozens
digit_d
;*** out of range?
movfw disp_c             ;Read hundreds digit
sublw d'9'                         ;9 - (hundreds)
btfsc STATUS,Z              ;Result = 0 ?
goto digit_d0                          ;yes "R = 0"
btfsc STATUS,C                     ;Result < 0 ?
goto digit_d0                          ;No. "R > 0"
msg 0x0a,0x0b,0x02                     ; E - 2 error detection
goto int_end

digit_d0
movlw d'10'                                      ;Divider
subwf cociente_l,f                    ;Digit - divisor
btfsc STATUS,Z                   ;Result = 0 ?
goto digit_d1                               ;yes. "R = 0"
btfsc STATUS,C                     ;Result = 0 ?
goto digit_d1                       ;No."R > 0"
goto digit_d2                              ;yess"R < 0"

digit_d1                                      ;( R >= 0 )
incf disp_d,f                     ;Increases the tens register
goto digit_d                       ;Following

digit_d2                        ;( R < 0 )
movlw d'10'                ;Divisor
addwf cociente_l,f               ;Return residue
goto digit_u                  ;Jump to put units

;*** Units
digit_u
movfw cociente_l              ;Read residue
movwf disp_u
goto int_end

After this, all that remains is to pass the output result to the LCD where the reading takes place.

The program is written entirely in assembly and can be downloaded from here

 

 

 

favicon bacd

+(39) 347 051 5328

Italy - Kazakhstan

09.00am to 18.00pm

About

We offer the best and economical solutions, backed by 27+ years of experience and international standards knowledge, echnological changes, and industrial systems.

Marketing Materials

Spring Renovation
Industry
US Gas Company
Construct
Plus Project
Vam Drilling Service
X Project
X Project
Cabrrus Training

Marketing Materials1

Spring Renovation
Industry
US Gas Company
Construct
Plus Project
Vam Drilling Service
ultrasonic sensor
ultrasonic sensor
Cabrrus Training