Skip to content

Instantly share code, notes, and snippets.

@samgiles
Created September 30, 2016 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samgiles/753641697e14146741fe908844553b2d to your computer and use it in GitHub Desktop.
Save samgiles/753641697e14146741fe908844553b2d to your computer and use it in GitHub Desktop.
Simple knock/tap detector
<html>
<body>
<script>
const state = {
x: 0,
y: 0,
z: 0,
knocked: 0,
};
const WINDOW_SIZE_MS = 500;
const KNOCK_THRESHOLD_MS = 500;
let framesPerWindow = 0;
let frames = 0;
window.ondevicemotion = function(event) {
let {x, y, z} = event.acceleration;
x = x === NaN ? 0 : x;
y = y === NaN ? 0 : y;
z = z === NaN ? 0 : z;
framesPerWindow = WINDOW_SIZE_MS / event.interval;
if (frames < framesPerWindow) {
frames++;
}
state.x = (((frames - 1) * state.x) + x) / frames
state.y = (((frames - 1) * state.y) + y) / frames
state.z = (((frames - 1) * state.z) + z) / frames
if (frames >= framesPerWindow) {
if (
x > (state.x + 0.8) ||
y > (state.y + 0.8) ||
z > (state.z + 0.8)
) {
state.knocked++;
}
if (state.knocked === 1) {
state.firstKnock = Date.now();
}
if (state.firstKnock) {
if ((Date.now() - state.firstKnock) > KNOCK_THRESHOLD_MS) {
console.log(state.knocked);
if (state.knocked >= 2 && state.knocked < 9) {
const pEl = document.createElement('p');
pEl.innerText = "Knocked!";
document.body.appendChild(pEl);
}
state.knocked = 0;
state.firstKnock = false;
}
}
}
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment