Design and Implementation of Model Predictive Control for a Gyroscopic Inverted Pendulum

This study proposes the design of an active stabilizing system (ASAS) for a single-track vehicle. Using the gyroscopic effects of two flywheels, this system can generate control torque to stabilize the vehicle in cases where there is centrifugal force of turning. To control the flywheel gimbals to generate stabilizing torque, a model predictive controller (MPC) is applied to control the system. For the controller design and performance evaluations, a model of a gyroscopic inverted pendulum is developed. Control strategies are proposed to stabilize the vehicle in the cases of straight running, circular motion, and path following. The results of the proposed stratgies when controlling the gyroscopic inverted pendulum showed good performance even with physical limitations of the control torques. In order to evaluate the real-time performance and the feasibility of the MPC, a real-time simulator is employed, which includes two embedded STM32F407 boards. The dynamic system and the control algorithms are respectively embedded into two STM32F407 boards for real-time simulation. Implementations of the MPC in this study demonstrate that the proposed controllers are feasible for real-time applications.


Introduction
The gyroscopic effect has many applications over a wide range of technical fields. Since this effect generates large torque with fast responses, it is used for both the active and passive stabilization of unstable dynamic systems. A conventional application of the gyroscopic effect is the stabilization of a ship's roll motion, as discussed by Townsend and Shenoi [1]. In aerospace and astronautic engineering, the gyroscopic effect is used in attitude guidance systems for spacecraft and satellites [2,3]. Lemus and Berry [4,5] applied it to develop a balance assistance device for humans.
Single-track vehicles, such bicycles, are highly unstable at low speeds. The history and state-of-the-art discussions on topic of bicycle dynamics and control were reviewed comprehensively by Schwab and Meijaard [6]. In a study of bicycle stability, Meijaard et al. [7] analysed the eigenvalues of a linearized bicycle model that was experimentally validated by Kooijman [8]. Results of these works showed the relationship of the bicycle's stability with its longitudinal speed. To explain the self-stablizing characteristic of a bicycle, Kooijman et al. [9] built a two-mass-skate bicycle model. After conducting experiments with this bicycle model, the authors found three parameters that were very important for self-stability: the front wheel spin angular momentum, the trail, and front-assembly mass distribution. Adjusting one of these three parameters can passively enhance the self-stable ability of a bicycle. To actively stabilize a bicycle, there are several methods, such as steering using the handle bar [10][11][12], moving the centre of mass [13,14], and using a gyroscope.
In applications using gyroscopes to stabilize single-track vehicles, Różewicz et al. [15] derived a mathematical model of a bicycle augmented with a gyroscope. However, no control strategies for this system were proposed. Lam et al. in their work [16] used a control moment gyro as an actuator to stabilize a small bicycle. By using proportional-derivative (PD) controllers, a stationary bicycle with initial angle of 11.6 • was stabilized and continued to oscillate around the upright position with steady-state errors of ±1.5 • . Yetkin et al. [17] designed an autonomous bicycle steered by the gyroscopic effect of a flywheel, where a sliding mode control algorithm is used for stabilization control of a static bicycle. The experimental results showed good performance in disturbance rejection, though chattering appeared in the control inputs. When applying robustness control, Thanh and Parnichkun [18] proposed using particle swarm optimization-based H 2 /H ∞ controller to balance a gyroscope-controlled bicycle. Though this prototype could move forward and backward at a low speed, its motions seem unnatural since the lean angle of the bicycle was kept as zero all the time to avoid the continuous rotation of the flywheel's gimbal angle. Hsieh et al. [19] designed a gyroscopic balancer for a riderless bicycle, and then verified their fuzzy sliding mode control with a standstill bicycle under impact disturbances. Chi and Chou [20] extended this work by developing a more complicated control algorithm. Their adaptive fuzzy sliding mode controller stabilized the bicycle when moving forward, though it failed to control the bicycle under the impact of constant disturbances by centrifugal forces.
To stabilize a bicycle using a gyroscope, an inverted pendulum-like model has been used to simplify the controller design processes [17][18][19][20]. Furthermore, the use of an inverted pendulum for control algorithm design and verification is very common in studies of balancing problems. For example, Wakatsuki et al. [21] used this approach to simulate an electric bicycle with power steering systems. Zhu et al. [22] used a gyroscopic inverted pendulum to benchmark an adaptive control algorithm for a single-wheel pendulum robot. The validity of the pendulum model combined with a single-wheel pendulum robot was verified by experimental data. Similarly, Jin et al. [23] used an inverted pendulum to evaluate the efficiency of a stabilizing device before applying it to a bicycle. In studies to enhance human balance using gyroscopic effect, Lemus et al. [4,5] conducted experiments on an inverted pendulum test bench instead of using an actual human.
Balancing an inverted pendulum also is an attractive topic in the field of control engineering. Numerous control algorithms have been proposed to address this problem. Using a classical control approach, Luecke et al. [24] used multiple loops of PD controllers, while Olivares and Albertos [25] used a proportional-integral-derivative (PID) controller for the inner loops and a linear controller for the outer loop. In another approach, Lin and Peng [26] proposed an evolutionary neural fuzzy controller that controls an inverted pendulum system. Guo et al. [27] applied sliding mode control theory and Messikh et al. [28] proposed model predictive controllers to stabilize a critical damped inverted pendulum. Compared with other control algorithms, the model predictive controller (MPC) offers an optimal control solution that minimizes output errors and control efforts. MPC predicts future outputs over a horizon using a state-space model of the system and incorporates the predicted output errors in a quadratic cost function. The cost function is minimized and subjected to the system's hard constraints during control process by using the quadratic programing method. Hence, MPC can effectively deal with constraints of the system and it is very important for a controller to deal with these constraints since they are present in many real-life system, such as the system's natural and physical limitations.
As discussed in the literature on applying gyroscopic effects to actively stabilize single-track vehicles, most of these studies focused on using gyroscopic torque of the spinning flywheels to maintain a bicycle upright under impact disturbances. Using a gyroscopic stabilizer provides the bicycle with the advantage of strong stability at low speeds, especially when it is difficult for the steering control to maintain bicycle balance [29]. However, a single-track vehicle requires a roll angle to be stable under the centrifugal forces of turning, and controlling a single-track vehicle so that it is upright at all times significantly reduces its mobility in turning. Even when some advanced algorithms were used to control the gyroscope systems [18][19][20], they still could not stabilize a bicycle when the centrifugal forces appeared. In this study, the gyroscopic effect is applied to design an assistant system for single-track vehicles that can actively help stabilize the vehicle in cases with and without centrifugal forces. To control the stabilizing system, which is a multiple input, multiple output control problem under the hard constraints of physical limitations, this study proposes the use of model predictive controllers. The MPC design is based on an inverted pendulum-like model of a bicycle. Then, a gyroscopic inverted pendulum is used to evaluate the performance of the control strategies in cases of with and without centrifugal forces. The feasibility and real-time performance of the MPC are evaluated by embedding the algorithm for real-time microprocessor boards. This paper is organized as follows, Section 1 gives a literature review of related research and specifies motivation for this study. In Section 2, the dynamics of a gyroscopic inverted pendulum is described, and Lagrangian equations are used to obtain the governing equations for the system. The equations of motion for the system are then verified by comparing the response with that provided by the commercial software ADAMS model (MSC Software Corporation, Newport Beach, CA, USA). Section 3 describes the design of model predictive controllers and control stategies to stabilize the system. Section 4 presents the results and a discussion of the study cases. Finally, Section 5 presents the conclusions of this study.

