by Rob Toulson and Tim Wilmshurst from textbook "Fast and Effective Embedded Systems Design: Applying the ARM mbed"
main.cpp@0:1270e200bd76, 2013-06-16 (annotated)
- Committer:
- robt
- Date:
- Sun Jun 16 15:37:30 2013 +0000
- Revision:
- 0:1270e200bd76
by Rob Toulson and Tim Wilmshurst from textbook "Fast and Effective Embedded Systems Design: Applying the ARM mbed"
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
robt | 0:1270e200bd76 | 1 | /* Program Example 13.1: HMC6352 Compass Setup and Read |
robt | 0:1270e200bd76 | 2 | */ |
robt | 0:1270e200bd76 | 3 | #include "mbed.h" |
robt | 0:1270e200bd76 | 4 | // mbed objects |
robt | 0:1270e200bd76 | 5 | I2C compass(p28, p27); // sda, scl |
robt | 0:1270e200bd76 | 6 | Serial pc(USBTX, USBRX); // tx, rx |
robt | 0:1270e200bd76 | 7 | // variables |
robt | 0:1270e200bd76 | 8 | const int addr = 0x42; // define the I2C write Address |
robt | 0:1270e200bd76 | 9 | char cmd[3]; // command array for read and write |
robt | 0:1270e200bd76 | 10 | float pos; // measured position |
robt | 0:1270e200bd76 | 11 | |
robt | 0:1270e200bd76 | 12 | // main code |
robt | 0:1270e200bd76 | 13 | int main() { |
robt | 0:1270e200bd76 | 14 | cmd[0] = 0x47; // 'G' write to RAM address |
robt | 0:1270e200bd76 | 15 | cmd[1] = 0x74; // Operation mode register address |
robt | 0:1270e200bd76 | 16 | cmd[2] = 0x72; // Op mode = 20H, no S/R, continuous |
robt | 0:1270e200bd76 | 17 | compass.write(addr,cmd, 3); // Send operation |
robt | 0:1270e200bd76 | 18 | while (1) { |
robt | 0:1270e200bd76 | 19 | compass.read(addr, cmd, 2); // read the two-byte echo result |
robt | 0:1270e200bd76 | 20 | pos = 0.1 * ((cmd[0] << 8) + cmd[1]); //convert to degrees |
robt | 0:1270e200bd76 | 21 | if (pos>180){ |
robt | 0:1270e200bd76 | 22 | pos=pos-360; |
robt | 0:1270e200bd76 | 23 | } |
robt | 0:1270e200bd76 | 24 | pc.printf("deg = %.1f\n", pos); |
robt | 0:1270e200bd76 | 25 | wait(0.3); |
robt | 0:1270e200bd76 | 26 | } |
robt | 0:1270e200bd76 | 27 | } |
robt | 0:1270e200bd76 | 28 |