Interfacing PIC12F1822 with HC-SR04 ultrasonic sensor circuit:
This is our example circuit schematic where internal oscillator of PIC12F1822 is used.
The LCD display is used to display the distance result.
To interface 1602 LCD with PIC12F1822 microcontroller we need 74HC595 shift register as what was done in this post:Interfacing PIC12F1822 microcontroller with LCD display

Interfacing PIC12F1822 with HC-SR04 ultrasonic sensor CCS C code:

C

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

// Interfacing PIC12F1822 with HC-SR04 ultrasonic sensor CCS C code

// 3-Wire LCD driver must be added

//LCD module connections

#define LCD_DATA_PIN PIN_A0

#define LCD_CLOCK_PIN PIN_A1

#define LCD_EN_PIN PIN_A2

//End LCD module connections

#include <12F1822.h>

#fuses NOMCLR INTRC_IO

#use delay(clock = 8000000)

#include <3WireLCD.c>

#use fast_io(A)

unsignedint16i,distance;

int1 wait_sensor(){

i=0;

set_timer1(0);// Reset Timer1

while(!input(PIN_A5)&&(i<1000))

i=get_timer1();// Read Timer1 and store its value in i

if(i>990)

return0;

else

return1;

}

unsignedint16 get_distance(){

i=0;

set_timer1(0);

while(input(PIN_A5)&&(i<25000))

i=get_timer1();

returni;

}

voidmain(){

setup_oscillator(OSC_8MHZ);// Set internal oscillator to 8MHz

setup_adc_ports(NO_ANALOGS);// Configure all pins as digital

set_tris_a(0x20);// Configure RA5 pin as input

lcd_initialize();// Initialize LCD module

lcd_cmd(LCD_CLEAR);// LCD Clear

lcd_goto(4,1);// Go to column 4 row 1

lcd_out("Distance:");

SETUP_TIMER_1(T1_INTERNAL|T1_DIV_BY_2);// Configure Timer 1 to increment by 1 every 1 us