![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Using an accelerometer to move a ball on an LED screen.
ADXL.cpp@1:c436c1b8333b, 2016-01-20 (annotated)
- Committer:
- bentogami
- Date:
- Wed Jan 20 21:20:23 2016 +0000
- Revision:
- 1:c436c1b8333b
- Parent:
- 0:708949ec9140
Mission success!
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
bentogami | 0:708949ec9140 | 1 | #include "ADXL.h" |
bentogami | 0:708949ec9140 | 2 | |
bentogami | 0:708949ec9140 | 3 | SPI acc(p11, p12, p13); |
bentogami | 0:708949ec9140 | 4 | DigitalOut cs(p10); |
bentogami | 0:708949ec9140 | 5 | char buffer[6]; |
bentogami | 1:c436c1b8333b | 6 | int16_t tempData[3]; |
bentogami | 0:708949ec9140 | 7 | float x, y, z; |
bentogami | 0:708949ec9140 | 8 | |
bentogami | 0:708949ec9140 | 9 | void accConfig() { |
bentogami | 0:708949ec9140 | 10 | cs=1; // initially ADXL345 is not activated |
bentogami | 0:708949ec9140 | 11 | acc.format(8,3); // 8 bit data, Mode 3 |
bentogami | 0:708949ec9140 | 12 | acc.frequency(2000000); // 2MHz clock rate |
bentogami | 0:708949ec9140 | 13 | cs=0; //select the device |
bentogami | 0:708949ec9140 | 14 | acc.write(0x31); // data format register |
bentogami | 0:708949ec9140 | 15 | acc.write(0x0B); // format +/-16g, 0.004g/LSB |
bentogami | 0:708949ec9140 | 16 | cs=1; //end of transmission |
bentogami | 0:708949ec9140 | 17 | cs=0; //start a new transmission |
bentogami | 0:708949ec9140 | 18 | acc.write(0x2D); // power ctrl register |
bentogami | 0:708949ec9140 | 19 | acc.write(0x08); // measure mode |
bentogami | 0:708949ec9140 | 20 | cs=1; // end of transmission |
bentogami | 0:708949ec9140 | 21 | } |
bentogami | 0:708949ec9140 | 22 | |
bentogami | 0:708949ec9140 | 23 | void getAccel(float* data) { |
bentogami | 0:708949ec9140 | 24 | wait(0.2); |
bentogami | 0:708949ec9140 | 25 | cs=0; //start a transmission |
bentogami | 0:708949ec9140 | 26 | acc.write(0x80|0x40|0x32); // RW bit high, MB bit high, plus address |
bentogami | 0:708949ec9140 | 27 | for (int i = 0;i<=5;i++) { |
bentogami | 0:708949ec9140 | 28 | buffer[i]=acc.write(0x00); // read back 6 data bytes |
bentogami | 0:708949ec9140 | 29 | } |
bentogami | 0:708949ec9140 | 30 | cs=1; //end of transmission |
bentogami | 0:708949ec9140 | 31 | tempData[0] = buffer[1] << 8 | buffer[0]; //combine MSB and LSB |
bentogami | 0:708949ec9140 | 32 | tempData[1] = buffer[3] << 8 | buffer[2]; |
bentogami | 0:708949ec9140 | 33 | tempData[2] = buffer[5] << 8 | buffer[4]; |
bentogami | 0:708949ec9140 | 34 | x = tempData[0]*0.004; |
bentogami | 0:708949ec9140 | 35 | y = tempData[1]*0.004; |
bentogami | 0:708949ec9140 | 36 | z = tempData[2]*0.004; |
bentogami | 0:708949ec9140 | 37 | data[0] = x; |
bentogami | 0:708949ec9140 | 38 | data[1] = y; |
bentogami | 0:708949ec9140 | 39 | data[2] = z; |
bentogami | 1:c436c1b8333b | 40 | |
bentogami | 0:708949ec9140 | 41 | } |