; PROGRAM GENERATES TIME BASE OF 1 SECOND WITH INTERRUPTS
; OF TIMER 0. FLASHES LED 7 EACH SECOND.
; USES TMR0 WITH 8 BITS AND PRESCALLER (256) TO GENERATE
; 5.46 MILISECONDS POR EACH INTERRUPT CYCLE.
; 183 CYCLES IS APROXIMATELY 1 SECOND.
; AS A SECOND TASK, PROGRAM PERFORMS ALSO A BINARY COUNT 
; IN MAIN PROGRAM WITH LEDS 0...3


	processor 18F2550
	include	  <p18F2550.inc>
	include	 "KEYBOLT.inc"	;Auxiliary file with macro

CONT1	EQU	H'60'			;COUNTER OF CYCLES, 65.5 MILISECONDS. 
J		EQU	H'61'
K		EQU	H'62'
L		EQU	H'63'
SALVAW	EQU H'64'			;guarda registro w
SALVAST	EQU H'65'			;guarda bandera Z

;program starts here
		org 	0X800
		goto 	begin			;jump to main program	
			
		org 	0x808			;interrupt subroutine in address 0x808				
		clrf	TMR0L			;inicializa TMR0
		movwf	SALVAW
		swapf	STATUS,w
		movwf	SALVAST
		bcf	INTCON,TMR0IF		;apaga bandera de overflow del TMR0
		incf	CONT1,f			;incrementa contador de 65.5 ms.
		movlw	D'183'
		subwf	CONT1,w			;prueba si la cuenta es igual a 183
		btfss	STATUS,Z		;bandera Z encendida?
		goto	salida			;count is not 183, return
		BTFSS	LED7			;is led on?
		GOTO	ENC		
		BCF		LED7			;LED OFF
		CLRF	CONT1	
		goto	salida	
ENC		BSF		LED7			;LED ON
		CLRF	CONT1
salida		swapf	SALVAST,w
		movwf	STATUS
		swapf	SALVAW,f
		swapf	SALVAW,w		
		retfie

;main program
begin		PUERTOS				;macro to inicialize ports.
		clrf	CONT1			;			
		movlw	B'11000111'		;HABILITA TEMPORIZADOR A 8 BITS Y CLOCK INTERNO					
		movwf	T0CON			;prescaler divides /256
		movlw	D'00'
		movwf	TMR0L			;inicialize timer=0	
		bsf		INTCON,GIE		;enable global interrupt
		bsf		INTCON,TMR0IE	;enable TMR0 interrupt.

;TAREA 2 CUENTA EN BINARIO EN RB0...RB3
	
increment:	incf	PORTB,F	
			call	retrobolt
			MOVF	PORTB,W
			ANDLW	H'7F'
			SUBLW	H'0F'
			BTFSS	STATUS,Z
			GOTO	NOCERO
SICERO:		MOVF	PORTB,W
			ANDLW	H'80'		;NO CAMBIES EL VALOR DEL BIT 7
			MOVWF	PORTB					
NOCERO		goto	increment


;delay subroutine. modify to (16.4 x L) miliseconds

retrobolt:	movlw	D'10'	;valor de L. Modifique para cambiar el valor del retraso.
			movwf	L
lloop		movlw	D'255'	; w := 200 decimal
			movwf	J		; J := w
jloop:		movwf	K		; K := w
kloop:		decfsz	K,f		; K = K-1, skip next if zero
			goto 	kloop
			decfsz	J,f		; J = J-1, skip next if zero
			goto	jloop
			decfsz	L,f
			goto	lloop
			return

			end