Comparing values from accelerometer over time

Hi I am new to Arduino and I am trying to use an accelerometer to detect motion.

So far I have got the accelerometer to send values to my Arduino Particle Argon board but I am struggling with implementing some logic that can compare the change in values over time.

To be clear I am trying to detect a significant change in the values which would imply the accelerometer is moving.

#include "Wire.h" // This library allows you to communicate with I2C devices.

const int MPU_ADDR = 0x68; // I2C address of the MPU-6050

int16_t acc_x, acc_y, acc_z;

char tmp_str[7]; // temporary variable used in convert function

char* convert_int16_to_str(int16_t i) { // converts int16 to string. Moreover, resulting strings will have the same length in the debug monitor.
  sprintf(tmp_str, "%6d", i);
  return tmp_str;

void setup() {
  Wire.beginTransmission(MPU_ADDR); // Begins a transmission to the I2C slave (GY-521 board)
  Wire.write(0x6B); // PWR_MGMT_1 register
  Wire.write(0); // set to zero (wakes up the MPU-6050)

void loop() {

  Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) [MPU-6000 and MPU-6050 Register Map and Descriptions Revision 4.2, p.40]
  Wire.endTransmission(false); // the parameter indicates that the Arduino will send a restart. As a result, the connection is kept active.
  Wire.requestFrom(MPU_ADDR, 7*2, true); // request a total of 7*2=14 registers
  // "<<8 |;" means two registers are read and stored in the same variable
  acc_x =<<8 |; // reading registers: 0x3B (ACCEL_XOUT_H) and 0x3C (ACCEL_XOUT_L)
  acc_y =<<8 |; // reading registers: 0x3D (ACCEL_YOUT_H) and 0x3E (ACCEL_YOUT_L)
  acc_z =<<8 |; // reading registers: 0x3F (ACCEL_ZOUT_H) and 0x40 (ACCEL_ZOUT_L)


any help in this would be appreciated thank you

So I need to compare the "acc_x" value at time_1 to "acc_x" at time_2 and if the difference between the two values is significant then produce some action

Your post was MOVED to its current location as it is more suitable.

Accelerometers can't tell if there is motion or not, only that there was a change in motion.
Moving at constant speed the acceleration is 0.

yes I know, that's the whole point of the question. I want to detect when the accelerometer changes from rest to motion, which would be represented as a significant change in values.

ill try explain it like code:

x = read accelerometer
y = read accelerometer 1 second later
threshold = some value

delta = y - x

if (delta > threshold)

then ("motion detected")

Wouldn't it be easier to get data out of the MPU-6050 if you used a library.

newaccelreading = read accel
diffaccel = newaccelreading - oldaccelreading
if diffaccel > threshold then change in accel was up
if diffaccel < -threshold then change in accel was down
oldaccelreading = newaccelreading
loop back.

Do that for your 3 axes.

Tom... :smiley: :+1: :coffee: :australia:

1 Like