
\ ------------------------------------------------------------------------------
\   Light intensity measurement with a LED on digital IO pins
\ ------------------------------------------------------------------------------

\ Try to measure brightness levels by reverse-charging the junction capacitance
\ of a LED connected both with anode and cathode to GPIO pins, and waiting
\ for the discharge of this small capacitance due to photocurrent.
\ You need to connect your own LED to the board to try this.

$01A0 constant PAIN     \ First row of GPIO pins, 0+ to 13+
$01A1 constant PAOUT    \ ...
$01A2 constant PADIR    \ ... 1: Output 0: Input

1 constant Anode        \ Connect LED with anode to GPIO 0+
2 constant Cathode      \           with cathode to GPIO 1+

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

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

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

: darkness ( -- )

  begin

    Anode Cathode or PADIR ! \ Set anode and cathode as output
          Cathode    PAOUT ! \ Anode low, cathode high
    10 us                    \ Wait a little bit to charge the junction capacitance to rail voltage
    Anode            PADIR ! \ Set cathode as input

    \ How long does it stay high? The time for this changes with photocurrent.
    0
    $3FFF 0 do \ Maximum time
      PAIN @ Cathode 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
;

darkness
