'****************************************************************
'                                                               *
'    Filename:	     GPS_LED_lib.bas                            *
'    Date:           11/20/2008                                 *
'    File Version:   0.01                                       *
'                                                               *
'    Author:         Peter Putnam                               *
'    email:          peter@ni6e.com                             *
'                                                               *
'    Based on work of Punerjot Singh Mangat                     *
'                                                               *
'****************************************************************
'
' commands are:
' rs232_putch(ASCII value of char to be sent)
' rs232_getch() as byte
' 
' GPIO.5 = RX input
' GPIO.4 = TX output
'
' Baud rate = 4800, Data bits = 8, Parity = none, Stop bits = 1

'******************************* delays for RS232 ******************************
'Wait() sets bit time
' One bit is 208 uSec at 4800 bps
' One instruction is 1 uSec using 4.0 MHz processor clock
'  Therefore, the bit time loop must use 208 instructions
'Wait_1() delays a half-bit time to sample at the middle of a bit

Dim rs232_count as byte

sub wait()
asm
{
MOVLW   d'65'
MOVWF   _rs232_count
LOOP1:
DECFSZ  _rs232_count, F
GOTO    LOOP1
return
}
end sub


sub wait_1()
asm
{
MOVLW   d'33'
MOVWF   _rs232_count
LOOP:
DECFSZ  _rs232_count, F
GOTO    LOOP
return
}
end sub
'**************************** delays for RS232 end *****************************


'************************ RS232 RX procedure ***********************************
'following is the function that receives the byte from the RS232 port. 
' The function waits till a byte is received

function rs232_getch() as byte
Dim bit_no as byte, byteread as byte

bit_no = 8
byteread = 0

do while (gpio.5 = 1)
   _asm nop
loop
'                                       'start bit detected
call wait_1()                           'delay 1/2 bit time
'                                       ' to sample mid-bit
do while (bit_no > 0)
   call wait()
   bit_no = bit_no - 1
   byteread = (byteread >> 1)
   byteread.7 = gpio.5
loop

call wait()

rs232_getch = byteread
end function
'************************ RS232 RX procedure ends ******************************



'************************ RS232 TX procedure ***********************************
'following is the procedure to output a byte to the RS232 port
Sub rs232_putch(c as byte)
Dim bit_no as byte

gpio.4 = 0
bit_no = 9

do while (bit_no > 0) 
   call wait()
   bit_no = bit_no - 1
   gpio.4 = (c & 1)
   c = (c >> 1) | 0x80
loop

gpio.4 = 1
call wait()

end sub
'************************ RS232 TX procedure ends ******************************