;; ---------------------------------------------------------
;;
;; Stellaris LM3S1000 ---  LM3S6965
;;
;; ---------------------------------------------------------

(library
 (system 0)
 (export sysc gioa giob gioc giod gioe giof giog gioh
	 uar0 uar1 tmr0 tmr1 ssi0 ssi1 i2c0 i2c1 adc0 pwm0
	 register-copy-bit config-power config-pin
	 pin-set pin-clear pin-set? stop restart spi-put spi-get)
 (import)

 (define sysc #x400fe00)
 (define gioa #x4000400)
 (define giob #x4000500)
 (define gioc #x4000600)
 (define giod #x4000700)
 (define gioe #x4002400)
 (define giof #x4002500)
 (define giog #x4002600)
 (define gioh #x4002700)
 (define uar0 #x4000C00)
 (define uar1 #x4000D00)
 (define ssi0 #x4000800)
 (define ssi1 #x4000900)
 (define i2c0 #x4002000)
 (define i2c1 #x4002100)
 (define tmr0 #x4003000)
 (define tmr1 #x4003100)
 (define tmr2 #x4003200)
 (define tmr3 #x4003300)
 (define adc0 #x4003800)
 (define pwm0 #x4002800)

 (define (register-copy-bit reg ofst bpos bval)
   (write (bitwise-copy-bit (read reg (- ofst)) bpos bval) reg (- ofst)))

 (define (config-power rcgc bit val)
   (register-copy-bit sysc (+ #x100 (bitwise-arithmetic-shift rcgc 2)) bit val))

 (define (config-pin port pin den odr pur pdr dir dr2r dr8r afun)
   (register-copy-bit port #x51c pin den)   ; GPIODEN 
   (register-copy-bit port #x50c pin odr)   ; GPIOODR
   (register-copy-bit port #x510 pin pur)   ; GPIOPUR
   (register-copy-bit port #x514 pin pdr)   ; GPIOPDR
   (register-copy-bit port #x400 pin dir)   ; GPIODIR
   (if (not (zero? dr2r)) (register-copy-bit port #x500 pin dr2r))  ; GPIODR2R
   (if (not (zero? dr8r)) (register-copy-bit port #x508 pin dr8r))  ; GPIODR8R
   (register-copy-bit port #x420 pin afun)) ; GPIOASEL

 (define (pin-set port pin)
   (write #xff port (bitwise-arithmetic-shift 1 (+ pin 2))))

 (define (pin-clear port pin)
   (write #x00 port (bitwise-arithmetic-shift 1 (+ pin 2))))

 (define (pin-set? port pin)
   (bitwise-bit-set? (read port #x03fc) pin))

 (define (stop tmr) (write #x00 tmr #x0c))

 (define (restart tmr) (write #x01 tmr #x0c))

 (define (spi-put port val)
   (let loop ((stat 0))
     (if (bitwise-bit-set? stat 1)
	 (write val port #x08)
	 (loop (read port #x0c)))))

 (define (spi-get port)
   (let loop ((stat 0))
     (if (bitwise-bit-set? stat 2)
	 (read port #x08)
	 (loop (read port #x0c)))))

 ) ; end of library