I have some questions about your code.
First, is your carriage return broken? Put the action for the for loop inside curly braces, so that the body of the loop is clearly distinguishable.
for(int i = 0; i < sizeof(data) && Serial.available() > 0; i++)
{
data[i] = Serial.read();
}
Why does the loop exit? You have two possible reasons for the loop to end. One is that the array to hold the data filled up. The other is that there was no more serial data to read. Which is occurring in your case?
When you run out of serial data to read, have you received a full packet (and x value, a y value, and a z value)?
You have no idea whether the packet is complete, because you are not sending or looking for an end of packet marker.
Serial data transmission is slow. Reading serial data is fast. There is a very good chance that your for loop is reading all the data that has been received before all the data has been sent.
Do you have a clue what this statement does?
Serial.flush();
It dumps any data in the serial buffer that has not yet been read. If your for loop ends because all the data has been read, this statement is useless. If your for loop ends because the array filled up, you have a problem that dumping random amounts of serial data will not solve. GET RID OF THIS STATEMENT. PERIOD.
data[sizeof(data) - 1] = 0;
This puts a NULL at the very last position of the array, not after the last value just stored in the array. Whatever garbage was left in the array from the last pass through loop is still there, between the new data in the array and the end of the array.
My problem is: I'm not getting the desired results, when it comes to calculate the tilt of the accelerometer.
This may be because you are not sending valid data. If you fix the problems mentioned above, you will be receiving an x value, a y value and a z value. These appear to be position values, not vector values. The names i, j, and k typically imply vector data. If the data being sent IS a vector, you should use correct names in the Arduino code, or use some comments to explain what is being sent.
The problem is when I calculate "g_max", which is the length of the gravity vector.
It doesn't return a constant value.
If you are (trying to) send(ing) a unit vector, why is it necessary to compute the constant value on the Arduino, which is not ideally suited for performing floating point arithmetic? If it isn't a unit vector being sent, why are you surprised that the value is not constant?
Storing the output of a function that returns a floating point value in an int is an exercise in frustration. Are you frustrated yet?