Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Native Modules and APIs

Sensors and Haptics

Read the accelerometer, gyroscope and magnetometer with expo-sensors, set update intervals, smooth noisy data, detect shakes and add tactile feedback with expo-haptics.

Phones are packed with sensors: accelerometer, gyroscope, magnetometer, barometer, light, pedometer. Combined with haptics (the small vibrations from the taptic engine), they let an app respond to the physical world: shake to undo, tilt to steer, a satisfying tick when a toggle flips.

The sensor modules need hardware, so the Expo code is read-only. Live stand-ins show the processing you do on the raw numbers, which is where the real work is.

expo-sensors

Terminal
npx expo install expo-sensors

Every sensor has the same shape: addListener(callback) returns a subscription, setUpdateInterval(ms) sets the rate, and isAvailableAsync() tells you if the hardware exists.

TSX
import { Accelerometer } from 'expo-sensors';
import { useEffect, useState } from 'react';

export function useAccelerometer(intervalMs = 100) {
  const [data, setData] = useState({ x: 0, y: 0, z: 0 });

  useEffect(() => {
    let subscription: ReturnType<typeof Accelerometer.addListener> | undefined;
    (async () => {
      if (!(await Accelerometer.isAvailableAsync())) return;
      Accelerometer.setUpdateInterval(intervalMs);
      subscription = Accelerometer.addListener(setData);
    })();
    return () => subscription?.remove();
  }, [intervalMs]);

  return data;
}

What each sensor reports:

Sensor Value Unit Typical use
Accelerometer x, y, z acceleration (includes gravity) g (Earth gravity is about 1 g) shake, tilt, steps
Gyroscope x, y, z rotation rate radians/second turning, spinning
Magnetometer x, y, z magnetic field microtesla compass heading
DeviceMotion acceleration, rotation, orientation mixed fused, easy tilt and orientation
Barometer pressure, relative altitude hPa altitude change
Pedometer step count steps fitness
LightSensor illuminance (Android) lux auto theme

On a table, a phone lying flat reads about { x: 0, y: 0, z: -1 } in g, because gravity is part of the reading. Remember the axes follow the device: x to the right, y up the screen, z out of the screen.

Sensors drain battery, so subscribe only while the screen is visible (useFocusEffect from expo-router) and use the largest interval that works: 100 to 200 ms for tilt, about 16 ms for games.

Raw data is noisy

Raw readings jitter. Two techniques fix most problems: smoothing (a low-pass filter) and thresholds with cool-downs. The first stand-in smooths a tilt reading with an exponential moving average.

JS Smooth noisy sensor data

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A smaller alpha means smoother but laggier values. Choose it by feel.

Detecting a shake

A shake is a short burst of strong acceleration. Compute the magnitude of the vector, compare it with a threshold, and ignore events for a moment afterwards.

JS Shake detector

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Without the cool-down one physical shake triggers a dozen callbacks. The same pattern (debounce, threshold) applies to double taps, flips and "pick up to wake".

Tilt and orientation with DeviceMotion

DeviceMotion fuses sensors, so you get ready-to-use rotation (alpha, beta, gamma in radians) instead of doing the math from raw acceleration:

TSX
import { DeviceMotion } from 'expo-sensors';

DeviceMotion.setUpdateInterval(50);
const sub = DeviceMotion.addListener(({ rotation }) => {
  const rollDegrees = (rotation.gamma * 180) / Math.PI;   // left/right tilt
  const pitchDegrees = (rotation.beta * 180) / Math.PI;   // forward/back tilt
});

A "bubble level" or a parallax background is just these two numbers mapped to a position. The magnetometer plus accelerometer produce a compass heading; for production compasses prefer Location.watchHeadingAsync, which already handles calibration and tilt compensation.

JS Turn tilt into a screen offset

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Haptics

expo-haptics triggers the device's vibration motor in meaningful ways:

Terminal
npx expo install expo-haptics
TSX
import * as Haptics from 'expo-haptics';

Haptics.selectionAsync();                                              // light tick: picker value changed
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);               // Light, Medium, Heavy, Soft, Rigid: physical collision
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);   // Success, Warning, Error: outcome

Use haptics to confirm, not to decorate: a tick for a selection, an impact for a button or snap, a notification pattern for results. Keep them short and rare, and respect the system setting (the calls do nothing when haptics are disabled; they do not work on iOS simulators). On Android, Vibration from react-native offers a plain vibration pattern, and iOS ignores custom durations.

A thin wrapper keeps usage consistent and testable:

JS A haptics helper with web fallback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Never unsubscribing, so the sensor keeps running in the background of the screen.
  • An update interval of a few milliseconds for a feature that needs 100.
  • Using raw values for UI without smoothing.
  • Forgetting that gravity is in accelerometer values (use DeviceMotion.acceleration for gravity-free motion).
  • Overusing haptics, so important feedback gets lost.
  • Testing on simulators, which usually provide no real sensor data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a stationary phone's accelerometer magnitude read, approximately?

    Gravity contributes about 1 g to the reading even when the phone is still.
  2. 2. Why add a cool-down to a shake detector?

    A shake produces many consecutive samples above the threshold.
  3. 3. Which haptic call best signals that a payment succeeded?

    Notification feedback types communicate outcomes: success, warning and error.
  4. 4. What should you do with a sensor listener when the screen unmounts?

    Removing the subscription stops the sensor and saves battery.

Summary

  • expo-sensors modules share one API: check availability, set an interval, add a listener, remove the subscription.
  • Smooth raw data, use thresholds with cool-downs, and prefer DeviceMotion for orientation.
  • expo-haptics provides selection, impact and notification feedback; use it sparingly.
  • Subscribe only while the screen is visible and test on real hardware.

Next: File System and Sharing