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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
| sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;
sbit LCD_RS_Direction at TRISB4_bit;
sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;
unsigned tOld, tNew;
char edge = 0;
char capture = 0;
unsigned tword;
int distance;
//Functions
void interrupt();
//main function
void main() {
int no1,no2;
char display[7];
char display1[7];
Lcd_Init(); // Initialize LCD
Lcd_Cmd(_LCD_CLEAR); // Clear display
Lcd_Cmd(_LCD_CURSOR_OFF); // Cursor off
TRISC = 0; // assign PORTC as output
TRISC.B2 = 1; // RC2 must be input
T1CON = 0x1; // Timer1 ON, internal clock Fosc/4
INTCON.GIE = 1; //Enable Global Interrupts
INTCON.PEIE =1; //Enable Peripheral Interrupts
PIE1.CCP1IE = 1; // enable interrupt capture
TRISD=0;
PORTD=0;
CCP1CON = 0x04; // Capture mode every falling edge
Lcd_Out(1,1," Measure the ");
Lcd_Out(2,1," distance using ");
Delay_ms(1000);
Lcd_Out(1,1," Ultrasonic ");
Lcd_Out(2,1," Sensor ");
Delay_ms(1000);
Lcd_Cmd(_LCD_CLEAR);
Delay_ms(500);
Lcd_Out(1,1,"Distance is:"); //Display Charactors on the LCD
while(1){ //Start never ending while loop
if(capture){
PIE1.CCP1IE = 0; // disable interrupt while processing
capture = 0; // clear flag
// Calculate length of pulse from rising edge to rising edge
tword = ~tOld + tNew+1;
// tword contain length of pulse in micro second
distance=tword /58.2; // 29.1 us = 1cm
Lcd_Out(2,1,distance);
Lcd_Out(2,11,"c");
Lcd_Out(2,12,"m");
if (distance>=5) { //MODIFIED
PORTD = 0xf0;
}
else if (distance<5) { //MODIFIED
PORTD = 0x0f;
}
PIR1.CCP1IF = 0; // clear CCP flag
PIE1.CCP1IE = 1; // enable interrupt
}
}// End of while
} // End of main
void interrupt() {
if(PIR1.CCP1IF==1){ //Check CCP1 enterrupt
if(!edge){
tOld = (256*CCPR1H)+CCPR1L; // keep starting value
edge = 1;
PIE1.CCP1IE = 0; // disable interrupt for change
CCP1CON = 0x05; // Capture mode every rising edge
PIE1.CCP1IE = 1; // Enable interrupt capture
}else{
tNew = (256*CCPR1H)+CCPR1L; // Keep ending value
capture = 1; // Complete capture, set a flag
edge = 0;
PIE1.CCP1IE = 0; // disable interrupt for change
CCP1CON = 0x04; // Capture mode every falling edge
PIE1.CCP1IE = 1; // Enable interrupt capture
}
PIR1.CCP1IF = 0; //Clear CCP flag
}
} |