
\ ------------------------------------------------------------------------------
\  Why is there an input register on the LEDs? For light input, of course :-)
\ ------------------------------------------------------------------------------

\ Try to measure brightness levels using the anode of the blue LED on the board.
\ This depends on the capacitance and forward voltage of the particular LED
\ and works in limited brightness ranges only... Dynamic range gets much better
\ if we can control both pins of the LED. See darkness.txt example.

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

8 constant blue \ Blue LED anode

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

3 constant avgshift \ Moving exponential average
: expavg ( avg x -- avg' ) swap dup avgshift rshift - + ;
0 variable average

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

: brightness ( -- )

  begin

    blue P2OUT c! \ Set LED anode high
    blue P2DIR c!
    10 us
    0 P2DIR c! \ Set LED anode pin as input

    \ How long does it stay high? The time for this changes with photocurrent.
    0
    $3FFF 0 do \ Maximum time
      P2IN c@ blue and if 1+ then
    loop

    \ Its noisy - apply a lowpass filter:
    4 rshift \ To prevent overflow for longer averaging
    average @ swap expavg dup average ! avgshift rshift

    hex. cr

  key? until
;

brightness
