// Range.C // // Measure distance using an ultrasonic range sensor // #include // Global Variables unsigned long int TIME, TIME0, TIME1, dT; const unsigned char MSG0[21] = "Range.C "; const unsigned char MSG1[21] = "Ultrasonic Sensor "; // Interrupt Service Routine void interrupt IntServe(void) { if (TMR0IF) { RC0 = !RC0; TMR0IF = 0; } if (TMR1IF) { TIME = TIME + 0x10000; TMR1IF = 0; } if (CCP1IF) { if (CCP1CON == 0x05) { // rising edge TIME0 = TIME + CCPR1; CCP1CON = 0x04; } else { TIME1 = TIME + CCPR1; dT = TIME1 - TIME0; CCP1CON = 0x05; } CCP1IF = 0; } } // Subroutines #include "lcd_portd.c" // Main Routine void main(void) { int mm; unsigned int i; TRISA = 0; TRISB = 0xFF; TRISC = 0x04; // capture every rising edge TRISD = 0; ADCON1 = 0x0F; LCD_Init(); LCD_Move(0,0); for (i=0; i<20; i++) LCD_Write(MSG0[i]); LCD_Move(1,0); for (i=0; i<20; i++) LCD_Write(MSG1[i]); Wait_ms(1000); LCD_Inst(1); TIME = 0; // set up Timer0 for PS = 1 T0CS = 0; T0CON = 0x81; TMR0ON = 1; TMR0IE = 1; TMR0IP = 1; PEIE = 1; // set up Timer1 for PS = 8 TMR1CS = 0; T1CON = 0x81; TMR1ON = 1; TMR1IE = 1; TMR1IP = 1; PEIE = 1; // set up Capture1 for rising edges TRISC2 = 1; CCP1CON = 0x05; CCP1IE = 1; PEIE = 1; // turn on all interrupts GIE = 1; while(1) { mm = dT * 0.1715; // units = 1/10 mm LCD_Move(0,0); LCD_Out(dT, 10, 7); LCD_Move(1,0); LCD_Out(mm, 10, 1); } }