;**************************************************************************
; iicrs0001.ASM
;
; PROGRAM: Simple Serial Project - Modified to explore PIC16F819  IIC module
;
; DESCRIPTION: 
;	simple serial project that receives serial commands to control IIC
;	IIC slave module is enabled and is polled and debug info is sent to serial port.
;   spaces are important
;
;   commands have been added to allow the IIC module to be exprimented with
;
; Uses PIC16F819
;
; Pull up SDA and SCL pins with 4k7 resistors,
;
; SERIAL PORT CONTROL:
;
;	PORT A0 is Serial input
;	PORT A0 is serial output
;
;	usb gmus-03 USB Serial Adapter
;
;	TX  D9 Pin 3 -[4k7]----+-----PA0
;	RX  D9 Pin 2 ----------/
;
;	GND D9 Pin 5 ---------------- 0V
;
 
;
; Serial Commands:-
;
;   ; w,p,r,g,f,a
;
;
; File Regiters
;	<CR>wAADD;		write DD to register AA
;	<CR>rAA;  		read AA and output to serial port
;
; EEPROM
;	<CR>pAADD;		write DD to EEPROM register AA
;	<CR>gAA;  		read EEPROM register AA and output to serial port
;
; PRIPHERALS
;
; IIC master commands to set to slave and master. 
;    Master is done by code. EEPROM
;
;	<CR>iAA;	IIC  init set Addr = AA
;
;	<CR><AA;	IIC START , ADDR , set lsb for R/W
;	<CR>>;		IIC STOP
;	<CR>/DD;	IIC master writeByte
;	<CR>?;	IIC master readByte & ACK.   If you get ~, SCL is being held low and read has timed out.
;	<CR>~;	IIC master readByte & NACK.  If you get ~, SCL is being held low and read has timed out.
;
;	<CR>lAA;	send 40 characters to LCD02 IIC display at address C6 incrementing AA.
;	<CR>LAADD;	read 16 bytes from IIC memory at IIC:0xA0 starting at address AADD, send to RS232.
;   <CR>
;
;	you need to w86FF to set PORT-B & SCL and SDA to IIC inputs.
;	you need to w9340 to set IIC ADDR
;	you need to w1436 to init IIC

; ic1
;
; write to  itself
;
; ic1
;<10;+*-0800-36 stat:FD09 e~A_SW7B
;#iic slave:+ @[10] con:36 stat:09 _~A_SW7B
;/12;+*-0804-36 stat:0929 e~D_SW7B
;#iic slave:+ W[12] con:36 stat:29 _~D_SW7B
;/34;+*-0804-36 stat:2929 e~D_SW7B
;#iic slave:+ W[34] con:36 stat:29 _~D_SW7B
;/56;+*-0804-36 stat:2929 e~D_SW7B
;#iic slave:+ W[56] con:36 stat:29 _~D_SW7B
;>;*-0004-36 stat:2930 e~DP_W7_


;
; read from itself, chip sends a count that increments per read.
;
; ic1
;<11;+*-0800-26 stat:FD0C e~A_SR7_
;
;#iic slave:+ @[11] con:26 stat:0C _.A_SR7_
;#iic slave:+ R[00] con:26 stat:0C _.A_SR7_
;?;=00-0804-26 stat:0C2C e~D_SR7_
;#iic slave:+ R[01] con:26 stat:2C _.D_SR7_

;=01-0804-26 stat:2C2C e~D_SR7_
;#iic slave:+ R[02] con:26 stat:2C _.D_SR7_

;=02-0804-26 stat:2C2C e~D_SR7_
;#iic slave:+ R[03] con:26 stat:2C _.D_SR7_

;=03-0804-26 stat:2C2C e~D_SR7_
;#iic slave:+ R[04] con:26 stat:2C _.D_SR7_

;~;=04-0804-36 stat:2C28 e~D_SW7_
;#iic slave:+ N[04] con:36 stat:28 _~D_SW7_
;>;*-0004-36 stat:2830 e~DP_W7_

;
;   I have an IIC display whose addr is C6
;
;   robot-electronics display:
;   http://www.robot-electronics.co.uk/htm/Lcd02tech.htm
;   There is a later device:
;   http://www.robot-electronics.co.uk/htm/Lcd03tech.htm
;
;   The display uses IIC at address 0xC6. 
;
;	<c6; 	send start and Address
;	/00; send DATA		register
;	/0c; send DATA 0x0c reset and clear display
;	/31; send DATA "1"
;	/32; send DATA "2"
;	/33; send DATA "3"
;	>;
;
;	<c7; 	send start and Address
;	W13DD; write data
;	W1436; set CLK enable
;	?;   master read data. This does an ACK. I need to add a cmd to read data and send NACK.
;	>;
;
;
;	you need to w86FF to set PORT-B & SCL and SDA to IIC inputs.
;	you need to w9340 to set IIC ADDR in this example 0x40  
;	you need to w1436 to init IIC
;
;   The sequence below set the chip to write to itself.
;
; write
; w9340; to set address
; w1400; to reset 
; w1436; to set mode
; <;
; /40;
; r13;
; /45;
; >;
;
; write to display 
; ic1
;<c6;+*-0000-36 stat:FD08 e~A_SW7_
;/00;+*-0000-36 stat:FD08 e~A_SW7_
;/0c;+*-0000-36 stat:FD08 e~A_SW7_
;/39;+*-0000-36 stat:FD08 e~A_SW7_
;>;*-0000-36 stat:FD10 e~AP_W7_

; read 4 bytes
; ic1
;<c7;+*-0000-36 stat:FD08 e~A_SW7_
;?;=40-0000-36 stat:FD08 e~A_SW7_
;;=00-0000-36 stat:FD08 e~A_SW7_
;;=00-0000-36 stat:FD08 e~A_SW7_
;;=03-0000-36 stat:FD08 e~A_SW7_
;~;=40-0000-36 stat:FD08 e~A_SW7_
;>;*-0000-36 stat:FD10 e~AP_W7_




;  if Sbit 
;	   if D/~A == A  ; address - SSPBUF is full with the received Address so BF will be set and must be read.
;		-- SSPBUF is full with the received Address so BF will be set and must be read.
;		-- BF is cleared on read.  BF will be cleared on read, as SSPBuf is emptied.		
;		if R/~W == R ; call readFirst  - slave must prepare and send byte. CKE is reset,Write byte into SSPBUF, enable SCL by setting CKE , Could reset state machine.
;		if R/~W == W ; call writeFirst - SSPBUF is emptied ,slave should read Address, enabling clock.
;
;	   if D/~A == D  ; If R and BF then NACK, except SSPSTAT is reset, so R/W=W, BF = 0 
;		if R/~W == R ; call readNext   - slave must write byte to be read into SSPBUF, BF = 0 
;		if R/~W == W ; call writeNext  - slave must read byte and use, It will hold SCL low while processing byte. BF =Full,wriet byte
;		  if BF =1 then there is data available.
;		  if BF =0 then the last byte read was NACK so no more bytes need to be sent.
;
;  if Pbit
;	 ; iic bus has gone idle 
;	 Obviously Master should only send when Bus has seen Stop
;
  
;
;
; start, addr+r/~w, ACK, data, ACK , data , ACK , stop
;
;
; On IIC int if using SSPCON=36;
;  if Sbit
;	   if D/~A == A  ; address
;		if R/~W == R ; call readFirst  - slave must write byte to be read into SSPBUF , Could reset state machine.
;		if R/~W == W ; call writeFirst - slave could read Address use it, It will hold SCL low while processing byte.
;
;	   if D/~A == D  ; data
;		if R/~W == R ; call readNext  - slave must write byte to be read into SSPBUF
;		if R/~W == W ; call writeNext - slave must read byte and use, It will hold SCL low while processing byte.
;
;  if Pbit
;	 ; iic bus has gone idle 
;
;	 if ( D/~A == A ) && ( BF==1 ) ; Address received
;	   if ( R/~W == W ) then call resetIICwrite;
;	   if ( R/~W == R ) then call resetIICread;
;
;  if ( BF == 0 ) && ( R/~W == R ) ?;
;
; address 0x20 bit 7 controls if interupt is polled.
;
;
; write
; w9340 to set address
; w1400 to reset 
; w1436 to set mode
; <;
; /40;
; r13;
; /45;
; >;
;
; read
; w9340 to set address
; w1400 to reset 
; w1436 to set mode
; <;
; /41;
; w1345;
; w1436 to set CLKE
; ?
; w1377; respond with 77
; w1436 to set CLKE
; ?
; >;
;
;
; AUTHOR:  Douglas Rice
; Copyright 2004
;
;
;**************************************************************************


