; Counter/timer test program for Atmel AVR microcontrollers
; Ingeneering Inc.
; www.ingeninc.com
; Jeff Holtzman
; 3/1/98, 6/1/98
;Description
;Demonstrates use of sleep mode, interrupts, and precise
;hardware generated time delay.  From 11/98 issue of
;Popular Electronics magazine.
;AUTHOR = Jeff Holtzman
;TARGET = AT90S1200
;REQUIRES = 1200def.inc

	.device		AT90S1200	

	.include	"1200def.inc"
	
	.def	Acc 	= R16		; general purpose accumulator
	.def	DispCnt	= R17		; display counter
	.def	TickCntLo = R18	; tick counter
	.def	TickCntHi = R19	; tick counter

	.equ	CLK_DIV = 4		; divide timer clock by 256
	.equ	CNT_LO	= 61		; provides 1 sec delay @ clk/256
	.equ	CNT_HI	= 0
	
	.cseg				; code begins here

	.org	0

Reset:		rjmp	V_Reset		; set up interrupt vectors
IRQ:		rjmp	V_IRQ
Timer:		rjmp	V_Timer
Comparator:	rjmp	V_Comp
V_IRQ:		reti			; dummy
V_Comp:		reti			; dummy

V_Reset:	
	ldi	DispCnt, 0		; reset display counter
	ldi	TickCntLo, CNT_LO	; reset tick counter
	ldi	TickCntHi, CNT_HI
	ldi	Acc, 255		; set PORT B for output
	out	DDRB, Acc
	out	PortB, Acc
	ldi	Acc, 0			; set PORT D for input
	out	DDRD, Acc
	ldi	Acc, 0b00100000	; set bit 5 to enable sleep mode
	out	MCUCR, Acc
	ldi	Acc, CLK_DIV		; set up interrupt clock
	out	TCCR0, Acc
	ldi	Acc, 2			; enable timer interrupt
	out	TIMSK, Acc
	ldi	Acc, $80		; enable global interrupts
	out	SREG, Acc
Rst_Loop:	
	sleep				; reset comes here
	in	Acc, PinD		; input Port D
	andi	Acc, $7f
	cpi	Acc, 0b01111010	; if S0+S2 pressed,
	brne	Rst_Loop		; reset display and tick counters
	ldi	TickCntLo, CNT_LO
	ldi	TickCntHi, CNT_HI
	ori	Acc, $80
	out	PortB, Acc
	ldi	DispCnt, 0
	rjmp	Rst_Loop
V_Timer:				; timer interrupt comes here
	subi	TickCntLo, 1		; decrement tick counter
	sbci	TickCntHi, 0
	brne	Exit
	cpi	TickCntLo, 0
	brne	Exit			; exit if not = 0
	inc	DispCnt			; else increment display counter,
	mov	Acc, DispCnt
	com	Acc
	out	PortB, Acc		; display it,
	ldi	TickCntLo, CNT_LO	; and reset tick counter
	ldi	TickCntHi, CNT_HI
Exit:		
	reti
