; E-DIE: PIC12F683-based electronic die
; ---------------------------------------------
; Schematic:	http://www.eeng.biz/files/edie.png	
; Part list: 	http://www.eeng.biz/files/edie.txt
; Picture:	http://www.eeng.biz/files/edie.jpg
; Video:	http://www.eeng.biz/files/edie.mpg


		list p=12F683
		include "p12F683.inc"

		__CONFIG _INTOSCIO & _MCLRE_OFF & _FCMEN_OFF & _IESO_OFF & _WDT_OFF & _CP_OFF & _CPD_OFF & _PWRTE_ON & _BOD_OFF


		cblock 0x20
			v1
			v2
			d1
			d2
		endc


		org 	0x000

	 	
Start	
		movlw	0x3F			
		movwf	GPIO					

		movlw	0x07
		movwf	CMCON0			;turn comparators off
	
		bsf	STATUS, RP0		;bank 1
		clrf	ANSEL
		movlw	b'011000'		;GPIO0,1,2,5 as outputs
		movwf	TRISIO			;GPIO4 as input
		movlw	b'00010000'		;pull-up resistor on GPIO4
		movwf	WPU
		movlw	b'00001000'		;pull-up resistor enabled 
		movwf	OPTION_REG
		movlw	0xFB			;251 		
		movwf	PR2
		movwf   b'01110001'	 	;8 MHz
		movwf	OSCCON		
Osctest	
		btfss	OSCCON,HTS		;oscillator stable?
		goto	Osctest			
		
		bcf 	STATUS,	RP0		;bank 0
		movlw	b'00000100'		;TMR2 enabled 
		movwf	T2CON
			

Main	
		btfss	GPIO, 4			;switch pressed?
		call	B0
		movlw	0x3F
		movwf	GPIO			;LEDs off
		goto 	Main

B0		
		movf	TMR2, w			;read TMR2
		movwf	v1				
		movwf	v2
		call 	Delay20m		;simple debounce
		btfsc	GPIO, 4	 		;still pressed?
		return
	
B1		
		movlw	0x06				
		subwf	v1, w			;v1-6 -> W
		btfss 	STATUS,	C		;if C=0 goto B2	
		goto	B2
		movwf   v1
		movwf   v2
		goto 	B1

B2		
		;1<= v2 <=6
		movf	v2, w
		call	Table
		movwf	GPIO			;turn LEDs on 
		
B3		
		btfsc	GPIO, 4			;still pressed?
		return
		goto 	B3


Table	
		ADDWF   PCL, f			
		retlw	0x07
	        retlw   0x23
        	retlw   0x03
        	retlw   0x21
        	retlw   0x01
        	retlw   0x20
        

Delay20m						;about 20 ms			
		movlw	0x3E
		movwf	d1
		movlw	0x20
		movwf	d2
Delay20_1
		decfsz	d1, f
		goto	$+2
		decfsz	d2, f
		goto	Delay20_1
	
		return



		end
		
	
