;-----------------------------------------------------------------
; Name:		External Interrupt Test and DC Motor.asm
; Tests external interrup functionality coupled with the 
;	TI SN754410 Quad H-Bridge to control a DC motor
; When SW00 is pressed, the motor will spin CW
; When SW01 is pressed, the motor will spin CCW
;-----------------------------------------------------------------

.include "m128def.inc"

; Interrupt service vectors

.org $0000
	rjmp Reset						; Reset vector
.org INT4addr
	rjmp IntV4						; INT0 vector (ext. interrupt from pin D0)	
.org INT5addr	
	rjmp IntV5						; INT1 vector (ext. interrupt from pin D1)

	
;-----------------------------------------------------------------
; Register defines for main loop
;-----------------------------------------------------------------


.def		mpr=r16					; defines multipurpose register
.def		mpr2=r17				; multipurpose register 2
.def		mpr3=r18				; multipurpose register 3


;-----------------------------------------------------------------
; Reset vector
;-----------------------------------------------------------------

Reset:
;-----Setting Stackpointer----------------------------------------
	ldi		MPR,low(RAMEND)			; Set stackptr to ram end
	out		SPL,MPR
	ldi 	MPR, high(RAMEND)
	out 	SPH, MPR

;-----Set Port Directions-----------------------------------------
	ser		mpr						; Set TEMP to $FF to...
	out		DDRB,mpr				; ...set data direction to "out"
	out		PORTB,mpr				; ...all lights off!
	out		DDRD,mpr				; Set Port D as Output
									; PD0 = 2A
									; PD1 = 1A
									; PD2 = 1,2EN

	clr 	mpr						; clear all bits
	out 	DDRE,mpr				; Set 'E' as input

;-----Enabling Interrupts-----------------------------------------

;Clear INT4 and INT5 in EIMSK register
	ldi		mpr,(0<<INT4)+(0<<INT5) ; Disable int 4 and 5 to set level control
	out		EIMSK,mpr
;Set level sense control
	ldi 	mpr,(1<<ISC40)+(1<<ISC41)+(1<<ISC50)+(1<<ISC51)				
									; Set both ISC4 and ISC5 bits high
	out		EICRB,mpr
;Clear any interrupts pending in EIFR
	ldi     mpr, (1<<INTF4)+(1<<INTF5) ;Set interrupt flag in EIFR
	out		EIFR,mpr
;Set INT0 and INT1 in EIMSK register
	ldi		mpr,(1<<INT4)+(1<<INT5) ; int masks 4 and 5 set
	out		EIMSK,mpr

;Clear MPR2 for use as counter
	clr		mpr2

;Enable global interrupts

	sei

mainloop:

	rjmp mainloop					;loop here forever.

;-----------------------------------------------------------------
;
; Int4 vector - decrease count

IntV4:
	clr		mpr3
	ldi		mpr3,0b00000101			;spin CW
	out		portd,mpr3
	dec		mpr2
	reti


;-----------------------------------------------------------------
;
; Int5 vector - increase count

IntV5:
	clr		mpr3					
	ldi		mpr3,0b00000110			;spin CCW
	out		portd,mpr3				
Int01:
	reti