Dynamic System Modeling
The gyroscopic inverted pendulum uses the principle of the gyroscopic effect of a spinning disk as shown in Figure 1. A disk with mass moment of initial I rotates about its z axis at a speed of → .
φ . When its precession angle changes at the rate of → .
α , a torque is generated along its x axis with a magnitude and its direction is determined by: At a precession angle α, the effective torques of the gyroscope effect on the horizontal and vertical axes are, respectively, where T H is used to stabilize the vehicle system in the roll motion and T V is an unwanted torque since it causes some uncontrolled effects on the yaw motion of the vehicle. By using two flywheels rotating in opposite directions at the same speed, the torque on the vertical axis of a flywheel will cancel out that of the other one. Since the magnitude of T H depends on the cosine of the precession angle α, the precession angle should be kept as small as possible in order to generate a larger effective toque on the horizontal axis. At a precession angle of ±90 • , the effective torque on the horizontal axis is zero.
Appl. Sci. 2017, 7, 1272 3 of 20 assistant system for single-track vehicles that can actively help stabilize the vehicle in cases with and without centrifugal forces. To control the stabilizing system, which is a multiple input, multiple output control problem under the hard constraints of physical limitations, this study proposes the use of model predictive controllers. The MPC design is based on an inverted pendulum-like model of a bicycle. Then, a gyroscopic inverted pendulum is used to evaluate the performance of the control strategies in cases of with and without centrifugal forces. The feasibility and real-time performance of the MPC are evaluated by embedding the algorithm for real-time microprocessor boards. This paper is organized as follows, Section 1 gives a literature review of related research and specifies motivation for this study. In Section 2, the dynamics of a gyroscopic inverted pendulum is described, and Lagrangian equations are used to obtain the governing equations for the system. The equations of motion for the system are then verified by comparing the response with that provided by the commercial software ADAMS model (MSC Software Corporation, Newport Beach, CA, USA). Section 3 describes the design of model predictive controllers and control stategies to stabilize the system. Section 4 presents the results and a discussion of the study cases. Finally, Section 5 presents the conclusions of this study.

