Knowing .NET Sometimes a coder who writes, sometimes a writer who codes. Formerly, a coder who edited magazines.

April 6, 2013

Accessing the Android Barometer using Xamarin.Android

Filed under: Xamarin — larry @ 10:58 am


< ![CDATA[
[Activity (Label = "HelloBarometer", MainLauncher = true)]
public class Activity1 : Activity, ISensorEventListener
    TextView mainLabel;  

    protected override void OnCreate(Bundle bundle)
        // Set our view from the "main" layout resource
        //Detect the barometer
        var sm = (SensorManager) this.GetSystemService(Context.SensorService);
        var barry = sm.GetDefaultSensor(SensorType.Pressure);
        //Subscribe to it
        sm.RegisterListener(this, barry, SensorDelay.Normal);
        // Get our button from the layout resource,
        // and attach an event to it
        mainLabel = FindViewById<textview>(Resource.Id.myText);

    public void OnAccuracyChanged(Sensor sensor, SensorStatus accuracy)
        Console.WriteLine("Things have changed");

    public void OnSensorChanged(SensorEvent pressureEvent)
        Console.WriteLine("Under pressure " + pressureEvent);
        var hPAs = pressureEvent.Values[0];
        var msg = string.Format("Current pressure: {0} hPA!", hPAs);
        mainLabel.Text = msg;
        var calcedAltitude = calculateAltitudeInFeet(hPAs);
        FindViewById<TextView>(Resource.Id.altitudeText).Text = string.Format("Calculated altitude is {0} ft", calcedAltitude);

    double calculateAltitudeInFeet(float hPAs)
        var pstd = 1013.25;
        var altpress =  (1 - Math.Pow((hPAs/pstd), 0.190284)) * 145366.45;
        return altpress;

I mean, I know I work for the guys, but this is just *ridiculously* easy. An hour ago I was installing the SDK…

And, yes, I live high on the side of an active volcano.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress