The problem is, your x axis is always 0, so atan2(0, y) will always return PI/2 or -PI/2. The rest is correction function. Is it possible that you mounted your sensor so that the x axis is always 0 and the movement axis are y and z? If so, you have to change your code:
// Calculate heading when the magnetometer is level, then correct for signs of axis.
float heading = atan2( scaled.ZAxis,scaled.YAxis);
It's possible that you have to swap the two axis again depending on your mount position.