Code
#include “mbed.h”
SPI spi(dp2, dp1, dp6); // mosi, miso, sclk
DigitalOut cs(dp14);
Serial pc(dp16, dp15); // tx, rx
int8_t read(uint8_t reg){
wait_us(100);
cs=0;
spi.write(reg<<1);
int8_t val = spi.write(0x00);
wait_us(100);
cs=1;
return (val);
}
void write(uint8_t reg, uint8_t val){
wait_us(10);
cs=0;
spi.write((reg<<1)|0x80);
spi.write(val);
wait_us(10);
cs=1;
}
int main() {
wait(1);
spi.format(8,0);
pc.baud(9600);
spi.frequency(3000000);
write(0x16,0b00000101);//2g set
wait(1);
//offset
write(0x10,0x11);
write(0x12,0x34);
write(0x14,0x2c);
wait(1);
float gx,gy,gz;
while(1){
gx=(float)(read(0x06))/64.0*9.8;
gy=(float)(read(0x07))/64.0*9.8;
gz=(float)(read(0x08))/64.0*9.8;
pc.printf(“gx=%2.2f gy=%2.2f gz=%2.2fn”,gx,gy,gz);
wait (0.1);
}
}