MPU6050 - Gyroscope problem

Hello,

This is my second project (and first post on this forum). I'm making self balancing robot. Well, everything would be fine but MPU6050 sometimes misreads position. Here's example: I put robot straight and MPU6050 send to console "0" - It's fine - but when I incline him and again put robot straight sometimes mpu6050 instead of "0" send to console "3". How can I fix this?

I'm using:
Arduino Nano
L293D
MPU6050

My code:
https://pastebin.com/pypAfeXT

btw. sorry for my english

but when I incline him and again put robot straight sometimes mpu6050 instead of "0" send to console "3".

The MPU6050 does NOT send anything to any console.

My code:
https://pastebin.com/pypAfeXT

If you are going to put your code in the rubbish bin, you should put your question(s) there, too.

If you are going to put your question(s) here, put your code HERE.

Gyroscopes don't measure orientation directly. They use numerical integration techniques to integrate the angular velocity. These techniques will always introduce drift, there's nothing you can do about that.

The solution here is to use a sensor fusion algorithm that takes into account the accelerometer data as well (gravity always points downwards). I've had some great results using Sebastian Madgwick's algorithm.

That being said, I'm not sure if you actually need to have a drift-free sensor for a balancing robot, since you can infer the upright orientation as the orientation that doesn't cause the robot to accelerate to either side.

Pieter

Please read and follow the directions in the "How to use this forum" post, and post your code in line, using code tags.