How to calibrate my accelerometer data

So I’m making a simple game that involves tilt control for android. I am trying to calibrate it so that the device accounts for position upon start-up. So if the user is holding it at an angle, the game will factor that in and adjust the acceleration. Here is my code:

public class PlayerInput : MonoBehaviour 
{	

	float xatstart = 0;
	float yatstart = 0;

	void Start()
	{
		xatstart = Input.acceleration.x;
		yatstart = Input.acceleration.y;

	}

	void Update()
	{
		Vector3 dir = Vector3.zero;
		
		// we assume that the device is held parallel to the ground
		// and the Home button is in the right hand
		
		// remap the device acceleration axis to game coordinates:
		//  1) XY plane of the device is mapped onto XZ plane
		//  2) rotated 90 degrees around Y axis
		dir.x = (-Input.acceleration.y-yatstart);
		dir.z = (Input.acceleration.x-xatstart);
		
		// clamp acceleration vector to the unit sphere
		if (dir.sqrMagnitude > 1)
			dir.Normalize();
		
		// Make it move 10 meters per second instead of 10 meters per frame...
		dir *= Time.deltaTime;
		
		// Move object
		transform.Translate (dir * speed);
   }

}

But whenever I test it, it acts super wacky on tilt. Any suggestions on how to fix this?

public class PlayerInput : MonoBehaviour
{

    	float xatstart = 0;
    	float yatstart = 0;
    
    	public float speed = 20f;
    
    	private Vector3 Move;
    	
    	void Start()
    	{
    		xatstart = Input.acceleration.x;
    		yatstart = Input.acceleration.y;
    		
    	}
    	
    	void Update()
    	{
    		Vector3 dir = Vector3.zero;
    		
    		// we assume that the device is held parallel to the ground
    		// and the Home button is in the right hand
    		
    		// remap the device acceleration axis to game coordinates:
    		//  1) XY plane of the device is mapped onto XZ plane
    		//  2) rotated 90 degrees around Y axis
    		dir.x = (-Input.acceleration.y-yatstart);
    		dir.z = (Input.acceleration.x-xatstart);
    		
    		// clamp acceleration vector to the unit sphere
    		if (dir.sqrMagnitude > 1)
    			dir.Normalize();
    		
    		// Make it move 10 meters per second instead of 10 meters per frame...
    		dir *= Time.deltaTime;
    		
    		// Move object
    		Move = new Vector3 (speed * dir.x,transform.rigidbody.velocity.y, speed * dir.z);
    
    		transform.rigidbody.velocity = Move;
    	}
    }

It depends on what you want to tilt exactly. I assume that you have a rigidbody attached to the object that you wanted to tilt, “Use Gravity” is unchecked and working on 3D. Try to copy-paste above script and see if it’s working for you.
One more thing: you may use Input.acceleration.normalized too for smoothing the movement instead of normalizing it with dir.Normalize().

@Bluewell where did you get dir.z and dir.x variables? they are no in the begining of script maybe this is old unity version?