;--------------------------------------------------------------------------
; Sec 0.1  #Defines tofor different chips
;--------------------------------------------------------------------------

; uncomment only one of these
;

;#define pic16F876 	1
;#define pic16F88  	1
#define pic16F819  	1

#define IICmaster 1

    LIST    w=1, R=DEC



;--------------------------------------------------------------------------
; Sec 0.2 #Defines for 16F876
;--------------------------------------------------------------------------

	ifdef pic16F876
    	LIST    P=16F876, R=DEC
	INCLUDE "p16F876.inc"       

	__idlocs  0x0876
	__CONFIG _CP_OFF & _DEBUG_OFF & _WRT_ENABLE_ON & _WDT_OFF & _BODEN_OFF & _PWRTE_ON  & _HS_OSC & _LVP_OFF

#define 	buildPWM	1
	cblock 0x20
	endc

; *********** I/O EQUATES **************
PORT_RS232	  EQU  PORTA 	    
TRIS_RS232	  EQU  TRISA 	    
RS232tx         EQU  0	; Serial Out
RS232rx         EQU  0	; Serial In needs to be equal to BUTTON_RS232
	endif



;--------------------------------------------------------------------------
; Sec 0.3 #Defines for 16F88
;--------------------------------------------------------------------------

	ifdef pic16F88
    LIST    P=16F88, R=DEC
	INCLUDE "p16F88.inc"       

	__idlocs  0x0088
;	__CONFIG    _CONFIG1,  _XT_OSC & _PWRTE_ON & _WDT_OFF
;	__CONFIG    _CONFIG2,  _IESO_ON & _FCMEN_ON
	
	
	__CONFIG    _CONFIG1, _CP_OFF & _CCP1_RB0 & _DEBUG_OFF &  _CPD_OFF & _LVP_OFF & _BODEN_OFF & _MCLR_OFF & _PWRTE_ON & _WDT_OFF & _INTRC_IO
	__CONFIG    _CONFIG2, _IESO_OFF & _FCMEN_OFF

;#define 	wantAtoD		1


	cblock 	0x20
	endc

PA0             EQU  0		; Serial Out and Serial In
PA1             EQU  1		; Output
PA2             EQU  2		; Output
 
T0IF			EQU TMR0IF	

PORT_RS232	  	EQU  PORTA 	    
TRIS_RS232	  	EQU  TRISA 	    
RS232tx         EQU  PA2	; Serial Out
RS232rx         EQU  PA2	; Serial In needs to be equal to BUTTON_RS232
OUTPUTPIN       EQU  PA1

SCL	EQU	4
SDA	EQU	1

	
	endif	

;--------------------------------------------------------------------------
; Sec 0.5 #Defines for 16F819
;--------------------------------------------------------------------------

	ifdef pic16F819

 
	list      p=16f819           ; list directive to define processor
	#include <p16F819.inc>        ; processor specific variable definitions
	
	__idlocs  0x0819
	
	 errorlevel  -302              ; suppress message 302 from list file
	 
	__CONFIG   _CP_OFF & _WRT_ENABLE_OFF & _CPD_OFF & _CCP1_RB2 & _DEBUG_OFF & _LVP_OFF & _BODEN_OFF & _MCLR_ON & _WDT_OFF & _PWRTE_ON &  _INTRC_CLKOUT


; '__CONFIG' directive is used to embed configuration word within .asm file.
; The lables following the directive are located in the respective .inc file.
; See data sheet for additional information on configuration word settings.

;#define 	wantAtoD		1

	
	cblock 	0x20
	endc
PA0             EQU  0		; Serial Out and Serial In
PA1             EQU  1		; Output
PA2             EQU  2		; Output
	
T0IF			EQU TMR0IF	

PORT_RS232	  	EQU  PORTA 	    
TRIS_RS232	  	EQU  TRISA 	    
RS232tx         EQU  PA0	; Serial Out
RS232rx         EQU  PA0	; Serial In needs to be equal to BUTTON_RS232
OUTPUTPIN       EQU  PA1

;IIC pins on Port B
SCL	EQU	4
SDA	EQU	1
	
	endif	



;--------------------------------------------------------------------------
; Sec 1. Equates and Constants
;--------------------------------------------------------------------------
; The General Purpose Registers start at the end of the 
; Special Purpose Registers.

; IPMentState values
; in normal running or in time setting modes
;

; DoTimeSlice bits
; these bits are set to schedule a timer chain event
DTsS4event	EQU	0	; 

RUN_BUFF		EQU	0	; 
RUN_SLAVE_DEBUG	EQU	1	; 

; IPtrigMenu
DTSFast			EQU	0

;--------------------------------------------------------------------------
; Sec 1.1 Button and LED 
;--------------------------------------------------------------------------

BUTTON_RS232	EQU	RS232rx	; EDG  - Bottom Buttom
BUTTON_DOWN		EQU	6		; EDG  - Bottom Buttom

;--------------------------------------------------------------------------
; Sec 2.0 Variables
;--------------------------------------------------------------------------
; Variables start 0x0C
;

;	DoTimeSlice Bits, to schedule, set bit

	cblock 	
IICflags ; 

DoTimeSlice

IPnew
IPlast
IPbuttonEvent

IPnewFast
IPlastFast
IPbuttonEventUp

IPtrigMenu

;
; 
;
RSiicState	;	set to @,R,W,N
RSiicByte	;   set to last received byte

; variables used by Serial input and output routines
RStxTemp
RSloopCnt

RSdelayCnt
RSin
RSout
RSinterCharDelay
RSafterCRCharDelay

; Serial input buffer
RSipBuffCnt ; input buffer counter
; start of buffer
RScmd
RSAa		;
RSaA		;
RSDd		;
RSdD		;
RSterminator
; end of buffer

; temporary variables
RSaddr
RSdata
;
; IIC data
;
; variables used by IIC routines
IICtmp
IICwaitCnt
IICflg

IICloopCnt	; counts 8 bits
IICtxTemp	; temporary copy of the character to be transmitted
IICbusBits	; temporary copy of SCL and SDA

IICslaveDataSource  
IICslaveDataSink  

	ENDC

	;
	; Put some variables in the common bank
	;
	cblock 	0x70
IICtmpCon
IICtmpCon2
IICtmpStat	
IICtmpStat2	

LCDptr

	endc

	

;--------------------------------------------------------------------------
; Sec 3. MACROS
;--------------------------------------------------------------------------


TEST_STRADDLE	MACRO	START
	if high( $ ) != high( START ) 
	    Error "Table straddles Page Boundary " + Start
	endif
	endm

;--------------------------------------------------------------------------
; Sec 4. Program Code
;--------------------------------------------------------------------------
	ORG     0       
	goto    Start
	MOVLW	04

	ORG 	4
	RETFIE
	goto 	Intrtn

;--------------------------------------------------------------------------
; Sec 4.1	Jump Table keep in bottom segment to keep it easier
;--------------------------------------------------------------------------

LCDgetByte
  
  	; LCDptr has been set to Absolute position of string in lookup table.
  	;
	; we should have set up PCLATH
	; When LCDstrPtr gets to 0xFF
	;	MOVLW	high $
	;	MOVWF	PCLATH 
	;

; use absolute 	address in LCDptr
	clrf	PCLATH
	movfw	LCDptr		; get the pointer
	incf	LCDptr,f 	; post increment the pointer
	movwf	PCL			
	
LCDstr1
	DT	"  -- iirs001.asm --  "
	; need to end string	
	retlw	0	

;--------------------------------------------------------------------------
; Sec 4.2	Jump Table associated functions.
;--------------------------------------------------------------------------
;
; LCDdispStr - function to write bytes from lookup table to IIC display.
;
; W contains absolute pointer
; assumes START,C6 already written
; does not sent STOP
;
LCDdispStr
	movwf	LCDptr

