' ------------------------------------------------------------------------------------------
' dsPICDEM 1.1 Developement Board
' Driver routines
'
' Created 11/2004 by Eric James
' ------------------------------------------------------------------------------------------
'
'
'
' Routines
' ========
'
' LCD_Init()		Initialize everything to use the LCD (SPI port), and
'			LDC
'
' LCD_puts(strming)	Write a string to the LCD at the cursor position
'
' lcd_putc(character)	Write a character to the LCD
'				
' lcd_pos(column,row)	Move the cursor to s given column and row
'
' lcd_write(value)	Write a value to the LCD controller
'


' Initialize LCD communications
' Notes:
'	Depending on the clock rate, the SPI2 clock rate might need changed
'
Sub lcd_Init()
	LATG9=1			' setup SPI slave select pin
	TRISG9=0
	SPI2CON=0x3A		' Master, CLK=Fosc/8, Sample at middle, Data on rising edge, Clk idle is low	
	SPI2IE=0		' make sure the interrupt is disabled
	SPI2STAT=0x8000		' enable the SPI Port
	
	lcd_write(0x82)		' clear the screen
	lcd_write(0x82)
End Sub

Sub lcd_HomeClear()
	lcd_write(0x82)
End Sub

Sub lcd_Home()
	lcd_write(0x81)
End Sub

' Write a string to the LCD
Sub LCD_puts(s() As String)
	Dim i,c As Integer
	
	i=0: c=s(0)
	While c<>0
		lcd_write(0xA8): lcd_write(c)
		i+=1: c=s(i)
	End While
	
End Sub

Sub LCD_putc(x As uInteger)
	lcd_write(0xA8)
	lcd_write(x)
End Sub


Sub LCD_POS(c As uInteger, r As uInteger)
	lcd_write(0xc5)
	lcd_write(c)
	lcd_write(r)
End Sub


Sub lcd_write(x As uInteger)
	Dim y As uInteger
	
	latg9=0				' set slave select low for new transmission
	SPI2_ROV=0
	
	y=SPI2BUF			' Dummy read to avoid overflow
	SPI2BUF=x			' write the data to the output buffer
	
	While SPI2_RBF=0		' loop till complete
	End While
	
	LATG9=1				' SPI slave select pin high	
End Sub