	title  "Test of Sleepmode, by PEK"

;
; Test of Sleepmode for PIC16F876
;


	list P=16F876, R=DEC

	include "P16F876.inc"

	__config _CP_OFF & _WDT_OFF & _XT_OSC


;
; Registers
;
;unbanked	udata_shr
;_w		res 1
_w		equ 0x21

;bank0	udata
;counter	res 1
counter	equ 0x20
;_status	res 1
;_pclath	res 1
;_fsr	res 1
_status	equ 0x22
_pclath	equ 0x23
_fsr	equ 0x24


;	code

; **************************************
; Start of Program
; **************************************
	org		0
	pagesel	Main
	goto		Main

	org		4
	pagesel	Interrupt_Routine
	goto		Interrupt_Routine


; **************************************
; ISR
; **************************************
Interrupt_Routine
	movwf		_w			; save W
	movf		STATUS,w
	clrf		STATUS		; force to page 0
	movwf		_status		; save STATUS
	movf		PCLATH,w
	movwf		_pclath		; save PCLATH
	movf		FSR,w
	movwf		_fsr			; save FSR

	btfsc		INTCON,INTF		; External Interrupt ?
;	clrf		counter		; Clear counter on interrupt

	bcf		INTCON,INTF		; Clear flag

; End ISR
	clrf		STATUS		; select bank 0
	movf		_fsr,w		; restore the FSR
	movwf		FSR
	movf		_pclath,w		; restore PCLATH
	movwf		PCLATH
	movf		_status,w		; restore STATUS
	movwf		STATUS
	swapf		_w,f			; restore W without corrupting STATUS
	swapf		_w,w
	retfie


; **************************************
; Main
; **************************************
Main

; Init Ports
	banksel	TRISB
	movlw		0x01
	movwf		TRISB			; Input on RB0 

; Init External Interrupt
	banksel	OPTION_REG
	bsf		OPTION_REG,NOT_RBPU	; Disable pull-ups on PortB
	bsf		OPTION_REG,INTEDG	; Interrupt on rising edge of RB0

	bsf		INTCON,INTE		; Enable external interrupt
	bsf		INTCON,GIE		; Global interrupt enabled

; Init Registers
	banksel	counter
	clrf		counter


Loop
	banksel	counter
	incf		counter,f
	
	rlf		counter,w
	andlw		0x02
	banksel	PORTB
	movwf		PORTB

	sleep
	nop

	pagesel	Loop
	goto		Loop


	end