LCDdispStrLoop
  	; output string to display
  	call	LCDgetByte
  	; look for NULL at end of the string to terminate it
  	xorlw	0	
  	skpnz	
  	return
  	call	IIctxCharW		; send the byte to the IIC buss.
  	goto  LCDdispStrLoop 
  	

;--------------------------------------------------------------------------
; Sec 4.3	Main Program Init Code
;--------------------------------------------------------------------------

Start
	ifdef 	OSCCON

	banksel	OSCCON
	; set OSC to 4 Mhz
	movlw	6 << IRCF0	; 4 Mhz
	movwf	OSCCON

	; don't wait
	banksel	0
	
	endif
	
	CLRF	IICflags
	
	call 	INinit
	call	IICinit	
	call	INsayHello	
	;
	; NOTE: IICsayHello	is called before the display has initalised.
	;
	call	IICsayHello	
	call	IICinit	
	goto	MainLoop


;--------------------------------------------------------------------------
; Sec 5.0	Main Loop Program 
;--------------------------------------------------------------------------

MainLoop	
	call	IPtimesliceFast
	
	; test for rising edge
	btfsc	IPbuttonEventUp,BUTTON_RS232	; RS232 input start 
	call	IPrs232
	
	;
	; Use IIC needs servicing.
	;
	btfsc	PIR1,SSPIF
	call	IICslave

	MOVF	DoTimeSlice,w
	bz		MainLoop

	;
	;	If a serial character has been received, Run DLrunBuff.
	;
	btfsc	DoTimeSlice,RUN_BUFF
	call	DLrunBuff

	btfsc	DoTimeSlice,RUN_SLAVE_DEBUG
	call	RSprintSlaveDebug

	goto 	MainLoop
	


;--------------------------------------------------------------------------
; Sec 6.	Subroutines, procedures and functions
;--------------------------------------------------------------------------


;--------------------------------------------------------------------------
; Sec 6.1	Button Poll Routine
;--------------------------------------------------------------------------
		
IPtimeslice
	;	--_____	button press
	;	----___	
	
	;	__-----  /IPnew
	;	----___  IPlast
	;	__--___  
	;
	;
	;
	; This reads all Port A inputs and looks for Press
	MOVFW	IPnew
	MOVWF	IPlast
	MOVFW	PORTA
	MOVWF	IPnew
	; IP last contains new setting, IPlast contains previous
	; look for falling edges
	COMF	IPnew,W
	ANDWF	IPlast,W
	; now force IPbuttonEvent bits to high for new pressed button
	; the service routine should reset the bit to clear the event.
	IORWF	IPbuttonEvent,F
	RETURN

IPtimesliceFast
	; Look for rising edges
	MOVFW	IPnewFast
	MOVWF	IPlastFast
	MOVFW	PORT_RS232
	MOVWF	IPnewFast

	COMF	IPlastFast,W
	ANDWF	IPnewFast,W
	IORWF	IPbuttonEventUp,F
	RETURN

;--------------------------------------------------------------------------
; Sec 6.2	.1 run process on request
;--------------------------------------------------------------------------

DLrunBuff
	BCF	DoTimeSlice,RUN_BUFF
	
	MOVFW	RSin			
	call	RSbuffInput
	return
	


;--------------------------------------------------------------------------
; Sec 6.3	 Button Input functions
;--------------------------------------------------------------------------


IPdownPressed 
	BCF IPbuttonEvent,BUTTON_DOWN
	return


IPrs232
	BCF IPbuttonEventUp,BUTTON_RS232
	goto RSrs232in 	


;--------------------------------------------------------------------------
; Sec 6.4	 Clock Chain Routine
;--------------------------------------------------------------------------
		
CLtimeslice
	;
	BTFSS	INTCON,T0IF
	RETURN

	; TMR0 timeout
	BCF		INTCON,T0IF
	BSF		DoTimeSlice,DTsS4event
	
	call	IPtimeslice
	RETURN


;--------------------------------------------------------------------------
; Sec 6.5 	Serial Input Routine
;--------------------------------------------------------------------------

;**************************************************
RSrs232in

; Test is in main loop or uncomment code below to
; spin for a start bit 
;		CLRWDT
;		BTFSS	PORT_RS232,RS232rx	
;		goto	RSrs232in		
		
		
	; call	RSdelayBit			; delay through Stop Bit
	call 	RSdelayHalfBit		; delay halfway into first bit

	movlw	8
	movwf	RSloopCnt
RSrs232inL0
	call	RSdelayBit			; delay halfway into first bit

	MOVFW	PORT_RS232
	ANDLW	 1<< RS232rx		; mask off bit
	ADDLW	-1<< RS232rx		; use ripple carry to move into C
	RRF		RSin,F
	
	; call	RSdelayBit
	DECFSZ	RSloopCnt,f
	goto	RSrs232inL0

	; do not test for Stop bit
	COMF	RSin,f
	BSF		DoTimeSlice,RUN_BUFF
	RETURN
	

;--------------------------------------------------------------------------
; Sec 6.6 	Serial Output Routines
;--------------------------------------------------------------------------

RSwrtHexNibble	; currently only displays 0..9, A..F
	ANDLW	0x0F
	ADDLW	0x06	; is it A..F, if so trigger a digit overflow
	SKPNDC
	ADDLW	7; subtract 10, then add 'A'-'0'
	ADDLW	0x30-6	; Subtract extra 6 added to cause DC
	MOVWF	RSout
	goto	RStxChar

RStxChar
	;
	; Output Start Bit
	; Start bit is low, data bits are inverted
	;
	
	banksel	RStxTemp
	movwf	RStxTemp
	comf	RStxTemp,f
	BANKSEL 	PORT_RS232
	BCF		PORT_RS232,RS232tx

	; Make RS232 pin an ouput while transmitting character
	BANKSEL  TRIS_RS232		
	BCF		TRIS_RS232,RS232tx
	BANKSEL  PORT_RS232		

	; 1200 baud output
	; move the char into RStxtemp, it is destroyed.

	; zzz_-xxxxxxxx__

	;
	; Do one more stop bit for luck 
        ;
	; This was needed on my XP machine
	; but has not been needed before. 
	;

	;
	BCF		PORT_RS232,RS232tx
	call	RSdelayBit

	;Start Bit
	BSF		PORT_RS232,RS232tx

	call	RSdelayBit
	movlw	8
	movwf	RSloopCnt

RStxCharLp1
	
	; After start bit, which is 1, then test each bit
	; I need to set PA:0 to same as LSB RStxTemp
	; this compares PA:0 with RStxTemp so see if it needs toggling
	; The xorwf PORT_RS232,f causes the bit to be toggled if required.
	
	RRF		RStxTemp,f
	movfw	STATUS
	andlw	1 << C			; mask off bit
	addlw   ( 1 << RS232tx) -1	; shift bit by using a ripple carry
	xorwf	PORT_RS232,W			; Doeas output need toggling ?
	andlw	1 << RS232tx		; Mask off output pin	
	xorwf	PORT_RS232,f			; Toggle output pin if needed	
	call	RSdelayBit			; delay bit
	
	
	decfsz	RSloopCnt,f
	goto	RStxCharLp1

	BCF		PORT_RS232,RS232tx
	call	RSdelayBit	; apply stop bit

	; apply an inter character delay of  4 bits
	; call	RSdelayBit
	; get inter character delay from the EEPROM

	; you have to read from RAM, and not EEPROM as pXXXX; does not work as EEwrt needs delay before EEread 
	MOVFW	RSinterCharDelay
RStxCharInterDelay	
	movwf	RSloopCnt

RStxCharLp2
	call	RSdelayBit
	decfsz	RSloopCnt,f
	goto	RStxCharLp2


	; Make RS232 pin an input so that main loop can test for start bit
	BANKSEL  TRIS_RS232		
	BSF		TRIS_RS232,RS232tx
	BANKSEL  PORT_RS232		

	RETURN


; timing functions to delay serial routines for a bit or half bit.

RSdelayHalfBit		
	MOVLW	0x1D		; shorten delay as edge detector takes about 22 us for 4800 baud
	goto	RSdelayBit0			

