Help with code for counting steps

I am using the MPU6050 accelerometer to count steps.

I am able to get a Y value from it which lets me track when my arm swings back and forward when walking as Y value is < 1 when arm is forward and > 3 when backward.

My code at the minute counts continuously when it is in these ranges but I only want it to count when it goes from Y < 1 to Y > 3.

So if the Y value went from 0.6 to 3.4 to 0.3 it would count 2 steps.

Is there a way to do this?

int steps = 0;
void setup() {
  Serial.begin(9600);
  Wire.begin();
}

void loop() {
 accelY = Wire.read()<<8|Wire.read();
 
 if (accelY < 1 || accelY > 3)
  {
    steps = steps + 1;
    Serial.print("Steps: ");
    Serial. print(steps);
    Serial.print("\n");
}

sketch_nov25a.ino (3.52 KB)

My code at the minute counts continuously when it is in these ranges but I only want it to count when it goes from Y < 1 to Y > 3.

See the StateChangeDetection example in the IDE and adapt the principle used to detect that a value has become valid rather than when it is valid

You want to “arm” a step when the value is less than ‘1’ and then take the step when armed and when the acceleration > 3. Something like:

int steps = 0;

bool bStepFlag;

void setup() 
{
    Serial.begin(9600);
    Wire.begin();

    bStepFlag = false;

}

void loop() 
{
    accelY = (Wire.read() << 8) | Wire.read();
    
    if( accelY < 1 )
        bStepFlag = true;
    else if( bStepFlag == true && accelY > 3 )
    {
        bStepFlag = false;
        steps++;
        Serial.print("Steps: ");
        Serial. print(steps);
        Serial.print("\n");
    }
 
}

BTW, you don’t need to read the sensor every single loop. For a pedometer a few readings a second would likely be more than enough.