I have an accelerometer mounted to an inverted pendulum (i.e. a cart-pole robot) which I'm using to measure the tilt angle from the vertical upright position (+y direction). If the inverted pendulum is held motionless at a fixed angle, the accelerometer essentially detects the gravity direction as a vector $(g_x,g_y)$ and the tilt angle $\theta$ can be determined by
$$\theta=tan^{-1}(\frac{g_x}{\sqrt{g_x^2+g_y^2}}).$$
However, if the inverted pendulum is in motion (e.g. if I'm dynamically trying to balance it like a cart-pole system), the pendulum itself is accelerating the accelerometer in a direction which is not necessarily the gravity direction. Acceleration from the cart may also distort the measurement of the gravity direction by the accelerometer as well. In such a case, I don't think the formula above is necessarily appropriate.
Of course, I'm not 100% sure that the swinging motion of the pendulum and the forward-backward motion of the cart are significant enough to distort the angle measurement on the accelerometer. I presume that if I start with initial conditions close to $\theta=0$ on the pendulum, it shouldn't be that significant. Nonetheless, if the pendulum is significantly perturbed by a disturbance force, I think the accelerometer's measurements must be compensated in some way.
How can I compensate for pendulum and cart accelerations when using an accelerometer to detect the tilt angle?