RSdelayBit		
	NOP
	MOVLW	0x40	 ; for 4800 baud	

RSdelayBit0			
	MOVWF	RSdelayCnt
RSdelayBit1	
	DECFSZ	RSdelayCnt,f		; 1
	goto	RSdelayBit1		; 2 clk
	CLRWDT
	RETURN

;---------------------------------------------------------------------------------------
; Sec 7.1 	IIC Routines - low level routines to do wired Or
;---------------------------------------------------------------------------------------

;
; The IIC buss should have 4k7 ohm pull ups from SDA and SCL to +5V
;
; Use TRIS to do wired OR
; set TRIS bit to 0 to assert 0
; set TRIS bit to 1 to let buss float high
;
;

IICtris
	MOVLW	0x00
	goto	IICwriteTris

IICtrisSDA
	MOVLW	0x00 | 1 <<   SDA  
	goto	IICwriteTris

IICtrisSDASCL
	MOVLW	0x00 | 1 <<   SDA  | 1 <<   SCL
	goto	IICwriteTris

IICtrisSCL
	MOVLW	 1 <<   SCL
	goto	IICwriteTris

IICwriteTris
	;
	; 
	; save bits
	;
	banksel	IICbusBits
	movwf	IICbusBits
	movlw   ~ ( 1 << SDA | 1 << SCL )
	;iorlw	0xED
	;
	; force PORTB bits lows
	;
	banksel PORTB
	; clrf	PORTB
	ANDWF	PORTB,f

	;
	;	Do Wired Or in IIC bus using TRIS 
	;
	movfw	IICbusBits
	; force TRISB bits, leaving other bits unaffected
	; W = want
	banksel TRISB
	xorwf	TRISB,w
	; want xor TRISB
	; mask off bits needing changing
	andlw	1 << SDA | 1 << SCL ;  
	;  for masked bits are zero and will not change bits 
	; for unmasked bits ( want xor TRISB xor TRISB ) equals  want
	xorwf	TRISB,f
 	banksel PORTB
 	return


	

;---------------------------------------------------------------------------------------
; Sec 7.2 	IIC Routines - low level routines - start,stop,restart, tx , rx , ack, nack
;---------------------------------------------------------------------------------------


IIcStart
     movlw	0
     movwf	PORTB
	; Apply IIC start
	; SCL on RB4
	; SDA on RB1
	; SCL ----\______
	; SDA --\___
	call	IICtrisSDASCL
	call	IICtrisSCL
	call	IICtris
	RETURN

IIcStop
	; Apply IIC start
	; SCL on RB4
	; SDA on RB1
	; SCL ____/-------
	; SDA ______/-----
	call	IICtris
	call	IICtrisSCL
	call	IICtrisSDASCL
	RETURN

IIcReStart
     movlw	0
     movwf	PORTB
	; Apply IIC start
	; SCL on RB4
	; SDA on RB1
	; SCL ___/----\___
	; SDA _/----\_____
	call	IICtris
	call	IICtrisSDA
	call	IICtrisSDASCL
	call	IICtrisSCL
	call	IICtris
	RETURN

IIctxCharW
IIctxChar
	;
	; Output One Byte which is in W
	;
	banksel IICtxTemp
	movwf	IICtxTemp

	movlw	8
	movwf	IICloopCnt
	
	BANKSEL IICflg
	clrf	IICflg
	
IIctxChar0
    ; set SDA and SCL low
	call	IICtris

	;
	; Look at MSB of Byte to be transmitted to decide if 1 or 0.
	;
	BTFSS	IICtxTemp,7
	goto	IIctxChar1	

    ; clock out ONE , set data high
	call	IICtrisSDA

    ; clock out ONE , set clock high
	call	IICtrisSDASCL

	; is clock high as requested?
	BANKSEL  PORTB
	BTFSS	PORTB,SCL
	BSF		IICflg,0

    ; clock out ONE , set clock high
	call	IICtrisSDA
	
	goto	IIctxChar2
	
IIctxChar1
    ; clock out ZERO
	; set CLK
	call	IICtrisSCL
	;
	; Check to see that clock has gone high.
	;
	BANKSEL  PORTB
	BTFSS	PORTB,SCL
	BSF		IICflg,0

	call	IICtris
		
IIctxChar2	
	banksel  IICtxTemp
	rlf		IICtxTemp,f
	
	DECFSZ	IICloopCnt,f
	goto	IIctxChar0

    ; Clock out ACK
    ; This is not tested	
	call	IICtrisSDA

	; set clock high
	call	IICtrisSDASCL

	; we don't do any thing here
	; NACK indicates slave has not ACK'd byte, may not be listeneing.

	; no SCL pulse was clamped by SCL stretching to hold back clocking
	
	;
	; output + for ACK and - for NACK and = for SCL clamped
	;
	banksel  PORTB

	MOVLW	'+'
	; test if SDA has been pulled low by other end
	btfsc	PORTB,SDA
	MOVLW	'-'
		
	; no SCL pulse was clamped
	banksel	IICflg
	btfsc	IICflg,0
	MOVLW	'='

	; IICflg is not used so store Char in IICflg
	movwf	IICflg

	; take clock low.
	call	IICtrisSDA

	; print out ACK to RS232
	banksel IICflg
	movfw	IICflg
	call 	RStxChar	

	return	


IIcrxChar
	;
	; 
	; Start bit is low, data bits are inverted
	;
	BCF		PORTB,2	
	movlw	8
	movwf	IICloopCnt
	
	; SCL ____
	; SDA ____
	call	IICtris

    ; allow data to rise
	call	IICtrisSDA
	
IIcrxChar0
	; test if SCL line has gone high, if not loop until it does
	clrf	IICwaitCnt

IIcrxChar0a

    ; now Allow clock to goto 1
	call	IICtrisSDASCL

	; decrement counter
IIcrxChar1
	decfsz	IICwaitCnt
	goto	IIcrxChar2
	
	;
	; CLK not gone high timeout
	;
	; turn on Blue LED if CLK does not go high.
	;
	BSF		PORTB,2
	return	
	
	
IIcrxChar2
	BTFSS	PORTB,SCL   
	goto 	IIcrxChar0a
	
    ; test bit;
	BCF		STATUS,C
	btfsc	PORTB,SDA
	BSF		STATUS,C
	rlf		IICtxTemp,f

	; reset clock
	call	IICtrisSDA
	
	decfsz	IICloopCnt,f
	goto	IIcrxChar0a

	return	

IIcrxAck
	;
	; ACK
	;

	; assert data for ACK
	call	IICtris
	; now clock ACK 
	call	IICtrisSCL
	call	IICtris
    movfw	IICtxTemp
	return	

IIcrxNAck
	;
	; NACK
	;

	; assert data for ACK
	call	IICtrisSDA
	; now clock ACK 
	call	IICtrisSDASCL
	call	IICtrisSDA
    movfw	IICtxTemp
	return	



;--------------------------------------------------------------------------
; Sec 7.3 	IIC Routines - these do not use the chip's slave IIC hardware
;--------------------------------------------------------------------------


IICinit
	;
	; Set address to 0x10
	;	
	MOVLW 	0x10
IICinitAddr
    banksel SSPADD
	MOVWF  	SSPADD

	MOVLW 	0xFF
    banksel TRISB
	MOVWF  	TRISB
	
	;
	; Set IIC mode
	;
	MOVLW 	0x36
    banksel SSPCON
	MOVWF  	SSPCON
	return

	;
	; routine to 
	;
	;
