TITLE "Example on using RS_bodySEND, RS_bodyRECEIVE macros"
;------------------------------------------------------------
;      Copyright: Eugene M. Hutorny © 2003,eugene@ksf.kiev.ua
;      Revision:  V0.01
;      Date:      Feb 25, 2003
;      Assembler: MPASM version 3.20.07
;------------------------------------------------------------
; Example on using RS_bodySEND, RS_bodyRECEIVE macros
;------------------------------------------------------------
			include         "p16f84a.inc"
			include			"rs.inc"
			
#define CLOCK 		.4000000
#define	RX	PORTB,0			; RX Pin,  RB0, input 
#define	TX	PORTB,1			; TX Pin,  RB1, output
#define CTS PORTB,2			; CTS pin, RB2, output 
#define RTS PORTB,6			; RTS pin, RB6, input
#define	RS_BITCOUNT	.8
#define RS_BUFFSIZE .16

	UDATA
TMP_WREG	res 1			; temporary storage for WREG
TMP_STATUS	res 1			;          - " -        STATUS
RS_DATA		res 1			; file register used in RS
RS_COUNT	res 1			; bit counter
RS_ALIGN	res 1			; alignment bits
RS_COUNTER	res 1			; recieved/echoed counter
RS_BUFFER	res RS_BUFFSIZE	; data buffer

nope	macro		; nop 2 cycles long
	goto $+1		
  endm
  
RS	CODE
RS_SEND
	RS_bodySEND .115200, RS_BITCOUNT, TX, 0
	return	

;---------------------------------------------------------------------------
RS_READBUFF					; READ incoming data to buffer
	bcf		INTCON, INTF
	bsf		INTCON, INTE
	bsf		INTCON, GIE
	bcf		CTS				; transmission shall begin
	clrf	TMR0			; clear timer
	bcf		INTCON, T0IF	; clear timer expiration flag
rx	clrwdt
	btfsc	RTS				; is RTS kept SPACE
	goto	suspend			; no, suspend reception
	tstf	RS_COUNTER		; test is something received
	skpnz					
	goto	rx				; if no bytes yet received, just wait
	btfsc	INTCON, T0IF	; if timer expired
	goto	suspend			; suspend reception
	tstf	RS_COUNTER		; test RS_COUNTER
	skpnz					; if( RS_COUNTER > 0)
	goto	rx				; continue reception
suspend	
	bsf		CTS				; request suspending reception
	clrf	TMR0			; clear timer
	; relaxation period after last byte recived
xr	clrwdt
	movlw	RS_BUFFSIZE - 1
	subwf	RS_COUNTER, W	; RS_COUNTER - (RS_BUFFSIZE - 1)
	skpnc					; if( RS_COUNTER - (RS_BUFFSIZE - 1) > 0)
	goto	readdone					
	btfsc	RTS				; wait if space is kept SPACE
	goto	readdone					
	btfss	TMR0, 2			; time out = 4 timer ticks (1024 IC) ~ 1 ms, good for fast PC's
	goto	xr
readdone
	bcf		INTCON, GIE
	bcf		INTCON, INTE	; disable INT interrupt
	return		

RS_INTERRUPT				; interrupt on RX entry
	movwf	TMP_WREG		; 6: save W
	swapf	STATUS, W		; 7: load STATUS
	movwf	TMP_STATUS		; 8: save STATUS
	bsf		CTS				; 9: request suspending reception
	RS_bodyRECEIVE .115200, RS_BITCOUNT, RX, 0, INDF, .9, -.3
	clrf	TMR0			; 75: clear timer
	incf	FSR, F			; 76: forward buffer pointer
	incf	RS_COUNTER, F	; 77: count this byte
	swapf	TMP_STATUS, W	; 78:
	movwf	STATUS			; 79: restore STATUS
	swapf	TMP_WREG, F		; 80:
	swapf	TMP_WREG, W		; 81: restore W
	bcf		INTCON, INTF	; 82: interrupt handled
	retfie					; 83: leave routine - 2 cycles of one stop bit left

	RS_delays
	END