Access the magnetometer sensor

Hello, I am working on a project to display and test the phone’s sensors (accelerometer, gyroscope etc) by using p5.js. I can’t find any information to access the magnetometer sensor, is there something implemented in P5js ?

Thanks in advance :slight_smile:

Some browsers on some OSes are able to access magnetometer (via Javascript) and some not. It also depends on web server configuration. Here are some useful notes: https://developer.mozilla.org/en-US/docs/Web/API/Magnetometer

Hi, thank you for the response I will try with that method :slight_smile:

Hello,

I am working with sasharvrn, and we have not been successfull in accessing the magnetometer. We understand that this is something that is not supported by all browsers, but that it should be possible to access it using chrome. I made some tests on an Android smartphone + chrome browser, and could run the demo webpage here (Sensor info). So I know that my magnometer is alive and can talk to my browser when asked properly.

I am trying to replicate this using p5.js, following yaniki’s suggestions, tried different ways but none that worked. Here is a link to one of my tries :slight_smile:

(I will paste the code at the end of this message if you prefer not follow the link)

I am sure that I am missing something obvious, but I do not know my way well enough in javascript and p5 to see it. If anyone has a clue, I would appreciate it.

– Code Below –

let magX = 0;
let magY = 0;
let magZ = 0;
let magSensor;

function setup() {
  createCanvas(400, 400);
  magSensor = new Magnetometer();

  magSensor.addEventListener("reading", (e) => {
    magX = magSensor.x;
    magY = magSensor.y;
    magZ = magSensor.z;
  });

  magSensor.start();
}

function draw() {
  //frameRate(2);
  background(220);

  textSize(42);
  fill(255);
  noStroke();
  text("x : " + magX, 25, 50);
  text("y : " + magY, 25, 100);
  text("z : " + magZ, 25, 150);
}