Dynamic System Modeling
The gyroscopic inverted pendulum uses the principle of the gyroscopic effect of a spinning disk as shown in Figure 1. A disk with mass moment of initial I rotates about its z axis at a speed of φ   .
When its precession angle changes at the rate of α   , a torque is generated along its x axis with a magnitude and its direction is determined by: .
At a precession angle α , the effective torques of the gyroscope effect on the horizontal and vertical axes are, respectively, cos , where H T is used to stabilize the vehicle system in the roll motion and V T is an unwanted torque since it causes some uncontrolled effects on the yaw motion of the vehicle. By using two flywheels rotating in opposite directions at the same speed, the torque on the vertical axis of a flywheel will cancel out that of the other one. Since the magnitude of H T depends on the cosine of the precession angle α , the precession angle should be kept as small as possible in order to generate a larger effective toque on the horizontal axis. At a precession angle of ±90°, the effective torque on the horizontal axis is zero.  When designing control strategies to stabilize a single-track vehicle, an inverted pendulum-like bicycle model (as shown in Figure 2) is obtained by assuming that the bicycle tires are knife-edge rolling disks with point contacts on a flat road surface, that there is no longitudinal or lateral slip at the contact points, and that the bicycle steering is fixed at a constant angle. In this figure, Γ o is an inertial coordinate system of Society of Automotive Engineers (SAE) standard, m is the total mass of the system, h c is the height of the centre of mass, g is the gravitational acceleration, r is radius of the circular path, v is the longitudinal speed of the bicycle, F c is the centrifugal force, N is the normal reaction force of the ground to the bicycle tires, F f is the friction force between the tires and the road surface at the contact points, and θ is the roll angle of the bicycle. In order to evaluate the performance of both the designs and the control strategies, a nonlinear inverted pendulum model is developed in the next section. Appl. Sci. 2017, 7, 1272 When designing control strategies to stabilize a single-track vehicle, an inverted pendulum-like bicycle model (as shown in Figure 2) is obtained by assuming that the bicycle tires are knife-edge rolling disks with point contacts on a flat road surface, that there is no longitudinal or lateral slip at the contact points, and that the bicycle steering is fixed at a constant angle. In this figure, o Γ is an inertial coordinate system of Society of Automotive Engineers (SAE) standard, m is the total mass of the system, c h is the height of the centre of mass, g is the gravitational acceleration, r is radius of the circular path, v is the longitudinal speed of the bicycle, c F is the centrifugal force, N is the normal reaction force of the ground to the bicycle tires, f F is the friction force between the tires and the road surface at the contact points, and θ is the roll angle of the bicycle. In order to evaluate the performance of both the designs and the control strategies, a nonlinear inverted pendulum model is developed in the next section. In this study, the design of the gyroscopic inverted pendulum includes two spinning flywheels attached to gimbal frames, four electric motors, and bevel gears as shown in Figure 3a. The two flywheels spin in opposite directions at the same speed in order to cancel the unwanted effect of a rotating mass on the yaw dynamics of the vehicle. By using two flywheels, the maximum effective torque that can be generated is the sum of the torque values for each flywheel.
As shown in Figure 3, the flywheels rotate on gimbal frames and are powered by the driving torques of two direct current (DC) electric motors that are attached to the gimbal frames and connected to the flywheel's shafts via couplings. Two other DC motors are used to rotate the gimbal frames. The driving torques of these motors are transmitted to the gimbal axes via bevel gears. The maximum and minimum values of the gimbal angle are limited from −90° to 90° by limiting switches. To avoid any damage to the system due to a failure in control, four rubber restraints are placed on the platform to prevent the inverted pendulum from falling more than  In this study, the design of the gyroscopic inverted pendulum includes two spinning flywheels attached to gimbal frames, four electric motors, and bevel gears as shown in Figure 3a. The two flywheels spin in opposite directions at the same speed in order to cancel the unwanted effect of a rotating mass on the yaw dynamics of the vehicle. By using two flywheels, the maximum effective torque that can be generated is the sum of the torque values for each flywheel.
As shown in Figure 3, the flywheels rotate on gimbal frames and are powered by the driving torques of two direct current (DC) electric motors that are attached to the gimbal frames and connected to the flywheel's shafts via couplings. Two other DC motors are used to rotate the gimbal frames. The driving torques of these motors are transmitted to the gimbal axes via bevel gears. The maximum and minimum values of the gimbal angle are limited from −90 • to 90 • by limiting switches. To avoid any damage to the system due to a failure in control, four rubber restraints are placed on the platform to prevent the inverted pendulum from falling more than 45 • . A total of five encoders are used to measure the angle of each joint in the system.

Nonlinear Dynamic Model
and the coordinate 1 g Γ is obtained by rotating b Γ about its b j axis through an angle 1 α : Similarly, the coordinate 2 g Γ is obtained by rotating through an angle 2 α : The position of the inverted pendulum's centre of mass of b in the coordinate system b Γ is:  Figure 3b shows the definitions of the coordinate systems that are required to describe the system's motions. The lower-case letters b, g i , and f i , where i = 1, 2, present the centres of mass of five bodies: the inverted pendulum, two gimbal frames, and two flywheels, respectively. Four Society of Automotive Engineers (SAE)-standard coordinate systems are used in the model: an inertial frame Γ o (I, J, K) that is fixed on the ground, a reference frame Γ b (i b , j b , k b ) that is mounted on the inverted pendulum at point O, and the two frames Γ g1 (i g1 , j g1 , k g1 ) and Γ g2 (i g2 , j g2 , k g2 ) that are placed on the gimbal's revolute joints G 1 and G 2 which move with the gimbal frames. The coordinate Γ b rotates about the I axis of Γ o through an angle θ. The transformation between each coordinate system is defined by:

