| 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: 2E49:2118F1:A6577D:BAFF09:695437E2
accept-ranges: bytes
age: 0
date: Tue, 30 Dec 2025 20:36:51 GMT
via: 1.1 varnish
x-served-by: cache-bom-vanm7210036-BOM
x-cache: MISS
x-cache-hits: 0
x-timer: S1767127011.409957,VS0,VE196
vary: Accept-Encoding
x-fastly-request-id: fae73eff394d696f6bd86679309e57ccc5b2f7b9
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 20:46:51 GMT
cache-control: max-age=600
content-encoding: gzip
x-proxy-cache: MISS
x-github-request-id: 2B4A:3FD64F:A7FA37:BCA3FF:695437E2
accept-ranges: bytes
age: 0
date: Tue, 30 Dec 2025 20:36:51 GMT
via: 1.1 varnish
x-served-by: cache-bom-vanm7210036-BOM
x-cache: MISS
x-cache-hits: 0
x-timer: S1767127012.620093,VS0,VE219
vary: Accept-Encoding
x-fastly-request-id: 9fdf702b6a5a0bb8e9b6dbaae4c83c5ea4bd2033
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))