| CARVIEW |
Select Language
HTTP/2 301
server: GitHub.com
content-type: text/html
location: https://realpython.github.io/pyscript-gravity-sensor/
x-github-request-id: C483:3A7A40:9F8E31:B33890:6953B440
accept-ranges: bytes
age: 0
date: Tue, 30 Dec 2025 11:15:12 GMT
via: 1.1 varnish
x-served-by: cache-bom-vanm7210093-BOM
x-cache: MISS
x-cache-hits: 0
x-timer: S1767093313.500664,VS0,VE199
vary: Accept-Encoding
x-fastly-request-id: 7480d2cf795eec0b809757ec65bd54cbc23a4a18
content-length: 162
HTTP/2 200
server: GitHub.com
content-type: text/html; charset=utf-8
last-modified: Tue, 31 May 2022 19:05:38 GMT
access-control-allow-origin: *
etag: W/"62966702-5d9"
expires: Tue, 30 Dec 2025 11:25:12 GMT
cache-control: max-age=600
content-encoding: gzip
x-proxy-cache: MISS
x-github-request-id: D720:2916CC:A0EEDF:B49977:6953B440
accept-ranges: bytes
age: 0
date: Tue, 30 Dec 2025 11:15:12 GMT
via: 1.1 varnish
x-served-by: cache-bom-vanm7210093-BOM
x-cache: MISS
x-cache-hits: 0
x-timer: S1767093313.713533,VS0,VE233
vary: Accept-Encoding
x-fastly-request-id: f92cfb037950ec229e16b2bf7379c4be95e1eeb7
content-length: 687
PyScript Gravity Sensor
- numpy
from js import addGravityListener
from pyodide import create_proxy
import numpy as np
span = document.querySelector("span")
def callback(x, y, z):
span.innerText = orientation(x, y, z)
def orientation(x, y, z):
gravity = np.array([x, y, z])
v = list(np.round(gravity / np.linalg.norm(gravity)).astype(int))
if v == [ 1, 0, 0]: return "Horizontal counterclockwise"
if v == [-1, 0, 0]: return "Horizontal clockwise"
if v == [ 0, 1, 0]: return "Vertical upright"
if v == [ 0, -1, 0]: return "Vertical upside down"
if v == [ 0, 0, 1]: return "Screen up"
if v == [ 0, 0, -1]: return "Screen down"
return "Tilted"
addGravityListener(create_proxy(callback))