Nonlinear Dynamic Model
and the coordinate Γ g1 is obtained by rotating Γ b about its j b axis through an angle α 1 : Similarly, the coordinate Γ g2 is obtained by rotating through an angle α 2 : The position of the inverted pendulum's centre of mass of b in the coordinate system Γ b is: the position of the gimbal joint G i in Γ b is: The position of the gimbal frame's centre of mass of g i and f i in Γ gi is: The position of these points in Γ o are obtained by: The angular velocity of each body is calculated as: The velocity of each body is calculated as: From Equations (12) and (13), the kinetic energy of the system is obtained by: where I b , I gi and I f i are the mass moment of inertia of each body.
The total potential energy of the system is By applying the Lagrangian equation for the total kinetic and total potential energy (14), (15), the system's equations of motion are: where L = T − V is the Lagrangian, q i is the ith generalized coordinate, and Q i is the ith non conservative force applied at each revolute joint. The nonlinear equations of motion (16) can be rewritten in a matrix form as: where matrix M ∈ R 5×5 is the mass matrix of the system, q is the vector of generalized coordinate q = [θ, α 1 , α 2 , φ 1 , φ 2 ] T , and f ∈ R 5×1 is the vector of nonlinear functions. In the next section, this nonlinear model is embedded on a microprocessor board to simulate the behaviuors of the dynamic system in real time.

Model Verification
The parameters for the inverted pendulum in Table 1 are derived from the 3D design of the system with selected hardware. By substituting these parameters into Equation (17), a numerical model that simulates the system's behaviours is obtained in Matlab/Simulink (MathWorks, Inc., Natick, MA, USA) by using an S-function block. To verify the model of the system's dynamics, the responses of the mathematical model are compared with the responses of a computer-aided engineering (CAE) model that is constructed with the commercial software package ADAMS (MSC Software Corporation, Newport Beach, CA, USA). An inverted pendulum is an unstable system that falls if no control actions are taken. Therefore, it is difficult to make a comparison based on the uncontrolled responses of this system. Preventing the inverted pendulum from falling can thus generate enough data for comparisons. Two dynamic models are controlled to balance around the upright position by using the same controllers. A simple control algorithm such as PID can be used to generate the closed loop responses.
The PID control scheme for the system is shown in Figure 4. Three PID controllers are used to control the inverted pendulum. The PID controller in the outer loop minimizes the roll angle θ and generates reference gimbal angles for the inner loop. Since the two flywheels spin at a constant speed in opposite directions, the gimbal angles α 1 and α 2 are controlled in different directions to allow a summation of the effective torque on the horizontal axis: The main task of the two PID controllers in the inner loops is controlling the gimbal frames to follow the reference signals. When the gimbal angles change at rate of . α 1 and . α 2 , the gyroscopic effects generate torques at the pivot of the inverted pendulum that can stabilize the system, as shown in Equation (18). After the inverted pendulum is stabilized in the upright position, PID2 and PID3 bring the gimbal angle back to its zero position and waiting for the next action.
In this simulation, the flywheels spin at a constant speed of 4000 rpm which is controlled independently using speed controllers, and the inverted pendulum is given an initial angle of 5 • . The parameters for the outer loop PID are K P1 = 3, K I1 = 5.65, and K D1 = 0.02. Since both flywheels have the same parameters, the two PID controllers of the inner loop have the same parameters, which are K P2,3 = 0.07, K I2,3 = 0, and K D2,3 = 0.001. Figure 5a compares the roll angle θ in 3 s, with the blue solid line indicating the response of the mathematical model and the red dashed line indicating the response of the ADAMS model. The maximum difference between these two models is 0.002 • . In Figure 5b,c the same notations are used to describe the comparison of gimbal angles. In this figure, both models exhibit the same responses for gimbal angles α 1 and α 2 . The difference in the roll angle θ is caused by numerical tolerances of different solvers in Matlab and ADAMS. When the inverted pendulum oscillates, the numerical errors are accumulated after each integration and the maximum value after 3 s of simulation is 0.002 • .
A comparison of the results shows that the proposed mathematical model (17) models the system exactly and can be used with an embedded hardware to simulate the real-time dynamic behaviours of the system. The main task of the two PID controllers in the inner loops is controlling the gimbal frames to follow the reference signals. When the gimbal angles change at rate of α  1 and α  2 , the gyroscopic effects generate torques at the pivot of the inverted pendulum that can stabilize the system, as shown in Equation (18). After the inverted pendulum is stabilized in the upright position, PID2 and PID3 bring the gimbal angle back to its zero position and waiting for the next action.
In this simulation, the flywheels spin at a constant speed of 4000 rpm which is controlled independently using speed controllers, and the inverted pendulum is given an initial angle of 5°. The parameters for the outer loop PID are

Linearized Model
Even though a nonlinear model of the system is obtained and verified in the previous section, a linear model around an operating point is still required in order to synthesize the MPC. In common MPC design, a linear model in state-space form is used to predict the system's future behaviour. Compared with the nonlinear model, the linear one is simpler and more efficient in computation. By

