Previous lessonTutorial homeNext lesson

Purchasing Link

Buy from OSOYOO Buy from US

Contents


1Objective

This tutorial focuses on enhancing the OSOYOO V3 Robot Car’s ability to drive straight by using the MPU6050 Inertial Measurement Unit (IMU). The MPU6050, a 3-axis motion tracking device, provides angular velocity (gyroscope) and linear acceleration (accelerometer) data, enabling the robot to actively correct its heading. This lesson covers sensor fusion techniques and PID control algorithms for robust straight-line performance.OSOYOO V3 Robot Car for Arduino with MPU6050 gyroscope

2Parts and Devices

For this lesson, you need the following component. Make sure you have it on hand before you start.

No. Picture Device Qty. Accessories Link
1 MPU6050 3-axis gyroscope module MPU6050 3 Axis Gyroscope 1 Click here to buy

3MPU6050: Principles of Operation

The MPU6050 integrates a 3-axis gyroscope and a 3-axis accelerometer. The gyroscope measures angular velocity, providing information about the robot’s rotational speed around its X, Y, and Z axes. Integrating this data over time yields angular displacement (for example, the yaw angle). However, raw gyroscope data is susceptible to drift, meaning it accumulates small errors over time. The accelerometer measures linear acceleration, which can be used to determine the device’s orientation relative to gravity. While accelerometers are stable over long periods, they are highly sensitive to vibrations and short bursts of movement, making their raw orientation data noisy.
MPU6050 gyroscope module mounted on OSOYOO V3 Robot Car

4Hardware Installation

Step 1: Complete the basic hardware assembly as described in robot car Lesson 1. If you already finished Lesson 1, just keep everything as is.

OSOYOO V3 Robot Car basic chassis assembly

Step 2: Mount the MPU6050 module securely on the robot chassis as shown below. (The MPU6050 communicates with the Arduino via the I2C protocol, which requires only two data lines: SDA (Serial Data) and SCL (Serial Clock), plus power (VCC) and ground (GND).)

MPU6050 wiring diagram for OSOYOO V3 Robot Car Arduino

 

5Software Installation

Open-source Arduino
Software (IDE)
Arduino IDE logo Download software here:
https://www.arduino.cc/en/Main/Software?setlang=en
7-Zip is a free utility
that extracts ZIP files
7-Zip logo Download 7-Zip here for free:
https://www.7-zip.org/

1. Arduino IDE Setup: Download and install the latest Arduino IDE from https://www.arduino.cc/en/Main/Software?setlang=en.

Arduino IDE installation
2. Download Sample Code: Download the sample code for Lesson 2 from here. Extract the contents and you will find a file named v3car-lesson2.ino inside a folder called v3car-lesson2. Open v3car-lesson2.ino in the Arduino IDE.

Open sample code in Arduino IDE

3. Install Libraries
First, download the library ZIP files from the links below:
https://osoyoo.com/driver/2wd/MPU6050_light.zip
https://osoyoo.com/driver/2wd/PID.zip
Next, do NOT unzip them. Open Arduino IDE -> Sketch -> Include Library -> Add .ZIP Library. Add the ZIP files to the Arduino IDE one by one.

Add ZIP library in Arduino IDE

4. Board and Port Selection: Connect the OSOYOO Basic Board (compatible with Arduino UNO) to your computer via a USB cable (Important: make sure the robot car’s power switch is OFF and the battery is disconnected before connecting the board to your PC). Launch the Arduino IDE. Go to Tools > Board and select Arduino Uno. Then go to Tools > Port and select the correct serial port. If you are unsure, check your operating system’s device manager for the assigned port.

Select board and port in Arduino IDE

5. Upload the Code: Click the “Upload” button (right-arrow icon) to compile and upload the sketch to the OSOYOO Basic Board.

Upload code to Arduino board

6. Check Whether Arduino Detects the MPU6050

Open the Serial Monitor (top-right corner of the Arduino IDE), set the baud rate to 9600, and you should see MPU6050 Found! as shown below. Congratulations! The Arduino is detecting the MPU6050 — you are ready to test the car.

Arduino Serial Monitor showing MPU6050 Found

Note: If you see “Failed to find MPU6050 chip“, the MPU6050 wiring has a problem. Make sure:
1) MPU6050 VCC/GND/SDA/SCL are properly connected to the OSOLINK Wi-Fi/BLE I/O shield as per our instructions
2) Arduino A4/A5 pins and SDA/SCL pins have no other wires connected (in line-tracking projects, A4/A5 may already be used by the tracking sensor)

