'// Author John Hale, Copyright Active Robots 2003/2004 '// This code may be used in part for any project provided '// its source is recognised. '//This code will 'fire' the 600 series smart-sensor once '//every 3 seconds reporting the distance in cm via the serial port '//at 9600 baud. I have used Port B, pin 7 as the Init line and pin 6 '//as the echo line. '//Method of operation: The timer is started, the init line is taken '//high. Wait for the echo line to go high, then stop the timer. The '//length of time taken for the echo to return can now be calculated '//from the loop counter and the timer contents register. '//Set definition file and crystal $regfile = "m8535.dat" $crystal = 16000000 '//Configure PortB Config Portb = Input Portb = &B01000000 Config Pinb.7 = Output '//Dim required variables Dim Loop_cnt As Long Dim Clk_cnt As Long Dim Elapsed_time As Single Dim Range As Long '//Configure Timer0 as a timer, set the prescale to 8 Config Timer0 = Timer , Prescale = 8 '//Define the ISR handler, enable interupts and timer On Ovf0 Tim0_isr Enable Timer0 Enable Interrupts Do Waitms 1500 '//Set timer and loop counter to zero Tcnt0 = 0 Loop_cnt = 0 '// Start the timer Start Timer0 '//fire ultrasonic transducer Portb.7 = 1 '//wait for echo Bitwait Pinb.6 , Set '//Stop the timer Stop Timer0 '//loop_cnt holds 256*8 (8 bit register * prescale) clock cycles, tcnt0 '//holds current clock cycles. '//To find the elapsed time in ms, multiply 256*8*loop_cnt then add tcnt0 Clk_cnt = 256 * 8 Clk_cnt = Clk_cnt * Loop_cnt Clk_cnt = Clk_cnt + Tcnt0 '//now divide by the clock speed/1000 Elapsed_time = Clk_cnt / 16000 '//Speed of sound (return journey) = 5.83milliseconds/metre '//Therefore in cms = 5.83/100 = 0.0583ms '//distance to target in cm = elapsed_time/0.0583 Range = Elapsed_time / 0.0583 Print Range Print '//drop init line ready to start next cycle Portb.7 = 0 Waitms 1500 Loop '//the following code is executed when the timer rolls over, keeping '//a count of the number of times the ISR is executed. Tim0_isr: Loop_cnt = Loop_cnt + 1 Return End