Linearized Model
Even though a nonlinear model of the system is obtained and verified in the previous section, a linear model around an operating point is still required in order to synthesize the MPC. In common MPC design, a linear model in state-space form is used to predict the system's future behaviour. Compared with the nonlinear model, the linear one is simpler and more efficient in computation. By linearizing the nonlinear model around an operating point of the system, a continuous time linear model in state-space form can be obtained as: where x is the state vector, y is the outputs, τ is the control inputs, and A, B, C are the coefficient matrices.
In this study, the inverted pendulum is used to verify the controllers, which are designed to stabilize a single-track vehicle by the gyroscopic effect of two spinning flywheels. The operating point of the system is the upright position and the gimbal angles are zero, the flywheels are rotating at a constant speed of 4000 rpm in the opposite direction. Therefore, the linearization operating point for the system is By expanding the equations of motion (17) in the Taylor series for the operating point in the upright position, the numerical results for a linear model are: Since the speed of the flywheels is controlled independently, the four states of . φ 1 , φ 1 , . φ 2 and φ 2 are excluded, and the state variables of the linear model are:

Model Predictive Control
MPC is an optimal control algorithm that takes account of system constraints such as its physical limitations. As shown in Figure 6, MPC uses a discrete time linear model to predict the system's future outputs where x(k) is the state vector, y(k) = θ(k) α 1 (k) α 2 (k) T is the output vector consisting of the system's roll angle and the flywheels' gimbal angle, and τ(k) = τ α1 (k) τ α2 (k) T is the vector of gimbal control torques at the kth step. The discrete state-space matrices, A d , B d , and C d , are easily computed from the continuous linear model (18) using a discrete sampling time T s . The prediction for system states in m steps ahead are calculated by: Based on the predicted states, MPC computes the optimal control sequences that minimize the cost function When the system contains physical limitations, such as limited control torque, MPC accounts for these limitations in the optimization problem using hard constraints In Equation (27), • 2 R denotes the quadratic form of the control torque τ(k + i) with the constant diagonal weighting matrix of control efforts R: τ(k + i) T Rτ(k + i); • 2 Q is the quadratic form of tracking errors with its weighting matrix Q; m is the predictive horizon; and n is the control horizon. In this equation, y re f (k + i) is the vector of reference signals at the prediction step of (k + i). In this study, the reference vector is maintained as a constant, y re f (k), over the prediction horizon, where θ r is the roll angle reference, and α 1r and α 2r are the gimbal angle references. Based on the predicted states, MPC computes the optimal control sequences that minimize the cost function When the system contains physical limitations, such as limited control torque, MPC accounts for these limitations in the optimization problem using hard constraints In Equation (27) where r θ is the roll angle reference, and 1r α and 2r α are the gimbal angle references. In addition to controlling the roll angle θ of a gyroscopic inverted pendulum, MPC also controls the gimbal angles 1 α and 2 α back to zero positions. This ensure that the flywheels generate larger effective torque, as shown in Equation (18). The control problem for this system involves two control inputs and three control outputs. The control performance and the robustness of MPC are affected by the parameters in Equation (27). Putting larger weights on the weighting matrix Q causes the controller to adhere tightly to tracking errors (so the tracking errors are decreased), but it In addition to controlling the roll angle θ of a gyroscopic inverted pendulum, MPC also controls the gimbal angles α 1 and α 2 back to zero positions. This ensure that the flywheels generate larger effective torque, as shown in Equation (18). The control problem for this system involves two control inputs and three control outputs. The control performance and the robustness of MPC are affected by the parameters in Equation (27). Putting larger weights on the weighting matrix Q causes the controller to adhere tightly to tracking errors (so the tracking errors are decreased), but it requires more gimbal torques from the electric motors. Increasing the value of the weighting matrix R gives a higher priority to reducing the control efforts and results in looser tracking performance. The other parameters of MPC are the prediction horizon m and the control horizon n. By choosing a smaller value of m, the controller is more aggressive. However, as point out by Wojsznis et al. [30], a large prediction horizon means that further increases have only a minor effect on control performance.
In the case whereby an external force acts on the system and its magnitude is measureable, the effect of this force on the system's dynamics is predicted by adding a term of measured disturbance into the prediction model. The linear prediction model (24) then becomes where B v is the disturbance parameter matrix and v(k) describes the measured disturbance. Figure 2 demonstrates the acting forces on the pendulum-like bicycle when it goes into a constant-radius turn. The centrifugal force affects the system's dynamics, so the predicted values for future outputs take this into account by using the prediction model in Equation (30). The control scheme for this case is shown in Figure 7, where the centrifugal force acting on the system's centre of mass is given in the form of a measured disturbance, v(k). Appl where v B is the disturbance parameter matrix and (k) v describes the measured disturbance. Figure 2 demonstrates the acting forces on the pendulum-like bicycle when it goes into a constant-radius turn. The centrifugal force affects the system's dynamics, so the predicted values for future outputs take this into account by using the prediction model in Equation (30). The control scheme for this case is shown in Figure 7, where the centrifugal force acting on the system's centre of mass is given in the form of a measured disturbance, (k) v . MPC contributes its advantages of multiple control inputs and multiple control outputs together with online optimization to control the system. However, the main drawback of MPC is its larger computation load for prediction and the online optimization process. Therefore, evaluating the performance of MPC in real-time is very important to guarantee the applicability of the control algorithm in a real-time system.

Control Results and Discussions
In this section, the proposed controllers are embedded in a microcontroller board for the realtime dynamic system. The following section describes the implementation of the proposed MPC and its control performance for some different cases of working conditions.

