Skip to content

Instantly share code, notes, and snippets.

@aminnj
Last active November 22, 2023 23:14
Show Gist options
  • Save aminnj/0aaa5189bd872e63f4dfba0cea0b5d2a to your computer and use it in GitHub Desktop.
Save aminnj/0aaa5189bd872e63f4dfba0cea0b5d2a to your computer and use it in GitHub Desktop.
Display and save accelerometer data from mobile browser
<!DOCTYPE html>
<html>
<head>
<title>Accelerometer Data</title>
</head>
<body>
<div id="accelerometerData">
<p>Acceleration X: <span id="accelerationX"></span></p>
<p>Acceleration Y: <span id="accelerationY"></span></p>
<p>Acceleration Z: <span id="accelerationZ"></span></p>
</div>
<div id="lastTenData">
<h3>Last 10 Accelerometer Measurements:</h3>
<ul id="lastTenList"></ul>
</div>
<button id="permissionButton">Request Accelerometer Permission</button>
<button id="saveDataButton">Save Data as CSV</button>
<script>
let permissionButton = document.getElementById('permissionButton');
let saveDataButton = document.getElementById('saveDataButton');
let accelerometerValues = [];
let measurementCount = 0;
permissionButton.addEventListener('click', async () => {
try {
await requestDeviceMotionPermission();
} catch (error) {
console.error('Error requesting permission:', error);
}
});
saveDataButton.addEventListener('click', () => {
downloadCSV();
});
async function requestDeviceMotionPermission() {
if (typeof DeviceMotionEvent.requestPermission === 'function') {
let permission = await DeviceMotionEvent.requestPermission();
if (permission === 'granted') {
startAccelerometer();
} else {
console.error('Permission denied');
}
} else {
console.error('DeviceMotionEvent.requestPermission is not supported');
}
}
function startAccelerometer() {
window.addEventListener("devicemotion", handleMotionEvent, true);
}
function handleMotionEvent(event) {
var acceleration = event.acceleration;
if (acceleration) {
let timestamp = performance.now();
let data = {
x: acceleration.x.toFixed(2),
y: acceleration.y.toFixed(2),
z: acceleration.z.toFixed(2),
t: timestamp,
t_utc: Date.now()
};
accelerometerValues.push(data);
measurementCount++;
updateDisplay(acceleration);
displayLastTenValues();
}
}
function updateDisplay(acceleration) {
document.getElementById("accelerationX").innerText = acceleration.x.toFixed(2);
document.getElementById("accelerationY").innerText = acceleration.y.toFixed(2);
document.getElementById("accelerationZ").innerText = acceleration.z.toFixed(2);
}
function displayLastTenValues() {
let lastTenList = document.getElementById("lastTenList");
lastTenList.innerHTML = '';
const startIndex = Math.max(0, accelerometerValues.length - 10);
const lastTen = accelerometerValues.slice(startIndex);
lastTen.forEach((data, index) => {
let timeDiff = index > 0 ? (data.t - lastTen[index - 1].t).toFixed(2) : '-';
let listItem = document.createElement('li');
listItem.innerText = `#${startIndex + index + 1}: X: ${data.x}, Y: ${data.y}, Z: ${data.z}, Timestamp: ${data.t.toFixed(2)}, Time since previous: ${timeDiff}, t_utc: ${data.t_utc}`;
lastTenList.appendChild(listItem);
});
}
function downloadCSV() {
const now = new Date();
const utcTimestamp = now.toISOString().replace(/[:T-]/g, '_').split('.')[0];
const filename = `accelerometer_data_${utcTimestamp}.csv`;
const csvContent = "data:text/csv;charset=utf-8," +
"x,y,z,t,t_utc\n" + // Header row
accelerometerValues.map(item => Object.values(item).join(',')).join('\n');
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
}
</script>
</body>
</html>
@aminnj
Copy link
Author

aminnj commented Nov 22, 2023

Created with chatgpt.

To host it quickly, put the file into a folder like share/, download ngrok, and host that folder via

ngrok http file://`pwd`/share/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment