#include <16F648A.h> #fuses INTRC_IO,NOWDT,PUT,NOPROTECT,NOBROWNOUT,NOLVP #use delay(clock=4000000) #use rs232(baud=9600,parity=N,xmit=PIN_B2,rcv=PIN_B1,bits=9) #define trigger PIN_B4 #define led1 PIN_B5 long rise,fall,pulse_width; #int_ccp1 void isr() { fall = CCP_1; pulse_width = fall - rise; // CCP_1 is the time the pulse went high } // CCP_2 is the time the pulse went low // pulse_width/(clock/4) is the time //with 4,000,000 clk each tmr1 increment = 1uS // In order for this to work the ISR // overhead must be less than the // low time. For this program the // overhead is 45 instructions. The // low time must then be at least // 9 us. long convert(long echo){ long distance; distance = echo / 74; return distance; } void main() { long dist; output_low(trigger); output_high(led1); printf("\r\nHigh time (sampled every second):\r\n"); setup_ccp1(CCP_CAPTURE_FE); // Configure CCP1 to capture fall setup_timer_1(T1_INTERNAL); // Start timer 1 enable_interrupts(INT_CCP1); // Setup interrupt on falling edge enable_interrupts(GLOBAL); while(TRUE) { output_high(trigger); delay_us(20); output_low(trigger); rise = get_timer1(); delay_ms(20); dist = convert(pulse_width); if (dist< 75){ output_low(led1); printf("\r dist:%lu inches",dist); } else { //timeout occurred, no obastacle output_high(led1); } } }