aboutsummaryrefslogtreecommitdiff
path: root/amforth-6.5/examples/i2c-compass.frt
blob: 651af14b9901ec7ace4af5743bdaac5bb6c82ab7 (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
\
\ compass module mmc2120 (memsic)
\ hwid is always $30
\ provides:
\
\   i2c.compass.get ( -- status X Y) 
\        X and Y are around 2000 (raw data)
\        status is 0 if no error occured

\ further calculation?

$30 constant i2c.compass

\ internal commands
: i2c.compass.setcoil
  i2c.compass i2c.begin
    0 i2c.tx
    %00000010 i2c.tx \ set coil
  i2c.end
;
: i2c.compass.resetcoil
  i2c.compass i2c.begin
    0 i2c.tx
    %00000100 i2c.tx \ reset coil
  i2c.end
;

: i2c.compass.measure
  i2c.compass i2c.begin
    0 i2c.tx
    %00000001 i2c.tx \ start measurement
  i2c.end
;

: i2c.compass.fetchdata ( -- status x y )
  i2c.compass i2c.begin
    0 i2c.tx
    i2c.start \ rep-start
    i2c.compass i2c.rd i2c.tx
    4 0 do i2c.rx loop i2c.rxn
  i2c.end
  ( -- status msb-x lsb-x msb-y lsb-y)
  swap >< or $fff and >r \ Y
  swap >< or $fff and r> \ X
;

\ get the raw data from the module
\ the numbers for X/Y are usually around 2000.
\ status is 0 if everything is ok
: i2c.compass.get ( -- status x y )
   i2c.compass.resetcoil 1ms
   i2c.compass.setcoil   5 ms
   i2c.compass.measure   5 ms
   i2c.compass.fetchdata
;