'*********************************************************************************************
' range-tone.bas
' Program to control the Devantech SRF04 ultrasonic module. Measure 
' the distance between the the unit and an object. Convert the raw 
' data to a frequency and output to the piezo element so that
' distance is represented by an audible frequency.
' Turn on the LEDs if an object is within 5 inches of the module. 
' PicBasic Pro Compiler by MicroEngineering Labs.
'*********************************************************************************************

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
dist_raw     var word
dist_inch    var word
dist_cm      var word
conv_inch    con 15
conv_freq    con 6
freq         var word

low trigger						' set trigger pin to logic 0
low left_led						' turn off left LED
low right_led						' turn off right LED

main:

     gosub sr_sonar					' get sonar reading
     if freq > 47 then main                             
     sound piezo,[80 + freq,10]                         ' output frequency determined by 
                                                        ' distance
     if dist_inch <= 5 then                             ' if an object is 5 inches or less
          high left_led                                 ' away from the ranger then turn on
          high right_led                                ' the left and right LEDs
     else 
          low left_led                                  ' turn off the left and right LEDs
          low right_led
     endif    

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 
         freq = (dist_raw/conv_freq)		' Convert raw data into a frequency
         pause 1				' wait for 10us before returning to main

return

