Mini Segway
In the spring semester of 2021, my end of semester project in my mechatronics class was to program a mini segway to both balance and to maintain its location in translation using LQR control. The goal was to balance the segway for 6 seconds, minimizing any translational motion. I exceeded this mark and was able to balance my segway for at least 20 seconds. My segway was also able to return to the starting location if disturbed by an outside force. The segway consisted of an arduino mega with an MPU-6500 gyro/accelerometer and custom motor control shield mounted on a servo motor with attached wheel. I used MATLAB and Simulink to program the segway utilizing the Simulink support package for arduino. Although I did not design the segway myself, I did create the mathematical model used to design the LQR controller.
Segway represented as a pendulum and wheel
Using the mathematical model, I obtained a state space model that described the four states of position and velocity in both translational and rotational motion. Since the resulting model was nonlinear, I then used MATLAB to numerically linearize the state space model about the equilibrium point. Now with the linearized state and input matrices, A and B respectively, I used the MATLAB lqr function to calculate the gain matrix K. Simulink was used to create the actual code run on the arduino, using the K calculated in MATLAB. Initially the Q matrix was set to weight all states equally, but was tuned to find the weighting that worked best.
MATLAB function for calculating the segway states
The readings from the gyroscope were used to measure the angular velocity of the segway, and by discrete integration calculate the angular position. The translational position was calculated from the readings of the built-in motor encoder and the known wheel radius. From this, the derivative was taken to get the translational velocity.
Simulink code for balancing segway