<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Acceleration Max with Gravity</title>
</head>
<body>
<h1 align="left">Acceleration Max</h1>
<img src="axes.png">
<a id="start_demo" href="#" role="button" >Start the demo</a>
<h4>Accelerometer Max including gravity</h4>
<ul>
<li>X-axis: <span id="Accelerometer_gx">0</span><span> m/s<sup>2</sup></span></li>
<li>Y-axis: <span id="Accelerometer_gy">0</span><span> m/s<sup>2</sup></span></li>
<li>Z-axis: <span id="Accelerometer_gz">0</span><span> m/s<sup>2</sup></span></li>
</ul>
<script>
function updateFieldIfNotNull(fieldName, value, precision=1){
if (value != null) {
document.getElementById(fieldName).innerHTML = value.toFixed(precision);
}
}
let xmax=0;
let ymax=0;
let zmax=0;
function handleMotion(event) {
let x = event.accelerationIncludingGravity.x;
let y = event.accelerationIncludingGravity.y;
let z = event.accelerationIncludingGravity.z;
if (x > xmax) {
xmax = x;
}
if (y > ymax) {
ymax = y;
}
if (z > zmax) {
zmax = z;
}
updateFieldIfNotNull('Accelerometer_gx', xmax);
updateFieldIfNotNull('Accelerometer_gy', ymax);
updateFieldIfNotNull('Accelerometer_gz', zmax);
}
let is_running = false;
let demo_button = document.getElementById("start_demo");
demo_button.onclick = function(e) {
e.preventDefault();
if ( DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === "function") {
DeviceMotionEvent.requestPermission();
}
if (is_running){
window.removeEventListener("devicemotion", handleMotion);
demo_button.innerHTML = "Start demo";
is_running = false;
} else {
window.addEventListener("devicemotion", handleMotion);
document.getElementById("start_demo").innerHTML = "Stop demo";
is_running = true;
xmax = ymax = zmax = 0;
}
};
</script>
</body>
</html>