0

I'm using gy-521 module and I'm wondering how can i get useful readings from it so that i could work with the data that I'm receiving.

I want for AcX and AcY variable values to be from -255 to 255. How to make this work.

sample data that I'm getting right now

X = 16380 Y = -64
X = 8116 Y = 3520
X = 12564 Y = 8728
X = -12652 Y = 1296
X = -17732 Y = -2420
X = -14576 Y = -2264

;

#include<Wire.h>
const int MPU_addr=0x68;
int16_t AcX,AcY;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B); 
  Wire.write(0);     
  Wire.endTransmission(true);
  Serial.begin(9600);
}

void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  
  AcX=Wire.read()<<8|Wire.read();  
  AcY=Wire.read()<<8|Wire.read();  

  Serial.print("X = "); Serial.print(AcX);
  Serial.print(" Y = "); Serial.println(AcY);

  delay(333);
}
2
  • And what are the values you are actually getting from it?
    – Majenko
    Dec 6 '16 at 23:10
  • X = 16380 Y = -64 X = 8116 Y = 3520 X = 12564 Y = 8728 X = -12652 Y = 1296 X = -17732 Y = -2420 X = -14576 Y = -2264 Dec 6 '16 at 23:16
0

Use this code:

AcX = map(AcX, -32768, 32767, -255, 255);
AcY = map(AcY, -32768, 32767, -255, 255);

Of course, you won't be able to store the resulting value in int8_t since its range is from -128 to 127.

Here you can read more about Arduino map() function.

4
  • Or just divide the values by 128 (the same as a right-shift by 7 bits).
    – Majenko
    Dec 6 '16 at 23:30
  • That is correct. However, by using map() you can tweak the input/output ranges. The sensor maybe doesn't return values below some threshold and in that case using shift would result in lower resolution of the output.
    – Chupo_cro
    Dec 6 '16 at 23:34
  • could you give me an example Dec 6 '16 at 23:34
  • For example, if you notice the sensor never returns values below -25000 you can use AcX = map(AcX, -25000, 25000, -255, 255); to increase the output resolution. Of course, the maximum value that sensor returns, in that case must not be above +25000. If the maximum value is e.g. 26000 then you must use AcX = map(AcX, -26000, 26000, -255, 255);
    – Chupo_cro
    Dec 6 '16 at 23:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.