MEMS Attitude Heading Reference Systems are widely employed to determine a system's attitude, but sensor measurement biases limit their accuracy. This paper introduces a novel factor graph-based method called MAgnetometer and GYroscope Calibration (MAGYC). MAGYC leverages three-axis angular rate measurements from an angular rate gyroscope to enhance calibration for batch and online applications. Our approach imposes less restrictive conditions for instrument movements required for calibration, eliminates the need for knowledge of the local magnetic field or instrument attitude, and facilitates integration into factor graph algorithms within Smoothing and Mapping frameworks. We evaluate the proposed methods through numerical simulations and in-field experimental assessments using a sensor installed on an underwater vehicle. Ultimately, our proposed methods reduced the underwater vehicle's heading error standard deviation from 6.21 to 0.57 degrees for a standard seafloor mapping survey.