You are reading a single comment by @Pzr0 and its replies. Click here to read the full conversation.
  • You could try just increasing the threshold value > 50 in the above code? Or how close is the magnet nearby? You could make the threshold value dependent on the strength of the magnetic field - since the noise in the reading may well be proportionate to the size of the field.

    Otherwise if the readings keep varying randomly you could try keeping a short term average of the readings and comparing that to work around noise? This isn't tested, but something like it should work:

    var avr = Puck.mag(); // long average
    var savr = Puck.mag(); // short average
    var magDiff;
    Puck.on('mag', function(xyz) {
      // update short average
      var dx = xyz.x-savr.x;
      var dy = xyz.y-savr.y;
      var dz = xyz.z-savr.z;
      savr.x += dx/2;
      savr.y += dy/2;
      savr.z += dz/2;  
      // work out difference in field
      var dx = savr.x-avr.x;
      var dy = savr.y-avr.y;
      var dz = savr.z-avr.z;
      magDiff = Math.sqrt(dx*dx+dy*dy+dz*dz);
      // update average
      var dx = xyz.x-avr.x;
      var dy = xyz.y-avr.y;
      var dz = xyz.z-avr.z;
      avr.x += dx/8;
      avr.y += dy/8;
      avr.z += dz/8;  
      LED.write(magDiff > 50); // this value might need lowering
    });
    Puck.magOn();
    

    You could also do a median filter, which is relatively easy to do with the built-in array.sort.

  • I noticed that when I stop moving my puck the magDiff value may start getting higher and after some seconds starts getting lower.. What can i do for that?

About

Avatar for Pzr0 @Pzr0 started