Real-Time Implementation
In this study, the real-time implementation is conducted using a "real-time simulator", which includes two STM32F407 boards and a RS232-to-USB converter. The advantage of this simulator is that it can be programmed using Matlab/Simulink via its code generation function which allows for rapid prototyping and real-time evaluation of control algorithms. The  MPC contributes its advantages of multiple control inputs and multiple control outputs together with online optimization to control the system. However, the main drawback of MPC is its larger computation load for prediction and the online optimization process. Therefore, evaluating the performance of MPC in real-time is very important to guarantee the applicability of the control algorithm in a real-time system.

Control Results and Discussion
In this section, the proposed controllers are embedded in a microcontroller board for the real-time dynamic system. The following section describes the implementation of the proposed MPC and its control performance for some different cases of working conditions.

Real-Time Implementation
In this study, the real-time implementation is conducted using a "real-time simulator", which includes two STM32F407 boards and a RS232-to-USB converter. The advantage of this simulator is that it can be programmed using Matlab/Simulink via its code generation function which allows for rapid prototyping and real-time evaluation of control algorithms. The ST microelectronic STM42F407VG microcontroller (a product of STMicroelectronics, Geneva, Switzerland) is an embedded board with a 32-bit ARM Cortex-M microprocessor. This microcontroller provides 1024 Kb of ROM (read-only memory), 192 Kb of RAM (random-access memory), and can run at a maximum clock speed of 168 MHz. The dynamic model and the control algorithm are embedded in the boards which were developed in Matlab/Simulink, as descireded above. Figure 8 shows the scheme for the real-time implementation. The nonlinear dynamic model of the gyroscopic inverted pendulum (17) Figure 9 shows the hardware connections of the real-time simulator. This simulator includes two STM43F407 boards and a UART-to-RS232 converter. All of these devices are connected to a 5v DC power supply from a personal computer. STM32F407 board 1 is connected to the other boards using three wires. The purple and blue wires are used to transmit and receive the data via the Tx and Rx pins, respectively, of UART channels. The black wire is connected to the ground on each board.  Figure 9 shows the hardware connections of the real-time simulator. This simulator includes two STM43F407 boards and a UART-to-RS232 converter. All of these devices are connected to a 5v DC power supply from a personal computer. STM32F407 board 1 is connected to the other boards using three wires. The purple and blue wires are used to transmit and receive the data via the Tx and Rx pins, respectively, of UART channels. The black wire is connected to the ground on each board.

Simulation Results
Three case studies are used to evaluate the performance of MPC in three control strategies for a single-track vehicle. The first strategy is to control the vehicle when returning to upright from an  Figure 9 shows the hardware connections of the real-time simulator. This simulator includes two STM43F407 boards and a UART-to-RS232 converter. All of these devices are connected to a 5v DC power supply from a personal computer. STM32F407 board 1 is connected to the other boards using three wires. The purple and blue wires are used to transmit and receive the data via the Tx and Rx pins, respectively, of UART channels. The black wire is connected to the ground on each board.

Simulation Results
Three case studies are used to evaluate the performance of MPC in three control strategies for a single-track vehicle. The first strategy is to control the vehicle when returning to upright from an initial angle and from an external disturbance while moving straight forward. The second is stabilizing the bicycle under a constant centrifugal during a circular motion, and the third is when

Simulation Results
Three case studies are used to evaluate the performance of MPC in three control strategies for a single-track vehicle. The first strategy is to control the vehicle when returning to upright from an initial angle and from an external disturbance while moving straight forward. The second is stabilizing the bicycle under a constant centrifugal during a circular motion, and the third is when the centrifugal force is time-varying due to following a path.

Straight Running and Disturbance Rejection
The first case study uses the inverted pendulum system to evaluate the control performance for returning the vehicle back to upright position from an initial angle and an external disturbance. Initially, the inverted pendulum is tilted at an angle of 10 • and the flywheels spin at a speed of 4000 rpm. The maximum gimbal angle torque that can be generated is 4 Nm, as shown in Table 1.
The control object in this case is to stabilize the inverted pendulum in upright position while maintaining minimum the precession angles α 1 , α 2 to be as small as possible by using a sequence of optimized control toques. To meet this control goal, the ratio between the weighting matrices for tracking errors and the control inputs should be sufficiently large. In order to ensure small tracking errors, a larger ratio is chosen for the weighting matrix Q to R as Further increases in this ratio can cause very aggressive control actions that reduce the control performance. The value of 700 is the weighting on error in θ, and the value of 400 is the weight on the error of the precession angles, α 1 , α 2 . By choosing the values 700 and 400, greater priority is given to minimizing the error in θ than to reducing the gimbal angles. In other words, the MPC prioritizes minimizing the roll angle error first. When this error is relatively small, MPC reduces the gimbal angle errors, α 1 and α 2 , back to zero. In this case, the prediction horizon, m, is chosen as 50. A smaller value of m results in larger steady-state errors and a larger value of m requires higher changing rate in the gimbal angles. Since the control horizon n is related to solving the optimization problem, increasing the control horizon might give better performance. However, the optimization problem then becomes more complicated and causes unfeasible control inputs. After tuning, the value n = 18 gives the best control performance. Figure 10 shows the results for the first case study where the initial condition of the system is: .
Here, the MPC initially generates maximum gimbal torques of 4 Nm to rotate the gimbal angles α 1 and α 2 in opposite directions at the largest changing rates of gimbal angles. By the gyroscopic effects, the control torque in Equation (18) is generated along the inverted pendulum pivot to bring it back to the upright position. When the inverted pendulum approaches to the upright position, the MPC slowly brings the gimbal angles back to zero positions to avoid any unwanted actions of the gyroscopic effect on the inverted pendulum. As shown in Figure 10, the inverted pendulum is stabilized after 2 s. To determine its ability to reject disturbances, an impulse disturbance is applied at 3 s. The applied disturbance is a lateral force of 300 N that acts at the centreof mass b of the inverted pendulum. When the impulse disturbance is applied, the gimbal angles change from 0 to 38 • in order to generate the counteracting momentum and reject the disturbance. At 5.5 s, the pendulum returns to the balanced state and at 6 s, the gimbal angles are at the zero positions. As shown in Figure 10c, the control torques reach the limited values during the stabilization process. However, by incorporating these limitations as hard constraints (28) in the online optimization process, MPC allows good control actions with only small variations in the control torques.
MPC slowly brings the gimbal angles back to zero positions to avoid any unwanted actions of the gyroscopic effect on the inverted pendulum. As shown in Figure 10, the inverted pendulum is stabilized after 2 s. To determine its ability to reject disturbances, an impulse disturbance is applied at 3 s. The applied disturbance is a lateral force of 300 N that acts at the centreof mass b of the inverted pendulum. When the impulse disturbance is applied, the gimbal angles change from 0 to 38° in order to generate the counteracting momentum and reject the disturbance. At 5.5 s, the pendulum returns to the balanced state and at 6 s, the gimbal angles are at the zero positions. As shown in Figure 10c, the control torques reach the limited values during the stabilization process. However, by incorporating these limitations as hard constraints (28) in the online optimization process, MPC allows good control actions with only small variations in the control torques.

Circular Motion
When a bicycle turns into a corner in a curve of constant radius at a particular longitudinal speed, it can be considered to be in circular motion. In this situation, the centrifugal forces that act on the pendulum-like bicycle are shown in Figure 2. The moment equilibrium condition of the system at the contact points is: When riding a bicycle, to stabilize it and turn into a curve, a rider needs to lean his/her bike at a roll angle to the inner side of the corner. Using this roll angle, the gravitational force becomes a counteracting force to the centrifugal force, which prevents the bicycle from being pulled out of its trajectory.
The magnitude of the centrifugal force is calculated as: For each value of centrifugal force, the required roll angle is calculated by applying the equilibrium condition (33): In practice, the centrifugal force can be determined by measuring the lateral acceleration using a sensor or by measuring the instantaneous turning radius for the longitudinal speed via a Global Positioning System (GPS) device. Therefore, it is possible to calculate the centrifugal force and the corresponding reference roll angle r θ using Equations (34) and (36). This information on the turning is used to enhance the controller's performance.
To determine the behaviour of the controller for this case by using the inverted pendulum system with a real-time simulator, the centrifugal force is modelled as a constant force that acts at the centre of mass of the system. For the initial conditions of longitudinal speed of 15 km/h and a turning radius of 5 m, the magnitude of the calculated centrifugal force is 101.01 N and the equilibrium roll angle r θ is 19.51°. The equilibrium roll angle is used as the reference signal for θ and the value of

Circular Motion
When a bicycle turns into a corner in a curve of constant radius at a particular longitudinal speed, it can be considered to be in circular motion. In this situation, the centrifugal forces that act on the pendulum-like bicycle are shown in Figure 2. The moment equilibrium condition of the system at the contact points is: mgh c sin θ = F c h c cos θ.
When riding a bicycle, to stabilize it and turn into a curve, a rider needs to lean his/her bike at a roll angle to the inner side of the corner. Using this roll angle, the gravitational force becomes a counteracting force to the centrifugal force, which prevents the bicycle from being pulled out of its trajectory.
The magnitude of the centrifugal force is calculated as: For each value of centrifugal force, the required roll angle is calculated by applying the equilibrium condition (33): Substituting Equation (34) into Equation (35) gives In practice, the centrifugal force can be determined by measuring the lateral acceleration using a sensor or by measuring the instantaneous turning radius for the longitudinal speed via a Global Positioning System (GPS) device. Therefore, it is possible to calculate the centrifugal force and the corresponding reference roll angle θ r using Equations (34) and (36). This information on the turning is used to enhance the controller's performance.
To determine the behaviour of the controller for this case by using the inverted pendulum system with a real-time simulator, the centrifugal force is modelled as a constant force that acts at the centre of mass of the system. For the initial conditions of longitudinal speed of 15 km/h and a turning radius of 5 m, the magnitude of the calculated centrifugal force is 101.01 N and the equilibrium roll angle θ r is 19.51 • . The equilibrium roll angle is used as the reference signal for θ and the value of F c is fed into the MPC as a measured disturbance as shown in Figure 7.
The inverted pendulum in this case is controlled by a MPC that uses the same prediction and control horizon as the first case. However, to reduce the overshoot in the transient response, weighting matrices that have smaller ratio between Q and R are used:

