'********************************************************************************************* ' Sonar-ranger.bas ' Program to control the Devantech SRF04 ultrasonic module. Measure ' the distance between the the unit and an object. Convert the raw ' data to inches and centimeters and then send the results to an LCD ' display. PicBasic Pro Compiler by MicroEngineering Labs. The ' conversion factors listed in the SRF04 manual are for the PULSIN ' of a Basic Stamp II which measures in 2us increments. When running ' a PICmicro MCU at 4 MHz and using the PicBasic Pro compiler the ' PULSIN command measures in 10us increments and the PULSOUT command ' also generates pulses with 10us increments. The adjusted conversion ' factors for 10us increments are: ' inches = raw_data / 15 ' centimeters = raw_data / 6 '********************************************************************************************* Include "modedefs.bas" ' Include serial modes trisa = %00000000 ' set porta to outputs trisb = %00001000 ' set portb pin 3 to input lcd var PORTA.3 ' define variables and constants piezo var PORTB.4 trigger var PORTB.2 echo var PORTB.3 left_led var PORTB.0 right_led var PORTB.1 baud con N2400 dist_raw var word dist_inch var word dist_cm var word conv_inch con 15 conv_cm con 6 low trigger ' set trigger pin to logic 0 low left_led ' turn off left LED low right_led ' turn off right LED Serout lcd,baud,[254,1] ' clear lcd screen pause 1000 ' give time to initialize lcd Serout lcd,baud,[254,128,"- Sonar Ranger -"] ' display program title on the LCD sound piezo,[100,10,50,5,70,10,50,2] ' Make startup sound pause 1000 ' wait for 1 second Serout lcd,baud,[254,128,"inches: "] ' set up the LCD display Serout lcd,baud,[254,192,"centimeters: "] main: gosub sr_sonar ' get sonar reading Serout lcd,baud,[254,135,#dist_inch," "] ' display the distance in inches Serout lcd,baud,[254,204,#dist_cm," "] ' display the distance in centimeters Goto main end sr_sonar: pulsout trigger,1 ' send a 10us trigger pulse to the SRF04 pulsin echo,1,dist_raw ' start timing the pulse width on echo pin dist_inch = (dist_raw/conv_inch) ' Convert raw data into inches dist_cm = (dist_raw/conv_cm) ' Convert raw data into centimeters pause 1 ' wait for 10us before returning to main return