6Test the Car


Place the car on the floor and turn on the power. The car will pause briefly while the Arduino initializes the gyroscope. Then it will drive straight forward. If you push the car with your foot to force it off course, it will automatically correct back to its original direction.

7A Brief Explanation of the Principles and Code

1) How does the Move() function control the car’s movement and steering?
The OSOYOO robot car uses differential steering. The move(speedL, speedR) function takes two parameters, speedL and speedR, representing the rotational speed of the left and right wheels respectively. The speed value ranges from -255 to +255, where a positive value means forward rotation and a negative value means backward rotation. For example, move(-50, 100) means the left wheel rotates backward at speed 50 while the right wheel rotates forward at speed 100, causing the car to make a sharp left turn.
2) MPU6050 Coding Introduction
After initialization, the MPU6050 gyroscope consistently tracks the robot’s orientation relative to its starting direction. When the robot car drifts from this initial direction, the MPU6050 reports the deviation back to the Arduino.
In our code, the Direction variable represents the car’s orientation at the moment it was placed on the ground (we assume it is facing forward, so we set Direction to 0).
After the calculations in the first few lines of the loop() function, we get the car’s current orientation in the currentAngle variable on line 129.

3) Introduction to PID and Code:

a) The Big Idea: What is PID?
Imagine you are driving a car and your goal is to keep it perfectly in the center of your lane. That is what we are asking our robot to do: stay on the “straight ahead” line.
PID is a control algorithm that acts like a smart, attentive driver. It continuously asks three questions to decide how to steer:
  1. P (Proportional): How far am I from the center of the lane right now?
  2. I (Integral): Have I been consistently off-center for the past few moments?
  3. D (Derivative): Am I swerving towards or away from the center too quickly?

By combining the answers to these three questions, the PID controller makes a smooth and efficient steering correction.

b) How the PID Function Works in Our Code
Let’s connect this theory directly to the PID_v1.h library and your code.
1. Initialization (in setup()):
// We tell the PID controller what to watch and what to control.
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

Direction = 0; // Our TARGET is to have an angle of 0 degrees.
myPID.SetMode(AUTOMATIC); // Turn on the controller.
  • &Input: A pointer to our sensor reading. In our code, Input is currentAngle. The PID controller reads this value continuously.
  • &Output: A pointer to our result. The PID controller writes its calculated correction value into the Output variable.
  • &Direction: A pointer to our target. We want to go straight, so we set this to 0.
2. The Main Loop (in loop()):
// 1. We get the sensor reading and put it into the Input variable.
Input = currentAngle; 

// 2. We call the compute function. This is where the PID magic happens!
myPID.Compute(); 

// 3. We use the result to control the motors.
int speedL = baseSpeed - Output;
int speedR = baseSpeed + Output;
move(speedL, speedR);
The myPID.Compute() function does all the hard work internally. Every time it is called (the library handles timing based on SetSampleTime), it:
  1. Reads the value from the Input variable (currentAngle).
  2. Calculates the error: error = Direction - Input.
  3. Calculates the Proportional term (Kp * error).
  4. Calculates and adds the Integral term (Ki * accumulated_error).
  5. Calculates and adds the Derivative term (Kd * rate_of_error_change).
  6. Sums them all up to get the final correction value.
  7. Writes this final value into the Output variable.
So, if Output is +15, it means the robot needs a correction of 15 units. We apply this by slowing down one motor (baseSpeed - 15) and speeding up the other (baseSpeed + 15), causing the robot to turn and reduce its error. If the robot is perfectly straight, Input will be 0, the error will be 0, and Output will be 0, so both motors run at baseSpeed.

4) How to Tune Kp, Ki, and Kd for Stable Movement

  1. Start here: Set Ki = 0.0 and Kd = 0.0 in your code.
  2. Find a Kp value that is stable and does not oscillate (or barely oscillates). This will likely be lower than 1.5.
  3. (Optional but recommended) Add a deadband of about 0.5 degrees to your loop to ignore sensor noise.
  4. Once Kp is stable, slowly increase Kd to reduce any remaining overshoot.
  5. Finally, slowly increase Ki to eliminate long-term drift.

 

8Advanced Considerations and Troubleshooting

By following these guidelines and understanding the underlying principles, you can turn the OSOYOO V3 Robot Car into a capable platform for autonomous navigation, laying the groundwork for more advanced robotics projects.

Previous lessonTutorial homeNext lesson