' <summary> <pre>
'
' Button Debouncing example
'
' Simply count button presses and display the total on an LCD
'
' This program works with the ICD2 Demo board
'
' PORTB pin 0 is pulled high with a 10K resistor and switched
'             low with the button
'
' LCD data bits 4, 5, 6, 7 connected to PORTD bits 4, 5, 6, 7
' LCD E  on PORTA bit 1
' LCD RW on PORTA bit 2
' LCD RS on PORTA bit 3
'
' </pre> </summary>

' ---------------------------------------------------------------
' LCD Variables required by <libs\interface\4BitLCD.bas>

Dim LCD_D4 @ PORTD.0 As Boolean, LCD_D4_DIR @ TRISD.0 As Boolean
Dim LCD_D5 @ PORTD.1 As Boolean, LCD_D5_DIR @ TRISD.1 As Boolean
Dim LCD_D6 @ PORTD.2 As Boolean, LCD_D6_DIR @ TRISD.2 As Boolean
Dim LCD_D7 @ PORTD.3 As Boolean, LCD_D7_DIR @ TRISD.3 As Boolean
Dim LCD_E  @ PORTA.1 As Boolean, LCD_E_DIR  @ TRISA.1 As Boolean
Dim LCD_RW @ PORTA.2 As Boolean, LCD_RW_DIR @ TRISA.2 As Boolean
Dim LCD_RS @ PORTA.3 As Boolean, LCD_RS_DIR @ TRISA.3 As Boolean

Include <libs\interface\4BitLCD.bas>	' load the LCD library
Include <libs\interface\debounce.bas>	' load the button debouncing library

Dim btnCounts As uInteger		' the button counter

Sub main()
	Call init()	' initialize both hardware and software
	
	While 1
		Call updateDisplay()			' refresh the LCD display
		Call WaitForButton(Addr(PORTB),0,0) 	' wait for a button press
		Call WaitForButton(Addr(PORTB),0,1)	' wait for button release
		btnCounts=btnCounts+1			' count this press
	End While	

End Sub

Sub updateDisplay()
	' <summary>
	'	Update the LCD display
	' </summary>
	
	Dim s(10) As String	' <var name="s"> Temporary string </var>
	
	Call LCDcls()
	Call LCDputs("Presses: ")
	Call str(btnCounts,s): Call LCDputs(s)
	
End Sub


Sub init()
	' <summary> Initialize hardware and software </summary>
	'

	' <summary>
	'ADC Configuration
	'=================
	' Processor: 18F452
	' Fosc: Fosc/32
	' Channel: 0
	' ADC: ON
	' Justify: Right
	' Analog Channels: AN0
	' Digital Channels: AN1,AN2,AN3,AN4,AN5,AN6,AN7
	' Verf+: Vdd
	' Vref-: Vss
	' </summary>
	
	ADCON0=0x81
	ADCON1=0x8E
	  
	Call LCDinit()		' initialize the LCD
	
	btnCounts=0		' initialize the button press counter
	  
End Sub