//////////////////////////////////////////////////////////////////////// // Sonar.c // //////////////////////////////////////////////////////////////////////////// #include <16F876.H> #fuses HS,NOPROTECT,NOWDT #include #use delay(clock=20000000) #use rs232(baud=19200, xmit=PIN_C6, rcv=PIN_C7) #define SONAR_INIT PIN_B3 #define SONAR_ECHO PIN_C1 #define SONAR_BINH PIN_B5 long time = 0; long distance = 0; byte done_read = 0; void sonar_read() { output_high(SONAR_INIT); // start TIMER1 set_timer1(0); delay_us(900); //add the blanking signal to here output_high(SONAR_BINH); // wait for ECHO to go high and get the time while(!input(SONAR_ECHO)); time = get_timer1(); delay_ms(100); output_low(SONAR_INIT); output_low(SONAR_BINH); delay_ms(100); done_read = 1; } main() { setup_timer_1( T1_INTERNAL|T1_DIV_BY_8); printf("\n\r started! \n\r"); while(TRUE){ distance = 0; if (getc() == 's') sonar_read(); if (done_read){ printf("done read = 1\r\n"); printf("time = %lu\n\r", time); // calculate distance distance = (time * 0.276); //(time * 0.0008)*345; printf(" Counter value: %lu -- distance: %lu\n\n\r", time, distance); done_read =0; } } }