Search code examples
mobilearduinoorientationscreen-orientation

Determine 'landscape' and 'portrait' orientation with Arduino


How does a mobile device determine if it is in landscape or portrait mode?

And would it be possible to replicate the same functionality on an Arduino Board given that the same sensors would be available?

For example, the board pictured below would be landscape and if rotated by 90deg it would be portrait.

enter image description here


Solution

  • This article describes it in all detail https://www.safaribooksonline.com/library/view/basic-sensors-in/9781449309480/ch04.html

    The relevant code snippet is provided in Objective-C, but can easily be translated in whatever you need:

    float x = -[acceleration x];
    float y = [acceleration y];
    float angle = atan2(y, x);
    
    if(angle >= −2.25 && angle <= −0.75) {
       //OrientationPortrait
    } else if(angle >= −0.75 && angle <= 0.75){
       //OrientationLandscapeRight
    } else if(angle >= 0.75 && angle <= 2.25) {
       //OrientationPortraitUpsideDown
    } else if(angle <= −2.25 || angle >= 2.25) {
       //OrientationLandscapeLeft];
    }
    

    Explanation: For any real arguments x and y that are not both equal to zero, atan2(y, x) is the angle in radians between the positive x-axis of a plane and the point given by the specified coordinates on it. The angle is positive for counter-clockwise angles, and negative for clockwise angles.