aboutsummaryrefslogtreecommitdiff
path: root/amforth-6.5/appl/arduino/blocks/wiring_analog.frt
blob: e3faa9a2bffde88747955ce8091b94a370118625 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
\ analog read functions for arduino.
\ 
\ usage
\  once (in turnkey): adc.init (sets up the subsystem)
\  repeated: analog.X analog_read ( -- n)
\  

\ \\\\\\\\\\\\\\\\\\\\\\\\\\\
\      HELPER ROUTINES      \
\ \\\\\\\\\\\\\\\\\\\\\\\\\\\
\ pin>channel
\     convert bitmask of portpin: back to value (bitposition)
: pin>channel   ( pinmask portaddr -- pos )
  drop          ( -- pinmask )
  log2          ( -- pos_of_most_significant_bit )
;

: adc.init ( -- )
  \ ADMUX
  \ A_ref is NOT connected externally
  \ ==> need to set bit REFS0 in register ADMUX
  [ 0 5 lshift      \ ADLAR off, makes read operation simpler
    1 6 lshift or   \ REFS0
  ] literal ADMUX c!
  \ ADCSRA
  [ 1 7 lshift      \ ADEN   ADC enabled
    1 2 lshift or   \ ADPS2  prescaler = 128
    1 1 lshift or   \ ADPS1  .
    1          or   \ ADPS0  .
  ] literal ADCSRA c!
;
: adc.init.pin ( bitmask portaddr -- )
  over over high
  pin_input
;
  
1 6 lshift constant ADSC_MSK \ ADStartConversion bitmask
: adc.start
  \ start conversion
  ADSC_MSK ADCSRA high
;
: adc.wait
  \ wait for completion of conversion
  begin
    ADCSRA c@ ADSC_MSK and 0=
  until
;
: adc.channel! ( channel -- )
  7 and                 \ clip channel to 0..7
  ADMUX c@ 7 invert and \ read ADMUX, clear old channel
  or                    \ add new channel
  ADMUX c!              \ write
;

: adc.get ( namedpin -- a )
  pin>channel adc.channel! adc.start adc.wait
  ADC @ \ always 10bit
;

\ make sure the ports are set up and do one
\ conversion.
: analog_read ( pinmask portaddr -- n )
     2dup adc.init.pin
     adc.get
;