This is a demonstration of the device motion and orientation JavaScript APIs, that read accelerometer data from a mobile device.
You may interact with the page at https://osteele.github.io/p5-orientation-and-motion-example/.
The motion and orientation data is displayed in three ways:
- All motion and orientation values are displayed in textual form
- A ball moves around the screen in response to the accelerometer
- A compass displays the heading and the heading accuracy
(The ball rotation is simply a frill. It does not directly relate to any sensor value.)
The code uses p5.js.
Note that the page needs to served over HTTPS, and viewed on a mobile device.
Some ways to do this are:
-
Run the code on the P5 Web Editor, or (untested) JSFiddle or CodePen.
-
Serve the project from your laptop. For example: (a) Open the project in Visual Studio Code; (b) use the Live Server extension; (c) Use ngrok to create an HTTPS address for it; (d) visit the
https://
URL on your phone. -
Publish the file to GitHub Pages, Netlify, or Vercel. (This is a very slow development cycle.)
This doesn't work:
- Run the program in OpenProcessing.org. This doesn't work because “Source frame did not have the same security origin as the main page.” Example: https://openprocessing.org/sketch/1208470
- The
devicemotion
anddeviceorientation
event listeners may only be added from thenthen
of a call toDeviceMotionEvent.requestPermission
. - The call to
DeviceMotionEvent.requestPermission
needs to occur the handler of a user gesture, such as a mouse click or key press. - Some example code on the web assigns to
window.ondevicemotion
instead of adding callingaddEventListener
. This has the same limitations as callingaddEventListener
with these event names. - JavaScript code that listens to the motion and orientation events only works
if it is (1) served from
localhost
or127.0.0.1
, or (2) served via HTTPS. See the Instructions, above.
MDN Articles:
- Detecting Device Orientation
- Orientation and Motion Data Explained
- DeviceOrientationEvent reference
- DeviceMotionEvent reference
Other documentation:
- Google Developer Docs: Device Orientation & Motion
- Apple Developer Documentation: Device Orientation Event
- Apple Developer Documentation: Device Motion Event
The “View Source” CSS is adapted from Christian Heilmann and Ildar Sagdejev's Pure CSS responsive "Fork me on GitHub" ribbon.
MIT