;	
;Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
;Value on
;POR, BOR
;Value on
;all other
;Resets
;0Bh,8Bh
;10Bh,18Bh
;INTCON GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF 0000 000x 0000 000u
;0Ch PIR1 — ADIF — — SSPIF CCP1IF TMR2IF TMR1IF -0-- 0000 -0-- 0000
;8Ch PIE1 — ADIE — — SSPIE CCP1IE TMR2IE TMR1IE -0-- 0000 -0-- 0000
;86h TRISB PORTB Data Direction Register 1111 1111 1111 1111
;13h SSPBUF Synchronous Serial Port Receive Buffer/Transmit Register xxxx xxxx uuuu uuuu
;14h SSPCON WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 0000 0000 0000 0000
;94h SSPSTAT SMP CKE D/A P S R/W UA BF 0000 0000 0000 0000
;Legend: x = unknown, u = unchanged, - = unimplemented, read as ‘0’. Shaded cells are not used by the SSP in SPI™ mode.	
; start, addr+r/~w, ACK, data, ACK , data , ACK , stop
;
;
; On IIC int
;
;  if Sbit 
;	   if D/~A == A  ; address - SSPBUF is full with the received Address so BF will be set and must be read.
;		-- SSPBUF is full with the received Address so BF will be set and must be read.
;		-- BF is cleared on read.  BF will be cleared on read, as SSPBuf is emptied.		
;		if R/~W == R ; call readFirst  - slave must prepare and send byte. CKE is reset,Write byte into SSPBUF, enable SCL by setting CKE , Could reset state machine.
;		if R/~W == W ; call writeFirst - SSPBUF is emptied ,slave should read Address, enabling clock.
;
;	   if D/~A == D  ; If R and BF then NACK, except SSPSTAT is reset, so R/W=W, BF = 0 
;		if R/~W == R ; call readNext   - slave must write byte to be read into SSPBUF, BF = 0 
;		if R/~W == W ; call writeNext  - slave must read byte and use, It will hold SCL low while processing byte. BF =Full,wriet byte
;		  if BF =1 then there is data available.
;		  if BF =0 then the last byte read was NACK so no more bytes need to be sent.
;
;  if Pbit
;	 ; iic bus has gone idle 
;	 Obviously Master should only send when Bus has seen Stop
;
; writeFirst
; 
;
;

IICslave
	; IIC int flag has been set so process byte.
	
	; Write: lowercase done by master
	; start, addr + w, ACK, data, ACK , data , ACK , stop
	
	; Read: UPPERCASE done by SLAVE
	; start, addr + r, ACK, DATA, ack , DATA , ack , stop
	
	;
	; Disable Int using bit 7 of 0x20
	; 
	;	banksel  IICflags
	;	btfsc	IICflags,7
	;	RETURN

	;
	; buffer  SSPCON, SSPSTAT  
	;
;	banksel DoTimeSlice
;	BSF		DoTimeSlice,RUN_SLAVE_DEBUG

	banksel	SSPCON
	movfw	SSPCON

	banksel IICtmpCon2
	movwf	IICtmpCon2
	
	banksel SSPSTAT	
	movfw	SSPSTAT
	banksel IICtmpStat2
	movwf	IICtmpStat2

	
IICslave1
	banksel  SSPSTAT	
	btfsc	SSPSTAT,S
	goto	IICslaveStart

	btfsc	SSPSTAT,P
	goto	IICslaveStop
	goto	iicslaveEndRtn

	
iicslaveEndRtn
	banksel	PIR1
	BCF		PIR1,SSPIF

	bsf		DoTimeSlice,RUN_SLAVE_DEBUG	
	RETURN
	
	
IICslaveStart
	banksel SSPSTAT	
	btfsc	SSPSTAT,D_A
	goto	IICslaveData
	goto	IICslaveAddress
	
	
IICslaveAddress
	;
	; Address by seen, use this to reset state machine.
	;
	;
	banksel IICflags
	BSF		IICflags,2
	; D_A = ADDR
	; if R_W = W then write, no need to do anything for the write
	; if R_W = R then READ and first byte needs to be read.	
	;
	; check BF, ADDR should be in SSPBUF and must be read.
	;
	;
	; ADDR is availabe and read. If W set then return.
	;
	movlw 	'@'
	banksel	RSiicState
	movwf	RSiicState

	banksel SSPBUF
	movfw	SSPBUF
	
	; store received byte.
	banksel	RSiicByte	
	movwf	RSiicByte

	;
	; If this a read or a write?
	;
	banksel	SSPSTAT
	BTFSS	SSPSTAT,R_W
	goto	IICslaveAddressW

	call	RSprintSlaveDebug

	movlw 	'R'
	banksel	RSiicState
	movwf	RSiicState
	
	;
	; ADDR received and R set so need to send byte
	; need to start READ and write to SSPBUFF
	;
	; As this is an Address reset read State Machine.
	;
	banksel IICslaveDataSource
	clrf	IICslaveDataSource
	movfw	IICslaveDataSource
	; save byte to be set to Master.
	banksel	RSiicByte	
	movwf	RSiicByte
	
	;
	; W contains first byte to be sent so write into SSPBUF
	;
	banksel SSPBUF
	movwf	SSPBUF
	;
	; Byte ready to be send remove clamp on clock to allow master to clock chip.
	; is this required? Seems to be
	banksel SSPCON
	BSF		SSPCON,CKP
	
IICslaveAddressW
	goto	iicslaveEndRtn

	
IICslaveData
	; S,D, 
	btfsc	SSPSTAT,R_W
	goto 	IICslaveDataRead
	
IICslaveDataWrite
	;
	; chip is being written to so read byte, if BF Set.
	; If S,D,W,BF=full, then byte just received and ACK'D.

	; If S,D,W,BF=empty, then last read was NACK'd and SSPSTAT was reset.
	; Check that there is data to be read, Master NACK last byte to end SLAVE transmission.
	; There is not need to sen another byte and SSPSTAT is reset fo R/W = W and BF = empty 
	;
	BTFSS	SSPSTAT,BF
	goto 	IICslaveDataReadNACK		; NACK of read resets SSPSTAT 
	
	;
	; S,W,BF - need to read byte received from master
	;
	movlw 	'W'
	banksel	RSiicState
	movwf	RSiicState

	banksel  SSPBUF
	movfw	SSPBUF
	banksel	RSiicByte
	movwf	RSiicByte

;	call	iicslaveProcessWriteByte

	goto	iicslaveEndRtn


iicslaveProcessWriteByte
	movwf IICslaveDataSink
	;
	; write out received byte to serial port.
	; normally you should call a state machine to sink the received bytes.
	;
	RETURN
	
IICslaveDataRead
	;
	; chip is being read so supply byte to be read.
	;
	
	movlw 	'R'
	banksel	RSiicState
	movwf	RSiicState

	;
	; call function to prepare a byte to send to the master.
	;
	call	iicslaveProcessReadByte
	;
	; store it so it can be displayed
	banksel	RSiicByte
	movwf	RSiicByte
	
	
	;
	; put byte into send buffer
	;
	banksel SSPBUF
	movwf	SSPBUF

	;
	; Byte ready to be send remove clamp on clock to allow master to clock chip.
	;
	banksel SSPCON
	BSF		SSPCON,CKP

;	banksel IICflags
;	BSF		IICflags,3

	goto	iicslaveEndRtn

iicslaveProcessReadByte
	; function to supply byte
	; simulate an data source by incrementing a byte and writing this into SSPBUFF
	; You should call a state machine to supply reall information here.
	incf	IICslaveDataSource,f
	movfw    IICslaveDataSource	

	RETURN

IICslaveDataReadNACK
	; last byte sent was NACK'd,
	; This is valid and indicates that master does not want any more bytes
	; datasheet says SSPSTAT is reset and awaits next star.
	
	; No need to prepare another byte to be read
	; Possibly 
	;
	MOVLW	'N'
	banksel	RSiicState
	movwf	RSiicState

	goto	iicslaveEndRtn





IICslaveStop
	;
	; stop bit 
	;
	banksel IICflags
	BSF		IICflags,4
	
	MOVLW	0x0D
	call 	RStxChar
		
	MOVLW	0x0A
	call 	RStxChar
	
	movlw 's'
	banksel	RSiicState
	movwf	RSiicState

	movlw 's'
	call 	RStxChar
	
	movlw 't'
	call 	RStxChar
	
	MOVLW	0x0D
	call 	RStxChar
		
	MOVLW	0x0A
	call 	RStxChar
	
	goto	iicslaveEndRtn

;--------------------------------------------------------------------------
; Sec 7.4 	IIC Routine - Print out a banner
;--------------------------------------------------------------------------

IICsayHello
	call	IIcStart

	; send Address 0xC6	
 	movlw	0xC6
 	call	IIctxCharW

	; send to register 0x00
 	movlw	0x00
 	call	IIctxCharW

	;
 	; send characters.
 	movlw	0x0c
 	call	IIctxCharW

    ;
    ; disply "start" or "stop" when button 1,2 pressed
    ;

 	movlw	LCDstr1 ; " -- iicrs001.asm  -- "
	call 	LCDdispStr		
	call	IIcStop
	
	return	

;--------------------------------------------------------------------------
; Sec 8.0	
;--------------------------------------------------------------------------


;--------------------------------------------------------------------------
; Sec 9.0 	RS232 routines 
;--------------------------------------------------------------------------

RSprintSlaveDebug
	banksel	DoTimeSlice
	bcf		DoTimeSlice,RUN_SLAVE_DEBUG

;	MOVLW	0x0D
;	call 	RStxChar
		
;	MOVLW	0x0A
;	call 	RStxChar
	
	MOVLW	'#'
	call 	RStxChar
	MOVLW	'i'
	call 	RStxChar
	MOVLW	'i'
	call 	RStxChar
	MOVLW	'c'
	call 	RStxChar
	MOVLW	' '
	call 	RStxChar
	MOVLW	's'
	call 	RStxChar
	MOVLW	'l'
	call 	RStxChar
	MOVLW	'a'
	call 	RStxChar
	MOVLW	'v'
	call 	RStxChar
	MOVLW	'e'
	call 	RStxChar
	
	MOVLW	':'
	call 	RStxChar


	;RSiicState	;	set to @,R,W,N
	;RSiicByte	;   set to last received byte

	movfw	IICflg
	call 	RStxChar

	MOVLW	' '
	call 	RStxChar
	
	movfw 	RSiicState
	call 	RStxChar

	movlw 	'['
	call 	RStxChar
	
	SWAPF	RSiicByte,W
	call	RSwrtHexNibble	

	MOVFW	RSiicByte
	call	RSwrtHexNibble	

	movlw 	']'
	call 	RStxChar

		
	MOVLW	' '
	call 	RStxChar
	MOVLW	'c'
	call 	RStxChar
	MOVLW	'o'
	call 	RStxChar
	MOVLW	'n'
	call 	RStxChar
	MOVLW	':'
	call 	RStxChar

	SWAPF	IICtmpCon2,w
	call	RSwrtHexNibble

	MOVFW	IICtmpCon2
	call	RSwrtHexNibble

	MOVLW	' '
	call 	RStxChar
	MOVLW	's'
	call 	RStxChar
	MOVLW	't'
	call 	RStxChar
	MOVLW	'a'
	call 	RStxChar
	MOVLW	't'
	call 	RStxChar
	MOVLW	':'
	call 	RStxChar

	SWAPF	IICtmpStat2,w
	call	RSwrtHexNibble

	MOVFW	IICtmpStat2
	call	RSwrtHexNibble

	movlw	' '
	call 	RStxChar

	movlw	'e'
	btfss	IICtmpCon2,SSPOV
	movlw	'_'
	call 	RStxChar

	movlw	'~'
	btfss	IICtmpCon2,CKP
	movlw	'.'
	call 	RStxChar

	
	movlw	'D'
	btfss	IICtmpStat2,D_A
	movlw	'A'
	call 	RStxChar

	movlw	'P'
	btfss	IICtmpStat2,P
	movlw	'_'
	call 	RStxChar

	movlw	'S'
	btfss	IICtmpStat2,S
	movlw	'_'
	call 	RStxChar

	movlw	'R'
	btfss	IICtmpStat2,R_W
	movlw	'W'
	call 	RStxChar


	movlw	'_'
	btfss	IICtmpStat2,UA
	movlw	'7'
	call 	RStxChar

	movlw	'B'
	btfss	IICtmpStat2,BF
	movlw	'_'
	call 	RStxChar

	MOVLW	0x0D
	call 	RStxChar
		
	MOVLW	0x0A
	call 	RStxChar


	RETURN

;--------------------------------------------------------------------------
; Sec 9.1 	RS232 routines 
;--------------------------------------------------------------------------


; IIC interupt routine

;;----- SSPSTAT Bits -------------------------------------------------------

;SMP                          EQU     H'0007'
;CKE                          EQU     H'0006'
;D                            EQU     H'0005'
;I2C_DATA                     EQU     H'0005'
;NOT_A                        EQU     H'0005'
;NOT_ADDRESS                  EQU     H'0005'
;D_A                          EQU     H'0005'
;DATA_ADDRESS                 EQU     H'0005'
;P                            EQU     H'0004'
;I2C_STOP                     EQU     H'0004'
;S                            EQU     H'0003'
;I2C_START                    EQU     H'0003'
;R                            EQU     H'0002'
;I2C_READ                     EQU     H'0002'
;NOT_W                        EQU     H'0002'
;NOT_WRITE                    EQU     H'0002'
;R_W                          EQU     H'0002'
;READ_WRITE                   EQU     H'0002'
;UA                           EQU     H'0001'
;BF                           EQU     H'0000'


; If SSPIF is set then work out what is happening

; if S ; start seen in middle of read
;
;   if A then Address received 
;	  if BF 
;        goto IICaddrCallBack
;   if D then Address received 
;      if R then
;        goto IICdataRCallBack
;      if W then
;        goto IICdataWCallBack
;

;--------------------------------------------------------------------------
; Sec 9.2 	Serial Output Format Routines
;--------------------------------------------------------------------------

RSasciiToNibble
	MOVWF	RSin
	; if 0..1 then 0x30 to 0x39
	; if A..F then 0x41 to 0x46
	; if a..f then 0x61 to 0x66
	; test if bit 4 set and assume a letter or number
	BTFSS	RSin,4
	ADDLW	0x09		; letter so add 9 
	ANDLW	0x0F		; mask of nibble
	return


;--------------------------------------------------------------------------
; Sec 9.3 	Serial Input Buffer Routine
;--------------------------------------------------------------------------

; take serial input CAADD and put into buffer 
; if char id ; the do command
; if char is CR reset buffer pointer
; if buff end then reset buff pointer


RSipbuffStart	EQU RScmd 
RSipbuffEnd	EQU RSterminator

RSbuffInput
	MOVWF	RSin
	; look for line feed and reset buff cnt
	ADDLW	-0x0D
	BNZ		RSbuffInput1
	MOVLW	RSipbuffStart
	MOVWF	RSipBuffCnt
	RETURN

RSbuffInput1		
	; end of line command - do command
	ADDLW	-';'+0x0D
	BNZ		RSbuffInput2
	goto	RSbuffInputProcess

RSbuffInput2
	; Store the current time into the next register.
	MOVFW	RSipBuffCnt
	MOVWF	FSR
	MOVFW	RSin
	MOVWF	INDF
	INCFSZ	RSipBuffCnt,f
	MOVFW	RSipBuffCnt

	ADDLW	-(RSipbuffEnd+1)
	; Check if the end of memory
	SKPZ	
	goto	RSbuffInputEnd1
	MOVLW	RSipbuffStart
	MOVWF	RSipBuffCnt

	; reset cursor
	MOVLW	0x0D
	call 	RStxChar
	RETURN
	

RSbuffInputProcess
	MOVLW	RSipbuffStart
	MOVWF	RSipBuffCnt

	MOVFW	RSAa
	; if 0..1 then 0x30 to 0x39
	; if A..F then 0x41 to 0x46
	; if a..f then 0x61 to 0x66
	; test if bit 4 set and assume a letter or number

	BTFSS	RSAa,4
	ADDLW	0x09		; letter so add 9 
	ANDLW	0x0F		; mask of nibble
	MOVWF	RSin
	SWAPF	RSin,F
	
	MOVFW	RSaA
	BTFSS	RSaA,4
	ADDLW	0x09		; letter so add 9 
	ANDLW	0x0F		; mask of nibble
	ADDWF	RSin,w
	MOVWF	RSaddr

	MOVFW	RSDd
	BTFSS	RSDd,4
	ADDLW	0x09		; letter so add 9 
	ANDLW	0x0F		; mask of nibble
	MOVWF	RSin
	SWAPF	RSin,F
	
	MOVFW	RSdD
	BTFSS	RSdD,4
	ADDLW	0x09		; letter so add 9 
	ANDLW	0x0F		; mask of nibble
	ADDWF	RSin,w
	MOVWF	RSdata
	
	; call 	RStxChar

	; got to end of buffer so process. does not allow for backspace

	; Write to file register
	MOVLW	-'w'
	ADDWF	RScmd,w	; test to see if command is s, if so save into register.
	bnz  	RSbuffInput3		
	
	MOVFW	RSaddr
	MOVWF	FSR
	
	MOVFW	RSdata
	MOVWF	INDF

	goto	RSbuffInputEndOK
	
	
