Documentation

$sensor

What the device is measuring, as state.

val lux = $sensor("light")

<Text>{Math.round(lux.value)} lx</Text>
@if (!lux.available) { <Text>No light sensor.</Text> }

Why this exists

Reading a sensor on Android means a SensorManager, a listener, and remembering to unregister it. $sensor is the same shape as $display and $permission: an object whose members are state, so reading one in markup subscribes to it and nothing at the call site registers anything.

Members

  • value — the primary axis, as a float; for a three-axis sensor it is x
  • x, y, z — the three axes
  • available — whether the device has this sensor
  • at — the reading's timestamp, in epoch milliseconds

Names

light, pressure, proximity, humidity, temperature, steps, accelerometer, gravity, gyroscope, magnetometer.

The list is closed. Any other name is a build error that lists these.

When it listens

The listener attaches when the app resumes and detaches when it pauses, so a backgrounded app holds nothing. It runs at about 5 Hz and the values are unfiltered: no smoothing and no debouncing. A light sensor that spikes as a hand passes over it reports the spike. Whether it counts is the app's decision.

To move something with the gyroscope, use the tilt-x morph driver. It runs at gesture speed and is built for parallax. To know the number, use $sensor.

Try it

Sensor.wh
val lux = $sensor("light")

<Column class="gap-4">
  <Text>{Math.round(lux.value)} lx</Text>
  @if (!lux.available) {
    <Text>No light sensor.</Text>
  }
</Column>
Kotlin waiting
Scroll into view to compile.

value is state. available says whether the device has the sensor at all, which is a real question for a barometer.

See Also