How to detect the device's rotation/orientation?

Holding the device in front of you so that you're looking at the screen, is there a way to detect how the user might rotate the device either clockwise or counterclockwise? I am trying to figure out how to apply physics to an object depending on how the device is oriented.

Is there a way to do this with AI? If yes can you show me an example code/app?

You can check the device orientation through the accelerometer's X, Y and Z values. They constantly show you the orientation of the device in the 3 dimensions.