As an Amazon Associate we earn from qualifying purchases.
An ultrasonic sensor is one of the easiest ways to measure distance with a microcontroller. This article shows how to read an ultrasonic sensor with a PIC16F877A using MikroC, and how to show the distance in centimetres on a 16×2 LCD. You get the wiring, the maths behind the 58 microsecond figure, the full program and a few tips for making the readings more reliable.
How an ultrasonic sensor measures distance
Modules such as the common HC-SR04 style sensor have four pins: VCC, GND, Trig and Echo. The sensor sends out a short burst of ultrasonic sound and listens for the reflection. The microcontroller does not read a distance directly. It reads a pulse whose width is proportional to the distance.
The sequence is always the same:
- The microcontroller sets the Trig pin high for about 10 microseconds, then sets it low.
- The sensor sends the ultrasonic burst.
- The Echo pin goes high and stays high until the reflected sound returns.
- The microcontroller measures how long Echo stayed high and converts that time to distance.
The calculation: why 58 microseconds per centimetre
The speed of sound in air is about 340 m/s (the code comment uses 340.29 m/s). The echo pulse covers the trip from the sensor to the object and back, so the sound travels the distance twice. To get the one-way distance we use half the speed, which is about 170 m/s.
- Half speed: 340.29 / 2 = about 170.15 m/s
- Convert to centimetres per microsecond: (170.15 × 100) / 1,000,000 = about 0.017 cm/µs
- Time for 1 cm: 1 / 0.017 = about 58.8 µs
So every 58 µs or so that the Echo pin stays high is roughly 1 cm of distance. The program below counts in steps of 58 µs, so the count is the distance in centimetres. Note that the original comment in this article gave 0.01715 cm/µs and 58.3 µs, which does not match the arithmetic above. The difference is small, but the corrected comment is in the code below.
Wiring the sensor to the PIC16F877A
The sensor runs from 5 V, which suits a PIC16F877A powered at 5 V. Connect it like this:
- VCC to 5 V
- GND to GND (shared with the PIC)
- Echo to pin RB0 (input)
- Trig to pin RB1 (output)
The LCD is connected in 4-bit mode on PORTD: RS to RD2, EN to RD3, and D4 to D7 on RD4 to RD7. These match the sbit declarations in the code. If you change any pin, change the matching declaration too.
MikroC code
Before you build, add the LCD library to your MikroC project (tick it in the Library Manager) and set the correct oscillator frequency in the project settings. The delay_us and delay_ms functions depend on that setting, so a wrong value gives wrong distances.
/*
-------calculation-----------
speed of sound = 340.29 m/sec.
Here the total distance travelled by sound = sum of
distance from sensor to object and object to sensor.
But both are same . so we need only one distance.
then speed become 170.15 m/sec.
converts m/sec to cm/microseconds.
then (170.15*100)/1000000 = 0.017 cm/us.
from above equation time taken to
travel distance 1CM = 1/0.017 = about 58.8us (58us used below).
---WIRING-----
VCC to 5v
GND to GND
Echo to pin B0
Trig to pin B1
*/
int c1=0;
char distance[8];
void usinit(void);
void uscheck(void);
// LCD module connections
sbit LCD_RS at RD2_bit;
sbit LCD_EN at RD3_bit;
sbit LCD_D4 at RD4_bit;
sbit LCD_D5 at RD5_bit;
sbit LCD_D6 at RD6_bit;
sbit LCD_D7 at RD7_bit;
sbit LCD_RS_Direction at TRISD2_bit;
sbit LCD_EN_Direction at TRISD3_bit;
sbit LCD_D4_Direction at TRISD4_bit;
sbit LCD_D5_Direction at TRISD5_bit;
sbit LCD_D6_Direction at TRISD6_bit;
sbit LCD_D7_Direction at TRISD7_bit;
// End LCD module connections
void main(){
Lcd_Init(); // Initialize LCD
Lcd_Cmd(_LCD_CLEAR); // Clear display
Lcd_Cmd(_LCD_CURSOR_OFF); // Cursor off
usinit();
while(1)
{ Lcd_Cmd(_LCD_CLEAR);
Lcd_Out(2,1,distance);
uscheck();
}
}
void uscheck(void)
{
portb.f1=1 ;
delay_us(10);
portb.f1=0 ;
while(!portb.f0);
c1=0;
while(portb.f0) {c1++; delay_us(58); } // 1CM ==58US
IntToStr(c1, distance);
delay_ms(200);
}
void usinit(void)
{
trisb.f0=1; //echoPin
trisb.f1=0; //trigPin
}
How the program works
usinit()
This sets RB0 as an input for the Echo signal and RB1 as an output for the Trig signal. It runs once at start-up.
uscheck()
This function does one measurement. It pulls Trig high for 10 µs and then low. It then waits for Echo to go high. Once Echo is high, it adds 1 to the counter c1 and waits 58 µs, repeating until Echo falls. The final count is the distance in centimetres. IntToStr converts it to text, and a 200 ms delay gives the sensor time to settle before the next reading.
main()
The main loop initialises the LCD, clears the screen and repeatedly prints the text in distance on the second row, then takes a new measurement. Because the print happens before the measurement in each pass, the display always shows the most recent completed reading.
Making the readings more reliable
- Add a timeout. The line while(!portb.f0); waits forever if the sensor is disconnected or no echo comes back. A counter that gives up after a set number of loops stops the program from freezing.
- Expect a small error. Each pass of the counting loop takes slightly longer than 58 µs because of the instructions around the delay. This can make readings a little low at long distances. Compare against a ruler and adjust the delay value if needed.
- Reduce flicker. Clearing the whole LCD on every pass makes the display blink. Writing the value in the same position and padding it with spaces looks steadier.
- Use a timer for better accuracy. The PIC16F877A has Timer1, which can measure the Echo pulse in hardware instead of counting delay loops.
- Point the sensor at flat surfaces. Soft, angled or very small objects reflect sound poorly and can give unstable or missing readings.
Troubleshooting
- LCD shows nothing: check the contrast pot, the LCD library in the project and the PORTD wiring.
- Distance is always 0: check that Echo goes to RB0 and Trig to RB1, and that the sensor has 5 V and a common ground.
- Readings are wrong by a steady ratio: the clock frequency in the MikroC project probably does not match your real oscillator.
- Program hangs at start-up: the code is probably stuck waiting for Echo. Check the wiring and add a timeout.
Related projects
If you use other controllers, see how to connect an ultrasonic sensor with the MSP430 or how the same sensor works on an ultrasonic sensor on ARM. Building on an Arduino instead? The HC-SR04 Arduino tutorial covers the same Trig and Echo timing with Arduino wiring and code. To get comfortable with the pins used here, read about digital input and output on the PIC16F877A. For other MikroC peripherals, try an RFID reader in MikroC or a DS1307 real-time clock in MikroC.
FAQ
Why is the distance count divided by 58?
Sound travels about 1 cm in roughly 29 µs, and the echo pulse covers the trip there and back. That makes about 58 µs of pulse width for each centimetre of distance.
Can I use a different pin instead of RB0 and RB1?
Yes. Any free digital I/O pins work. Change the TRIS settings and the portb.f0 and portb.f1 references in the code to match your wiring.
Does this code work with the HC-SR04?
It uses the standard Trig and Echo method with a 10 µs trigger pulse, which is how HC-SR04 style modules work. Check the datasheet of your own module for its supply voltage and range.
Why does the reading jump around?
Reflections from angled or soft surfaces, electrical noise and the timing error of the delay loop can all cause jumps. Taking several readings and averaging them gives a steadier value.