
$20A constant P1SEL0
$20C constant P1SEL1

$120 constant PMMCTL0
$124 constant PMMCTL2

$C80 constant SAC0OA
$C82 constant SAC0PGA
$C84 constant SAC0DAC
$C86 constant SAC0DAT
$C88 constant SAC0DACSTS
 

: enable-dac0 ( -- )

  \ Enable internal 2.5V reference

  $A5 PMMCTL0 1+ c!            \ PMMCTL0+1 Password
    %10 4 lshift 1 or PMMCTL2 ! \ 2.5V reference, INTREFEN    
    0 PMMCTL0 1+ c!              \ Lock again

  \ Wait for reference to settle

  begin 1 12 lshift PMMCTL2 bit@ until

  \ Set P1.1 as analog pin

  2 P1SEL0 c!  2 P1SEL1 c!

  \ Configure DAC

  1 12 lshift SAC0DAC !     \ Select 2.5V int Vref as DAC reference
  0 SAC0DAT !                \ Initial DAC data
  1 SAC0DAC bis!              \ Enable DAC


  \ Configure output buffer

  1 3 lshift 1 7 lshift or \ PMUXEN, NMUXEN  Enable negative and positive input
  %01 or                    \ PSEL: 12 bit reference DAC source select
  %01 4 lshift or            \ NSEL: PGA source select
  SAC0OA !

  %01 SAC0PGA !                         \ Set OA as buffer mode
  1 10 lshift 1 8 lshift or SAC0OA bis! \ Enable SAC and OA  
;

: dac0 ( u -- ) SAC0DAT ! inline ;



\ 8 cycles per loop run for 1 us @ 8 MHz.
: us 0 ?do [ $3C00 , $3C00 , ] loop ;
: ms 0 ?do 998 us loop ;

: breathe ( -- )
  enable-dac0
  begin
  4096 0 do      i   dac0 500 us loop
  4096 0 do 4096 i - dac0 500 us loop
  key? until
;

