	NOLIST
;	This file is part of picide, ATA(PI) interface to PIC18 family MCUs.
;	Copyright (C) 2004-5 Toby Thain, toby@telegraphics.com.au

;	This program is free software; you can redistribute it and/or modify
;	it under the terms of the GNU General Public License as published by  
;	the Free Software Foundation; either version 2 of the License, or
;	(at your option) any later version.

;	This program is distributed in the hope that it will be useful,
;	but WITHOUT ANY WARRANTY; without even the implied warranty of
;	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;	GNU General Public License for more details.

;	You should have received a copy of the GNU General Public License  
;	along with this program; if not, write to the Free Software
;	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
	LIST

	TITLE picide
	SUBTITLE "RS232 Serial"

;; Version history
;; 16-Oct-2004: 0.1 - started by Toby
;; 23-Feb-2005: 1.0 - public release under GPL

; contents of this module:
	global init_rs232	; initialise USART
	global putch,getch	; write/read serial bytes

#include "defs.inc"

#define BAUD9600 64	; BRG value @ lo speed, 40MHz clock

	code

init_rs232:
	; configure port pins
	bsf TRISC,6	; set both pins as INPUTS
	bsf TRISC,7	; the USART reconfigures as needed
	movlw BAUD9600
	movwf SPBRG	; set rate
	bcf BAUDCON,BRG16 ; using 8 bit BRG
	movlw b'00100010' ; 8-bit tx,txen,async,lo speed,tsr empty
	movwf TXSTA
	movlw b'10010000' ; spen,8-bit rx,cren
	movwf RCSTA
	return

getch:	btfss RCSTA,OERR	; seen an overrun?
	bra rxch		; no
	bcf RCSTA,CREN		; yes. reset receive
	bsf RCSTA,CREN
	; framing errors are automatically reset on next valid byte
rxch:	  clrwdt ; if watchdog timer is enabled
	  btfss PIR1,RCIF	; received a char?
	  bra rxch	; no. check again
	movf RCREG,w
	return

putch:	  clrwdt ; if watchdog timer is enabled
	  btfss PIR1,TXIF	; txmit buffer full?
	  bra putch	; no. check again
	movwf TXREG
	return

	end