Path Following
In a path-following task, the motion of a bicycle is usually a combination of running straight ahead, turning left, and turning right with various radii of curvature and at various longitudinal speeds. When following a path, the magnitude of centrifugal force on the bicycle system varies over time, so the bicycle's roll angle must be changed over time to compensate for the centrifugal force.
In this case, the bicycle is assumed to follow an S-shaped path which involves combinations of straight running and turning at the constant radii of curvature of 6 m as shown in Figure 12. The longitudinal speed of the bicycle during the task is maintained at 15 km/h. The control problem for the inverted pendulum in this case is tracking the trajectory of the equilibrium roll angle over the path. In order to implement a strict controller that gives small tracking errors, the MPC uses the parameters that are proposed in Section 4.2.1. This control strategy is performed on the real-time simulator using the same approach with Section 4.2.2.

Path Following
In a path-following task, the motion of a bicycle is usually a combination of running straight ahead, turning left, and turning right with various radii of curvature and at various longitudinal speeds. When following a path, the magnitude of centrifugal force on the bicycle system varies over time, so the bicycle's roll angle must be changed over time to compensate for the centrifugal force.
In this case, the bicycle is assumed to follow an S-shaped path which involves combinations of straight running and turning at the constant radii of curvature of 6 m as shown in Figure 12. The longitudinal speed of the bicycle during the task is maintained at 15 km/h. The control problem for the inverted pendulum in this case is tracking the trajectory of the equilibrium roll angle over the path. In order to implement a strict controller that gives small tracking errors, the MPC uses the parameters that are proposed in Section 4.2.1. This control strategy is performed on the real-time simulator using the same approach with Section 4.2.2. Figure 13 shows the control results of the inverted pendulum for this case. In the first 3 s, the bicycle runs straight ahead and the equilibrium of the system is the upright position. Therefore, θ, α 1 , and α 2 are maintained at zero positions. Thereafter, the vehicle changes direction by turning to the left, so the equilibrium roll angle θ r is −16.40 • . When the bicycle comes out of the corner, at 13 s, it returns to its upright position. At 23 s, the bicycle changes direction again by taking a right turn and the reference signal is changed to 16.40 • . The maximum gimbal angle during the simulation is 6.12 • and the gimbal torques are relatively small. The maximum value is 0.44 Nm. As shown in the control results, the MPC provides good control performance, with a maximum tracking error for θ of 0.51 • .  Figure 13 shows the control results of the inverted pendulum for this case. In the first 3 s, the bicycle runs straight ahead and the equilibrium of the system is the upright position. Therefore, θ , 1 α , and 2 α are maintained at zero positions. Thereafter, the vehicle changes direction by turning to the left, so the equilibrium roll angle r θ is −16.40°. When the bicycle comes out of the corner, at 13 s, it returns to its upright position. At 23 s, the bicycle changes direction again by taking a right turn and the reference signal is changed to 16.40°. The maximum gimbal angle during the simulation is 6.12° and the gimbal torques are relatively small. The maximum value is 0.44 Nm. As shown in the control results, the MPC provides good control performance, with a maximum tracking error for θ of 0.51°.  Figure 13 shows the control results of the inverted pendulum for this case. In the first 3 s, the bicycle runs straight ahead and the equilibrium of the system is the upright position. Therefore, θ , 1 α , and 2 α are maintained at zero positions. Thereafter, the vehicle changes direction by turning to the left, so the equilibrium roll angle r θ is −16.40°. When the bicycle comes out of the corner, at 13 s, it returns to its upright position. At 23 s, the bicycle changes direction again by taking a right turn and the reference signal is changed to 16.40°. The maximum gimbal angle during the simulation is 6.12° and the gimbal torques are relatively small. The maximum value is 0.44 Nm. As shown in the control results, the MPC provides good control performance, with a maximum tracking error for θ of 0.51°.

Conclusions
This study proposes a design for an active stabilizing system for a single-track vehicle. By using the gyroscopic effects of two flywheels, this system can generate control torques to stabilize the vehicle in cases with centrifugal forces during turning. In order to verify the performance when stabilizing the vehicle, a gyroscopic inverted pendulum system is developed. The mathematical model for the inverted pendulum is derived using Lagrange's equation and then is verified by comparing the closed loop response with a model which is constructed using the commercial software ADAMS.
To control the flywheel's gimbals for generating stabilizing torque, a model predictive control algorithm is used to synthesize the controllers. The prediction model for MPC is obtained by linearizing the nonlinear inverted pendum model around its upright position. Three different strategies are proposed to stabilize the vehicle under different working conditions. The performance of these control strategies were verified by applying them to control the gyroscopic inverted pendulum.
In order to evaluate the real-time performance and the feasibility of the proposed controllers, a real-time simulator is proposed. This includes two embedded STM32F407 boards and a UART-to-RS232 converter. The two STM32F407 boards are used to embed the dynamics system and the control algorithm, respectively. The interactions between the dynamic system and the controller, such as control torques and feedback signals, are studied using the UART protocol. By using the simulator, the real-time performance and the feasibility of the control algorithm can be verified without the need for costly and time-consuming manufacturing and practical experiments. The results for the real-time implementation in this study demonstrate the feasibility of embedding the proposed controllers in common hardware.