Software to filter out signal spikes?

I’ve just been wondering if there’s not a simple way to help avoid spurious signals from causing, say, a While loop from ending too soon. I don’t know if there is some kind of digital filtering that goes on behind the scenes with the Cortex, etc. so I was wondering if some software might be able to help with it if there is not.

I thought about the following, written kinda in pseudocode but it seems somewhat weird. :confused:

Would something like this make sense to use?
Basically what I think this would do is cause a While loop to check multiple times to make sure the sensor actually reached its value and wasn’t faked out by a signal spike.



SafeCount = 10;
Counter = 0;

While(SensorValue<TargetValue  OR  Counter<SafeCount)
  {

     Turn the motor on;

      If(SensorValue >= TargetValue)  //If the desired condition was met....
         {
            Counter = Counter + 1;  //...then start counter.
            Wait 1 millisecond;
         }
  }

  Turn the motor off;

Sure, I wrote something to get around a pot occasionally giving a bad value for the kids last weekend.

task
turntableTask()
{
   // attempt to fix the bad pot
  int lastPot = SensorValue[pot];

  if( turnTablePosition > SensorValue[pot] )
    {
    while((SensorValue[pot] < turnTablePosition) && (lastPot < turnTablePosition))
      {
      motor[TurnTable] = -50;
      lastPot = SensorValue[pot];
      wait1Msec(25);
      }
    }
  else
    {
    while((SensorValue[pot] > turnTablePosition) && (lastPot > turnTablePosition))
      {
      motor[TurnTable] =  50;
      lastPot = SensorValue[pot];
      wait1Msec(25);
      }
    }

  motor[TurnTable] = 0;
  turnTableDone = 1;
}

That’s only a one sample delay but can be enough sometimes to fix a flakey pot.

sometimes I use an IIR (infinite impulse response) filter, here is an example filtering current in the smartMotor library.

    // simple iir filter to remove transients
    m->filtered_current = (m->filtered_current * 0.8) + (i_bar * 0.2);

Very cool. Thanks very much! :slight_smile: