📱 Device Features
Sensors: Accelerometer & More
Accelerometer, Compass, Gyroscope, Barometer.

Accelerometer

csharp
if (Accelerometer.Default.IsSupported)
{
    Accelerometer.Default.ReadingChanged += (s, e) =>
    {
        var (x, y, z) = (
            e.Reading.Acceleration.X,
            e.Reading.Acceleration.Y,
            e.Reading.Acceleration.Z);

        MainThread.BeginInvokeOnMainThread(() =>
            Label.Text = $"X:{x:F2} Y:{y:F2} Z:{z:F2}");
    };
    Accelerometer.Default.Start(SensorSpeed.UI);
}

// Always stop sensors when the page disappears
protected override void OnDisappearing()
{
    Accelerometer.Default.Stop();
    base.OnDisappearing();
}

Other Sensors

csharp
// Compass — magnetic bearing in degrees
Compass.Default.ReadingChanged += (s, e) =>
    heading = e.Reading.HeadingMagneticNorth;
Compass.Default.Start(SensorSpeed.UI);

// Gyroscope — rotational velocity (rad/s)
Gyroscope.Default.ReadingChanged += (s, e) =>
    velocity = e.Reading.AngularVelocity;

// Barometer — atmospheric pressure in hPa
Barometer.Default.ReadingChanged += (s, e) =>
    pressure = e.Reading.PressureInHectopascals;

Key Takeaways

Always check IsSupported before starting a sensor
Stop all sensors in OnDisappearing to conserve battery
SensorSpeed.UI provides fast-enough updates for real-time display
Update UI on the main thread — sensor callbacks are on background threads
Lesson 30 of 30Device Features
← Previous ✓ Back to Curriculum