//////////////////////////////////////////////////////////////////////// //// sonic_c.C //// //// //// //// Ultrasonic distance measure uses of timer0 and interrupts // receives sonic to measure as a character on rs232 // transmits results as a character on rs232 /// count@ counts no of 0.1ms interrupts while echo high //// scount1, scount2 hold distance, value 0(near)-170(far) // output to sonic on pin D0,D1,D2 // input from sonic B1,B2,B3 // shows results on led D3,D4,D5 if object < 30cm from sonic transmitter ///////////////////////////////////////////////////////////////////////// #include <16F877.h> #fuses HS,NOWDT,NOPROTECT #use delay(clock=20000000) #use RS232(baud=9600,xmit=pin_C4,rcv=pin_C3) byte count1,count2,count3; byte scount1,scount2,scount3; byte turn; #INT_RTCC clock_isr(){ //Now read the inputs to see if a sonic has echoed if (input(PIN_B1)) count1++; if (input(PIN_B2)) count2++; if (input(PIN_B3)) count3++; } main() { short s1,s2,s3; byte d_ready,thresh; output_low(PIN_D0); output_low(pin_D1); output_low(PIN_D2); s1=0; s2=0; s3=0; thresh=50; //initial threshold for lighting leds setup_counters(RTCC_INTERNAL,RTCC_DIV_2); enable_interrupts(INT_RTCC); disable_interrupts(GLOBAL); turn=1; count1=0; count2=0; count3=0; //show 3 leds working output_high(PIN_D3); output_low(PIN_D4); output_low(PIN_D5); delay_ms(100); output_low(PIN_D3); output_high(PIN_D4); output_low(PIN_D5); delay_ms(100); output_low(PIN_D3); output_low(PIN_D4); output_high(PIN_D5); delay_ms(100); output_low(PIN_D3); output_low(PIN_D4); output_low(PIN_D5); d_ready=2; do{ if (d_ready==2) turn=getc(); if (d_ready==2) { if (turn==1) { output_high(PIN_D0); delay_us(20); output_low(PIN_D0); s1=0; } if (turn==2) { output_high(PIN_D1); delay_us(20); output_low(PIN_D1); s2=0; } if (turn==3) { output_high(PIN_D2); delay_us(20); output_low(PIN_D2); s3=0; } d_ready=0; enable_interrupts(GLOBAL); if (turn==255) { //set led on threshold d_ready=2; disable_interrupts(GLOBAL); thresh=getc(); } } if (d_ready==0) { if (turn==1) { if ((input(PIN_B1)) && (s1==0)) { //Catch high transition, start of echo received count1=0; s1=1; } if ((!input(PIN_B1)) && (s1==1)) { //Update counter on low pulse scount1=count1; s1=0; d_ready=1; } if (count1>250) { scount1=count1; d_ready=1; } } if (turn==2) { if ((input(PIN_B2)) && (s2==0)) { //Catch high transition, start of echo received count2=0; s2=1; } if ((!input(PIN_B2)) && (s2==1)) { //Update counter on low pulse scount2=count2; s2=0; d_ready=1; } if (count2>250) { scount2=count2; d_ready=1; } } if (turn==3) { if ((input(PIN_B3)) && (s3==0)) { //Catch high transition, start of echo received count3=0; s3=1; } if ((!input(PIN_B3)) && (s3==1)) { //Update counter on low pulse scount3=count3; s3=0; d_ready=1; } if (count3>250) { scount3=count3; d_ready=1; } } } //now scount1 and scount2 have echo values if (d_ready==1) { disable_interrupts(GLOBAL); if (turn==1) { if (scount1