Hi I'm using an Arduino uno to program a LIS2DH St accelerometer via SPI. The values I get don't really make sense..I'm not sure if I'm doing something wrong in the code. Can anyone please check it?
#include <SPI.h>
//Register Addresses
const int OUT_X_L = 0x28; //X-axis acceleration data
const int OUT_X_H = 0x29;
const int OUT_Y_L = 0x2A; //Y-axis acceleration data
const int OUT_Y_H = 0x2B;
const int OUT_Z_L = 0x2C; //Z-axis acceleration data
const int OUT_Z_H = 0x2D;
const byte READ = 0b10000000;
const int CS = 10;
void setup()
{
pinMode(CS,OUTPUT);
SPI.begin();
//our device requires data to be sent MSB
//(most significant byte) first, pg. 23
SPI.setBitOrder(MSBFIRST);
//clock is idle high and data is shifted in and out
//on the rising edge of the data clock signal, pg. 23
SPI.setDataMode(SPI_MODE3);
SPI.setClockDivider(SPI_CLOCK_DIV2);
//Create a serial connection to display the data on the terminal.
Serial.begin(9600);
//writeRegister(CTRL_REG1,0x07);
delay(100);
}
void loop()
{
Serial.print(" x = ");
Serial.print(readval(1));
Serial.print(" y = ");
Serial.print(readval(2));
Serial.print(" z = ");
Serial.println(readval(3));
delay (500);
}
unsigned int readRegister(byte x) {
unsigned int r=0;
byte b = x | READ;
digitalWrite (CS, LOW);
SPI.transfer(b);
r = SPI.transfer (0x00);
digitalWrite (CS, HIGH);
return r;
}
int readval (int x) {
int val = 0;
byte h, l;
if (x==1) {
l = readRegister(OUT_X_L);
h = readRegister(OUT_X_H);
}
else if (x == 2) {
l = readRegister(OUT_Y_L);
h = readRegister(OUT_Y_H);
}
else if (x == 3) {
l = readRegister(OUT_Z_L);
h = readRegister(OUT_Z_H);
}
val = ( (h<<8 ) | l);
return val;
}