<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Acceleration with Gravity</title>
</head>
<body>
<h1 align="left">Acceleration</h1>
<img src="axis.png">
<a id="start_demo" href="#" role="button" >Start the demo</a>
<h4>Accelerometer 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);
}
function handleMotion(event) {
updateFieldIfNotNull('Accelerometer_gx', event.accelerationIncludingGravity.x);
updateFieldIfNotNull('Accelerometer_gy', event.accelerationIncludingGravity.y);
updateFieldIfNotNull('Accelerometer_gz', event.accelerationIncludingGravity.z);
}
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";
demo_button.classList.add('btn-success');
demo_button.classList.remove('btn-danger');
is_running = false;
}else{
window.addEventListener("devicemotion", handleMotion);
document.getElementById("start_demo").innerHTML = "Stop demo";
demo_button.classList.remove('btn-success');
demo_button.classList.add('btn-danger');
is_running = true;
}
};
</script>
</body>
</html>