
#include "msp430g2x31.inc"

  org 0xf800
start:
  ;; Turn off watchdog
  mov.w #0x5a80, &WDTCTL

  ;; Please don't interrupt me
  dint

  ;; Set up stack pointer
  mov.w #0x0280, SP

  ;; Set up crystal
  mov.b #(64|32), &DCOCTL
  mov.b #0xf, &BCSCTL1
  mov.b #0, &BCSCTL2

  ;; Set up output pins
  ;mov.b #0x77, &P1DIR        ; P1.0, P1.1, P1.4, P1.5, P1.6
  mov.b #0x05, &P1DIR        ; P1.2 P1.0
  ;mov.b #(64|32), &P1SEL
  mov.b #0x05, &P1OUT        ; P1.4=/CS

  ;; Set up SPI
  mov.b #(USIPE7|USIPE6|USIPE5|USIMST|USIOE|USISWRST), &USICTL0
  mov.b #0x00, &USICTL1
  mov.b #USIDIV_4+USISSEL_2, &USICKCTL ; div 1, SMCLK
  bic.b #USISWRST, &USICTL0            ; clear reset

  ;; Just a test of SPI
  bic.b #0x04, &P1OUT      ; /CS = 0 (enable)

  ;mov.b #0x3f, &USISRH
  mov.b #0x3f, &USISRL
  ;mov.b #USI16B|16, &USICNT    ; Flush out 16 bits
  mov.b #8, &USICNT             ; Flush out 8 bits

wait_spi:
  bit.b #USIIFG, &USICTL1
  jne wait_spi

  mov.b #0xff, &USISRL
  mov.b #8, &USICNT             ; Flush out 8 bits

wait_spi_low:
  bit.b #USIIFG, &USICTL1
  jne wait_spi_low


  bis.b #0x04, &P1OUT      ; /CS = 1 (disable)

  ;mov.w #0xffff, r12
blah:
  ;dec.w r12
  ;jne blah
  ;bis.b #0x10, &P1OUT

  ;; Set up A/D
  ;mov.w #0x2270, &ADC10CTL0
  ;mov.w #0x0010, &ADC10CTL1
  ;mov.w #0x0010, &ADC10AE

  ;; Set up Timer
  mov.w #36364, &TACCR0
  ;mov.w #(512|16|2), &TACTL   ; TASSELx=SMCLK, IDx=DIV1, MCx=UP, TAIE=1
  mov.w #(512|16), &TACTL   ; TASSELx=SMCLK, IDx=DIV1, MCx=UP, TAIE=1
  mov.w #16, &TACCTL0

  ;; Okay, I can be interrupted now
  eint

  ;jmp blink_test

main:
  ;jmp main

blink_test:
  mov.w #0x01, r8
repeat:
  ;mov.b r8, &P1OUT
  xor.b #0x41, r8
  mov.w #65535, r9
waiter:
  dec r9
  jnz waiter
  jmp repeat

timer_interrupt:
  ;inc r9
  ;cmp #8000, r9
  ;jge turn_off
  ;bis.b #0x01, &P1OUT
  ;reti
turn_off:
  ;bic.b #0x01, &P1OUT
  xor.b #0x10, r8
  ;mov.b r8, &P1OUT
  reti

spi_interrupt:
  reti

  org 0xffe8
vectors:
  dw spi_interrupt
  dw 0
  dw 0
  dw 0
  dw 0
  dw timer_interrupt       ; Timer_A2 TACCR0, CCIFG
  dw 0
  dw 0
  dw 0
  dw 0
  dw 0
  dw start                 ; Reset


