// Copyright (c) 2004 Rowley Associates Limited.
//
// This file may be distributed under the terms of the License Agreement
// provided with this software.
//
// THIS FILE IS PROVIDED AS IS WITH NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

#include <msp430.h>
// This defines the timeout period for a millisecond timer
#define MS_TIMEOUT 500           

	.text
	.code
	.align 0

        .public _BoardInit
        .public _SetTimerISR
        .public _TicksPerSecond
        .public _SetButtonPressedISR
        .public _SetLeds
        .public _Idle

        .extern _ctl_interrupt_count
        .extern _ctl_exit_isr

_BoardInit:
        BIS.B   #1, &P1DIR
        ret

_SetTimerISR:
        mov.w r15, &timer_isr
        mov.w   #TASSEL1+TACLR,&TACTL   ; SMCLK, clear TAR
        mov.w   #CCIE,&CCTL0            ; CCR0 interrupt enabled
        mov.w   #MS_TIMEOUT,&CCR0       ; 
        bis.w   #MC1,&TACTL             ; Start Timer_a in continous mode
        ret

_TicksPerSecond:
        mov #0, r15
        mov #1000, r14
        ret


TA0_ISR:
        push.w r4
        push.w r5
        push.w r6
        push.w r7
        push.w r8
        push.w r9
        push.w r10
        push.w r11
        push.w r12
        push.w r13
        push.w r14
        push.w r15        
        add.w #1, &_ctl_interrupt_count           
        
        call timer_isr
        add.w #MS_TIMEOUT,&CCR0

        mov.w sp, r15        
        jmp _ctl_exit_isr

_SetButtonPressedISR:
        mov.w r15, &button_pressed_isr
        bis.b   #0FFh,&P2IE   ; P2 Interrupt enabled
        bis.b   #0FFh,&P2IES  ; P2 hi/low edge
        bic.b   #0FFh,&P2IFG  ; P2 IFG Cleared
        ret

P2_ISR:
        push.w r4
        push.w r5
        push.w r6
        push.w r7
        push.w r8
        push.w r9
        push.w r10
        push.w r11
        push.w r12
        push.w r13
        push.w r14
        push.w r15 
        bic.b   #0FFh,&P2IFG  ; P2 IFG Cleared
        add.w #1, &_ctl_interrupt_count           
        call button_pressed_isr
        mov.w sp, r15        
        jmp _ctl_exit_isr

_SetLeds:
        cmp #0, r15
        jz ledoff
        BIS.B   #1, &P1OUT
        ret
ledoff:
        BIC.B   #1, &P1OUT
        ret

_Idle:
        ret

        .data
timer_isr:
        dw 0
button_pressed_isr:
        dw 0
                                  
        .vectors
        .keep

        org 0x2
        dw P2_ISR

        org 0xC
        dw TA0_ISR                                                                 
                                          