RSbuffInput3

	; put octet in EEPROM
	MOVLW	-'p'
	ADDWF	RScmd,w	; test to see if command is s, if so save into register.
	bnz  	RSbuffInput4		
	
	BANKSEL	RSaddr
	MOVFW	RSaddr
	call	EEsetAddr

	BANKSEL	RSdata
	MOVFW	RSdata
	call	EEwrt

	goto	RSbuffInputEndOK
	
	
	
		
RSbuffInput4
	; read from file register
	MOVLW	-'r'
	ADDWF	RScmd,w	; test to see if command is s, if so save into register.
	bnz  	RSbuffInput5

	MOVFW	RSaddr
	MOVWF	FSR
	
	MOVFW	INDF
	MOVWF	RSin

RSbuffInput4display
	MOVLW	'='
	call 	RStxChar
	
	SWAPF	RSin,w
	call	RSwrtHexNibble

	MOVFW	RSin
	call	RSwrtHexNibble
	
	goto	RSbuffInputEnd


RSbuffInput5
	; get from EEPROM register
	MOVLW	-'g'
	ADDWF	RScmd,w	; test to see if command is s, if so save into register.
	bnz  	RSbuffInput15

	MOVFW	RSaddr
	call	EEread
	MOVWF	RSin
	
	goto	RSbuffInput4display	
	

RSbuffInput15

	ifdef IICmaster

	; Apply IIC start
	; SCL on RB4
	; SDA on RB1
	; SCL ----\______
	; SDA --\___

	MOVLW	-'<' ;ff
	ADDWF	RScmd,w	
	bnz  	RSbuffInput16
	call	IIcStart
	; send the address always follows a start so send the first 8 bits;
	movfw	RSaddr	

	call	IIctxChar
	goto	RSbuffInputEndOK

RSbuffInput16
	; Apply IIC stop
	; SCL _/--------
	; SDA _____/----
	MOVLW	-'>' 
	ADDWF	RScmd,w	
	bnz  	RSbuffInput17
	call	IIcStop
	goto	RSbuffInputEndOK


RSbuffInput17
	; Send word
	; SCL __/--\____
	; SDA __________
	
	MOVLW	-'/' ; apply iic 0
	ADDWF	RScmd,w	
	bnz  	RSbuffInput18
	movfw	RSaddr	
	call	IIctxChar
	goto	RSbuffInputEndOK

RSbuffInput18
	; read word
	; SCL __/--\____
	; SDA __________
	
	MOVLW	-'?' ; apply iic 0
	ADDWF	RScmd,w	
	bnz  	RSbuffInput19
	call	IIcrxChar
	;call	IIcrxCharAck
	call	IIcrxAck

	MOVWF	RSin

	MOVLW	'='
	call 	RStxChar
	
	SWAPF	RSin,w
	call	RSwrtHexNibble

	MOVFW	RSin
	call	RSwrtHexNibble
	
	goto	RSbuffInputEnd
	
	goto	RSbuffInputEndOK

    endif   

RSbuffInput19
	; read word
	; SCL __/--\____
	; SDA __________
	
	MOVLW	-'~' ; apply iic 0
	ADDWF	RScmd,w	
	bnz  	RSbuffInput20
	call	IIcrxChar

	;call	IIcrxCharNAck
	call 	IIcrxNAck
	
	MOVWF	RSin

	MOVLW	'='
	call 	RStxChar
	
	SWAPF	RSin,w
	call	RSwrtHexNibble

	MOVFW	RSin
	call	RSwrtHexNibble
	
	goto	RSbuffInputEnd
	
	goto	RSbuffInputEndOK

RSbuffInput20
	; Apply IIC init
	; SCL on RB4
	; SDA on RB1
	; SCL ----\______
	; SDA --\___

	MOVLW	-'i' ; i20  - init IIC module
	ADDWF	RScmd,w	
	bnz  	RSbuffInput21

	movfw	RSaddr	
	call	IICinitAddr	
	; send the address always follows a start so send the first 8 bits;
	movfw	RSaddr	

	call	IIctxChar
	goto	RSbuffInputEndOK

RSbuffInput21
	; IIC display init and fill 

	MOVLW	-'l' ; i20  - init IIC module
	ADDWF	RScmd,w	
	bnz  	RSbuffInput22

	movfw	RSaddr	

	call	IIcStart
	; send the address always follows a start so send the first 8 bits;
	movlw	0xc6
	call	IIctxChar

	movlw	0x00
	call	IIctxChar
	movlw	0x0c
	call	IIctxChar

	movfw	RSaddr	
	movlw	.40
	movwf	RSdata
	
RSbuffInput21_loop
	movfw	RSaddr	
	call	IIctxChar
	incf	RSaddr,f
	decfsz	RSdata
	goto	RSbuffInput21_loop

	call	IIcStop
	movfw	RSaddr	
	call	IIctxChar
	goto	RSbuffInputEndOK



RSbuffInput22
	; IIC display init and fill 

	MOVLW	-'L' ; i20  - init IIC module
	ADDWF	RScmd,w	
	bnz  	RSbuffInput23

	movfw	RSaddr	

	call	IIcStart
	; send the address always follows a start so send the first 8 bits;
	movlw	0xA0
	call	IIctxChar

	movfw	RSaddr	
	call	IIctxChar
	movfw	RSdata
	call	IIctxChar

;	call	IIcStop
;	call	IIcStart
	call	IIcReStart

	; send the address always follows a start so send the first 8 bits;
	movlw	0xA1
	call	IIctxChar

	movlw	0x20
	movwf	RSdata
		
RSbuffInput22_loop
	call	IIcrxChar
	;call	IIcrxCharAck
	decfsz	RSdata
	goto	RSbuffInput22_loop2
	
	call 	IIcrxNAck
	call	IIcStop
	goto	RSbuffInputEndOK

RSbuffInput22_loop2
	call	IIcrxAck
	MOVWF	RSin

	MOVLW	','
	call 	RStxChar
	
	SWAPF	RSin,w
	call	RSwrtHexNibble

	MOVFW	RSin
	call	RSwrtHexNibble

	goto	RSbuffInput22_loop




RSbuffInput23

	MOVLW	'?'
	call 	RStxChar
	goto	RSbuffInputEnd
			
RSbuffInputEndOK

	MOVLW	'*'
	call 	RStxChar
	;
	
RSbuffInputEnd
	banksel  IICflags
	btfss   IICflags,0
	goto	RSbuffInputEnd0


	MOVLW	' '
	call 	RStxChar
	
	banksel	PIR1
	movfw	PIR1
	movwf 	IICtmp

	banksel	SSPSTAT
	movfw	SSPSTAT
	
	banksel	IICtmpStat
	movwf 	IICtmpStat

	SWAPF	IICtmp,w
	call	RSwrtHexNibble

	MOVFW	IICtmp
	call	RSwrtHexNibble


	SWAPF	IICtmpStat,w
	call	RSwrtHexNibble

	MOVFW	IICtmpStat
	call	RSwrtHexNibble

	movlw	' '
	call 	RStxChar

	movlw	'e'
	btfss	IICtmpCon,SSPOV
	movlw	'_'
	call 	RStxChar

	movlw	'~'
	btfss	IICtmpCon,CKP
	movlw	'.'
	call 	RStxChar

	
	movlw	'D'
	btfss	IICtmpStat,D_A
	movlw	'A'
	call 	RStxChar

	movlw	'P'
	btfss	IICtmpStat,P
	movlw	'_'
	call 	RStxChar

	movlw	'S'
	btfss	IICtmpStat,S
	movlw	'_'
	call 	RStxChar

	movlw	'R'
	btfss	IICtmpStat,R_W
	movlw	'W'
	call 	RStxChar


	movlw	'_'
	btfss	IICtmpStat,UA
	movlw	'7'
	call 	RStxChar

	movlw	'B'
	btfss	IICtmpStat,BF
	movlw	'_'
	call 	RStxChar
	
	btfss   IICtmpStat,BF
	goto 	RSbuffInputEnd0


	;
	; read SSPBUF ad print of char
	;
		

	banksel	SSPBUF
	movfw	SSPBUF
	movwf 	IICtmp
	SWAPF	IICtmp,w
	call	RSwrtHexNibble

	MOVFW	IICtmp
	call	RSwrtHexNibble

	
	

