
\ ------------------------------------------------------------------------------
\  A small example on how to use the included assembler
\ ------------------------------------------------------------------------------

\ Register usage in Mecrisp Forth on MSP430:

\ r0    PC
\ r1    SP
\ r2    SR
\ r3    CG
\
\ r4    Pointer for data stack
\ r5    Index for loops
\ r6    Limit for loops
\ r7    Scratch register which is only saved on interrupt entry.
\ r8    Free, unused in Forth
\ r9    Free, unused in Forth
\
\ r10   Registers that need to be saved before use
\ r11    ''
\ r11    ''
\ r13    ''
\ r14    ''
\ r15    ''

\ ------------------------------------------------------------------------------

$28 constant P2IN   \   [7:0] Eight LEDs on the ULX3S board
$29 constant P2OUT  \    ...
$2A constant P2DIR  \    ... 1: Output 0: Input

: fancyblinky ( -- )

  1 P2DIR c!

  \ Register usage in this example:
  \
  \  r7 : Scratch
  \  r8 : Minsky sine
  \  r9 : Minsky cosine
  \ r10 : Exponential brightness
  \ r11 : Sigma delta modulator phase

  push.w r10
  push.w r11

  \ Start values for Minsky circle algorithm

  mov.w  #0 r8
  mov.w #70 r9

  begin \ Yes, you can mix Forth and Assembler!

    \ Minsky circle algorithm

    mov.w r9 r7  \ x' = x + y  >>> 4
    rra.w r7
    rra.w r7
    rra.w r7
    rra.w r7
    add.w r7 r8

    mov.w r8 r7  \ y' = y - x' >>> 4
    rra.w r7
    rra.w r7
    rra.w r7
    rra.w r7
    sub.w r7 r9

    \ Adjust circle coordinates to bitexp input values

    mov.w r9 r7    \ Select sine/cosine here
    add.w #$78 r7

    \ Modified bitexp function

    mov.w r7 r10
    and.w #$0F r10
    bis.w #$10 r10

    rra.w r7
    rra.w r7
    rra.w r7
    rra.w r7

\   jz + \ No check necessary, as minimum input value always requires a shift
l-: add.w r10 r10
    sub.w #1 r7
    jnz -
\ l+:

    \ Display current brightness step for a while

    30000 0 do \ Adjust blink speed here, more = slower
      add.w r10 r11   \ Sigma-Delta-Modulation
      rrc.b &P2OUT    \ Shift carry into position
    loop

  key? until

  pop.w r11
  pop.w r10

  0 P2OUT c!
;

\ Curious? Disassemble it with "see fancyblinky"
