'Author: languer (©2013)
'Pin Allocation:
'PIN# Main_Fn Secondary_Fn
'GP0 -> OUT_RS232 ICSP-DAT
'GP1 -> N/A ICSP-CLK
'GP2 -> N/A
'GP3 -> N/A MCLR
'GP4 -> IO_SONAR
'GP5 -> N/A
'Usage Information:
'RS232 Baud Rate: 9600bps
'Comments: PING only works with +5V.
'To use lower voltage, recommend using step-up regulator (e.g NCP1402)
'The SONAR principle determines the distance to an object based on the
'speed of sound(1_inch = 73.746_usec).If a pulse is sent, its distance (in inches)
'to target will be; d_in = (t_usec / 73.746)
'SONAR measures the return pulse, time pulse travels to target and back to the SONAR
'Or d_in = (t_usec / 147.492)
'General Configuration
Define CONF_WORD = 0x33c4
'Oscillator/Clock Configuration for internal 8MHz osc
Define CLOCK_FREQUENCY = 8
OSCCON = 0x71
'Variable Declarations
'>>I/O
Symbol io_rs232_tx = GP0 'rs-232 output
Symbol io_sonar = GP4 'ping/hc-sr04 sensor
'>>Constants
Const _trisio = %11111110
'>>Variables
Dim flag_valid_dist As Bit
Dim _true As Bit
Dim _false As Bit
_true = True
_false = False
'Main Program
main:
Dim distance_in As Word 'distance in inches
Call init()
WaitMs 1000
Serout io_rs232_tx, 9600, CrLf, "Main..."
While _true
flag_valid_dist = False
distance_in = get_distance()
If flag_valid_dist = _true Then
Serout io_rs232_tx, 9600, CrLf, "Distance=", #distance_in, "_in"
Else
Serout io_rs232_tx, 9600, CrLf, "Invalid Measurement"
Endif
flag_valid_dist = False
WaitMs 1000
Wend
End
'init
Proc init()
AllDigital
TRISIO = _trisio
'set TMR1 prescaler to 1:2 -> with 8MHz clock
'this results in tmr1 resolution of 1uS, with maximum of 65.53ms
'or 0.007in resolution, with maximum of 442inches
T1CON.T1CKPS1 = 0
T1CON.T1CKPS0 = 1
'clear global variables
flag_valid_dist = False
Low io_rs232_tx
Low io_sonar
Serout io_rs232_tx, 9600, CrLf, "Power-up..."
End Proc
'get distance procedure
Function get_distance() As Word
Dim echo_time As Word
'transmit pulse
Config io_sonar = Output
High io_sonar
WaitUs 10
Low io_sonar
'receive echo time
'zero-out timer1
TMR1L = 0
TMR1H = 0
PIR1.T1IF = 0
'allow for some holdoff time
WaitUs 200 '8-cycles of 40kHz is 200us, PING recommends 750us
'wait for rising edge of echo pulse
Config io_sonar = Input
While io_sonar = 0
Wend
'turn-on timer1
T1CON.TMR1ON = True
'wait for falling edge of echo pulse or timeout
While io_sonar = 1 And PIR1.T1IF = 0
Wend
T1CON.TMR1ON = False
If PIR1.T1IF Then
echo_time = 0
Else
echo_time.HB = TMR1H
echo_time.LB = TMR1L
flag_valid_dist = True 'flag a valid distance was measured
Endif
'zero-out timer1
TMR1L = 0
TMR1H = 0
PIR1.T1IF = 0
'return value
get_distance = echo_time / 148
End Function