RSbuffInputEnd0

	MOVLW	'-'
	call 	RStxChar

	banksel  PIR1
	SWAPF	PIR1,w
	call	RSwrtHexNibble

	MOVFW	PIR1
	call	RSwrtHexNibble
	

	banksel  IICflags
	SWAPF	IICflags,w
	call	RSwrtHexNibble

	MOVFW	IICflags
	call	RSwrtHexNibble

	MOVLW	'-'
	call 	RStxChar

	banksel  SSPCON
	movfw	SSPCON
	
	banksel	IICtmp
	movwf 	IICtmp
	
	banksel  SSPSTAT
	movfw	SSPSTAT
	
	banksel	IICtmpStat
	movwf 	IICtmpStat

	
	SWAPF	IICtmp,w
	call	RSwrtHexNibble

	MOVFW	IICtmp
	call	RSwrtHexNibble

	MOVLW	' '
	call 	RStxChar
	MOVLW	's'
	call 	RStxChar
	MOVLW	't'
	call 	RStxChar
	MOVLW	'a'
	call 	RStxChar
	MOVLW	't'
	call 	RStxChar
	MOVLW	':'
	call 	RStxChar

	SWAPF	IICtmpStat2,w
	call	RSwrtHexNibble

	MOVFW	IICtmpStat2
	call	RSwrtHexNibble

	SWAPF	IICtmpStat,w
	call	RSwrtHexNibble

	MOVFW	IICtmpStat
	call	RSwrtHexNibble

	movlw	' '
	call 	RStxChar

	movlw	'e'
	btfss	IICtmpCon,SSPOV
	movlw	'_'
	call 	RStxChar

	movlw	'~'
	btfss	IICtmpCon,CKP
	movlw	'.'
	call 	RStxChar

	
	movlw	'D'
	btfss	IICtmpStat,D_A
	movlw	'A'
	call 	RStxChar

	movlw	'P'
	btfss	IICtmpStat,P
	movlw	'_'
	call 	RStxChar

	movlw	'S'
	btfss	IICtmpStat,S
	movlw	'_'
	call 	RStxChar

	movlw	'R'
	btfss	IICtmpStat,R_W
	movlw	'W'
	call 	RStxChar


	movlw	'_'
	btfss	IICtmpStat,UA
	movlw	'7'
	call 	RStxChar

	movlw	'B'
	btfss	IICtmpStat,BF
	movlw	'_'
	call 	RStxChar

	MOVLW	0x0D
	call 	RStxChar
		
	MOVLW	0x0A
	call 	RStxChar

RSbuffInputEnd1

    return


;--------------------------------------------------------------------------
; Sec 10.0 Initilization code - 
;--------------------------------------------------------------------------
INinit
	; Enable Interupts
	MOVLW	H'00'
	MOVWF	INTCON

	CLRF PORT_RS232 ;Initialize PORT_RS232 by setting
	;output data latches
	

     ifdef 	OSCCAL
	; get the Oscillator calibration

    
	;MOVLW	0x6C		; load the Calib
	BSF		STATUS,RP0
	call 	OscCalValue
	MOVWF	OSCCAL
	endif
	
	ifdef pic16F876
     ;make AtoD inputs digital
	BANKSEL ADCON1
	MOVLW 0X07 ;Turn comparators off and
	MOVWF ADCON1 ;enable pins for I/O
	endif

	ifdef pic16F819
     ;make AtoD inputs digital
	BANKSEL ADCON1
	MOVLW 0X07 ;Turn comparators off and
	MOVWF ADCON1 ;enable pins for I/O
	endif


	banksel	TRIS_RS232
	BSF		TRIS_RS232, RS232tx 	; Make PORT_RS232 3:0 INPUTS.
	BCF		TRIS_RS232,OUTPUTPIN

	banksel	RSipbuffStart
	; reset input buffer
	MOVLW	RSipbuffStart
	MOVWF	RSipBuffCnt
	
	MOVLW	0x14
	MOVWF	RSinterCharDelay

	; Change Prescaler
	CLRWDT

	; Configure Tmr 0
	BSF		STATUS,RP0
	; Set up prescaller for 8192 / 16 = 512 ticks perseconds.

	MOVLW	0x0 + 2 	; For Tmr0 0=/2, 1=/4, 2=/8,3=/16
	MOVWF	OPTION_REG
	BCF		STATUS,RP0

	CLRF	DoTimeSlice	
	CLRF	IPbuttonEvent
	CLRF	IPbuttonEventUp
	return




INsayHello	
	; print out power on message
	MOVLW	0x0D
	call 	RStxChar
		
	MOVLW	0x0A
	call 	RStxChar

	MOVLW	'i'
	call 	RStxChar
		
	MOVLW	'c'
	call 	RStxChar
		
	MOVLW	'1'
	call 	RStxChar
		
	MOVLW	0x0D
	call 	RStxChar
		
	MOVLW	0x0A
	call 	RStxChar
	
	return


;--------------------------------------------------------------------------
; Sec 11.0 	EEprom Routines for 16F628
;--------------------------------------------------------------------------

EEread		
	; w contains address
	banksel	EEADR	
	MOVWF	EEADR
	banksel 	EECON1
	ifdef EEPGD
	BCF 		EECON1, EEPGD; Point to Data memory
	endif
	BSF		EECON1,RD
	BANKSEL EEDATA ; Select Bank of EEDATA
	MOVFW	EEDATA
	banksel	0	
	RETURN

EEsetAddr
	banksel	EEADR
	MOVWF	EEADR
	RETURN
	
EEwrt	; blocking, EEADR and EEDATA set up.

	banksel 	EEDATA
	MOVWF	EEDATA
	;BCF		PIR1,EEIF
	
	banksel 	EECON1
	BCF		EECON1,WREN	; disable EROM
	ifdef EEPGD
	BCF 		EECON1, EEPGD ; Point to DATA
	endif
	BSF		EECON1,WREN
	BCF		INTCON,GIE
	MOVLW	0x55
	MOVWF	EECON2
	MOVLW	0xAA
	MOVWF	EECON2
	BSF		EECON1,WR
	BsF		INTCON,GIE
	
	; Now wait for EEwrt to finish write
EEwaitForWrt	; block until EEPROM write has finished.
	BCF		EECON1,WREN	; disable EROM

	; NOTE:- I have commented out the goto and the write to eeprom started to work
		
;		btfsc	EECON1,WR	
;		goto	EEwaitForWrt
	
	;BCF		EECON1,EEIF	; EEPROM finished

	banksel	0	
	RETURN
	
	
;--------------------------------------------------------------------------
; Sec 12.0		Interrupt Routines
;--------------------------------------------------------------------------

Intrtn		
		RETFIE

;--------------------------------------------------------------------------
; Program End
;--------------------------------------------------------------------------

LastProgWord

;--------------------------------------------------------------------------
; Sec 13.0		EEPROM data
;--------------------------------------------------------------------------
		ORG	0x2100
		; first 2 on and off are general ones
		DE	.100,.50  ; 4

		ORG	0x2110
		; first 2 on and off are general ones
		; solar,off,bright/dim,Timer 61=~41 seconds ticks 1e6/2^16m = 1/15.2587890625
		
		DE	-2,-2,-1
		DE	0x5A			 ; Vbatt
		DE	00
		DE	.61			 ; inter sample delay 0x3d = 4 seconds
		DE	0x14			 ; InterCharacter delay (bits),
		DE	0x80			 ; InterCharacter delay (bits) after MMdisplay CR,


	cblock 	
LastVar
	endc
	END

