Using this chip breakout board on the Arduino Uno with the example provided I was getting an error at 180 degrees when raw X is less than zero and raw Y is equal to zero. Adding the following “if” statement to the //convert to heading section fixes things.
if (x < 0 && y==0) {
Z = 180;
}