; Mike Nitchie
; Bharat Kuncharavelu
; USART Presentation - Receive code
; 3/31/2014

	LIST	p=16F628		;tell assembler what chip we are using
	include "P16F628.inc"	;include the defaults for the chip
	__config 0x3D18			;sets the configuration settings (oscillator type etc.)

	cblock 	0x20 			;start of general purpose registers
		d1
		d2
	endc
	
	org	0x0000		
	
	movlw	0x07
	movwf	CMCON			;turn comparators off (make it like a 16F84)

	bsf		STATUS,RP0
	movlw	b'00000110'		; Enable TX and RX pins
	movwf	TRISB			
	movlw	0x00
	movwf	TRISA			; ports A and B will be output for display

; wait 1ms to ensure that Transmitter is transmitting
delay
	call 	waitForTransmitter 

setBaudRate
	
	bsf		TXSTA,BRGH		; Select high baud rate
	movlw	d'25'
	movwf	SPBRG			; 9600 baud

configureModes
	bcf	TXSTA,SYNC			; selects Async mode
	bcf	STATUS,RP0
	bsf	RCSTA,SPEN			; Configures PORTB<1,2> as serial ports

enableReception
	bsf	RCSTA,CREN			; Enables reception

;could use an interrupt here instead
waitForData
	btfss	PIR1,RCIF		; RCIF is set when RSR moves data to RCREG
	goto	waitForData

processData
	movf	RCREG,w			; moves received data to w
	call	sevenSegmentDecode
	movwf	PORTA
	movwf	PORTB

prepareForMore
	clrf	RCREG			; Allows reception of more data
	goto	waitForData

sevenSegmentDecode
	addwf	PCL,f
	retlw	B'01011111'		; decode 0
	retlw	B'00000110'		; decode 1
	retlw	B'10011011'		; decode 2
	retlw	B'10001111'		; decode 3
	retlw	B'11000110'		; decode 4
	retlw	B'11001101'		; decode 5
	retlw	B'11011101'		; decode 6
	retlw	B'00000111'		; decode 7

waitForTransmitter
			;993 cycles
	movlw	0xC6
	movwf	d1
	movlw	0x01
	movwf	d2
waitForTransmitter_0
	decfsz	d1, f
	goto	$+2
	decfsz	d2, f
	goto	waitForTransmitter_0

			;3 cycles
	goto	$+1
	nop

			;4 cycles (including call)
	return
	
	end

