Dual Mode Control of an Inverted Pendulum: Design, Analysis and Experimental Evaluation

We present an inverted pendulum design using readily available V-slot rail components and 3D printing to construct custom parts. To enable the examination of different pendulum characteristics, we constructed three pendulum poles of different lengths. We implemented a brake mechanism to modify sliding friction resistance and built a paddle that can be attached to the ends of the pendulum poles. A testing rig was also developed to consistently apply disturbances by tapping the pendulum pole, characterizing balancing performance. We perform a comprehensive analysis of the behavior and control of the pendulum. This begins by considering its dynamics, including the nonlinear differential equation that describes the system, its linearization, and its representation in the s-domain. The primary focus of this work is the development of two distinct control modes for the pendulum: a velocity control mode, designed to balance the pendulum while the cart is in motion, and a position control mode, aimed at maintaining the pendulum cart at a specific location. For this, we derived two different state space models: one for implementing the velocity control mode and another for the position control mode. In the position control mode, integral action applied to the cart position ensures that the inverted pendulum remains balanced and maintains its desired position on the rail. For both models, linear observer-based state feedback controllers were implemented. The control laws are designed as linear quadratic regulators (LQR), and the systems are simulated in MATLAB. To actuate the physical pendulum system, a stepper motor was used, and its controller was assembled in a DIN rail panel to simplify the integration of all necessary components. We examined how the optimized performance, achieved with the medium-length pendulum pole, translates to poles of other lengths. Our findings reveal distinct behavioral differences between the control modes.

We present an inverted pendulum design using readily available V-slot rail components and 3D printing to construct custom parts.To enable the examination of different pendulum characteristics, we constructed three pendulum poles of different lengths.We implemented a brake mechanism to modify sliding friction resistance and built a paddle that can be attached to the ends of the pendulum poles.A testing rig was also developed to consistently apply disturbances by tapping the pendulum pole, characterizing balancing performance.We perform a comprehensive analysis of the behavior and control of the pendulum.This begins by considering its dynamics, including the nonlinear differential equation that describes the system, its linearization, and its representation in the s-domain.The primary focus of this work is the development of two distinct control modes for the pendulum: a velocity control mode, designed to balance the pendulum while the cart is in motion, and a position control mode, aimed at maintaining the pendulum cart at a specific location.For this, we derived two different state space models: one for implementing the velocity control mode and another for the position control mode.In the position control mode, integral action applied to the cart position ensures that the inverted pendulum remains balanced and maintains its desired position on the rail.For both models, linear observer-based state feedback controllers were implemented.The control laws are designed as linear quadratic regulators (LQR), and the systems are simulated in MATLAB.To actuate the physical pendulum system, a stepper motor was used, and its controller was assembled in a DIN rail panel to simplify the integration of all necessary components.We examined how the optimized performance, achieved with the medium-length pendulum pole, translates to poles of other lengths.Our findings reveal distinct behavioral differences between the control modes.

Declaration
This paper represents a substantial extension of work originally presented at the 2022 International Conference on System Science and Engineering (ICSSE) [1].The differences with the previous publication are that here we now include the ability to change the physical pendulum's mechanical characteristics, provide a more rigorous system analysis, build a custom testing rig, and improve upon previous system identification and testing procedures.

Overview
An inverted pendulum is a mechanical system comprising a rigid pole, with a pivot at one end that is located on a mobile cart.The challenge of building an inverted pendulum is that, in its inverted upright configuration, it represents a marginally an unstable system.The task is to maintain the system in this inherently unstable upright position, even in the presence of minor disturbances such as a gentle tap.Achieving this balance requires the implementation of a control strategy.The control mechanism must continuously measure the angular displacement of the pendulum from the vertical and correspondingly manipulate the cart's position to counteract any deviations.

Previous work
The inverted pendulum is widely recognized as one of several classical problems in the field of control engineering that is enlightening to study [2].It has been used as a benchmark in robotics and control theory for almost the last 100 years and is often chosen to test and evaluate new control methods [3].This preference arises because pendulum balancing represents behavior ASTESJ ISSN: 2415-6698 relevant to a wide range of theoretical challenges and practical applications [4,5].
One prominent example of these behaviors is the inverted pendulum's manifestation as a simple non-linear dynamic system, characterized by stable and unstable equilibrium points.During the dynamic transition from a downward to an upright position, the pendulum exhibits nonlinearity, primarily arising from how the pendulum angle affects the applied torque due to the pendulum's weight [6].In addition, it represents a system for which it is crucial to achieve stability at the upright position in the presence of disturbances, which can only be achieved by moving the cart appropriately along its rail [7].
James Kerr Roberge was one of the first researchers to describe an inverted pendulum [6].Since then, many inverted pendulum designs and their variants have been constructed and studied, including ones aimed at teaching and research [8,9], mobile designs [10,11], pendulums mounted on drones [12], as well as rotary designs [13,14].
Derivations of the dynamics of inverted pendulums and their simulation have been carried out by many researchers, for example [15].Many different approaches to control have also been investigated.These include PID and classical approaches to control in the s-domain [16,17], state feedback control [1,18], and Lyapunov-based controller design [19], and comparisons have been made between different controllers [20].Machine Learning (ML) approaches are becoming an increasingly successful way to deal with hard control problems.They mark a change from designing controllers based on explicit mathematical models derived from physics to more empirical methodologies that are essentially data driven [21].ML approaches make use of reinforcement learning (RL) based on Q-Learning [22], Policy Iteration [23], and Deep Q-Networks [24].The PILCO RL algorithm is especially data efficient, since it builds and makes use of a probabilistic model of the task dynamics as it learns to balance the pendulum [25].Further ML approaches involve neural networks [26,27] and genetic algorithms [28,29].Hybrid methods using control engineering approaches and neural network techniques have also been investigated [30].Researchers often compare different control approaches [31].More complex twolink inverted pendulums have also been studied by several researchers and implemented using a range of control techniques [32].Other researchers have even investigated the use of reinforcement learning to control a pendulum with three links [33].
The inverted pendulum also forms a basis for understanding simple balancing robots [34][35][36].There is also increasing interest in the construction of legged and humanoid robots [37,38], in which control of balance plays an important role [39][40][41].
Falls in the elderly are a common health issue worldwide and consequently understanding the mechanisms of how humans maintain balance whilst standing is an area of much research [42][43][44][45].The inverted pendulum has also been used to model and understand this process [44][45][46][47][48][49][50][51][52].More recent work has also included the use of experiments with robotic manipulanda to investigate how humans can balance items with their hands [53][54][55][56].
Given the significance of the inverted pendulum in the field of control engineering, inverted pendulum theory finds extensive applications across diverse fields, including robotics, aerospace systems, marine systems, flexible systems, mobile systems, and locomotive systems [57][58][59].The characteristics of the inverted pendulum make it well-suited for modelling a multitude of practical scenarios, highlighting its significance and profound influence across various industries.

Extension of previous work
The current inverted pendulum design expands upon our previous publication [1], in several important ways.We made modifications to the mechanical components of the pendulum system, enabling us to alter its physical characteristics and now utilize a range of pendulum configurations, with changes in pendulum length (635mm, 335mm, 233mm), viscous damping (adding a paddle to the pole), and friction (compression of a brake on the pendulum pole).

Inverted pendulum components
Here we build an inverted pendulum system consisting of a pole pivoted at one end on a cart that moves on a linear track actuated by a stepper motor, which can be balanced in its inverted position by observing the pole angle and controlling cart movement.Our design comprises several distinct component parts, illustrated in Figure 1.
The pendulum assembly is composed of several distinct components.These include a v-groove aluminum profile track and a cart unit that supports the inverted pendulum, moving along the track on a wheeled cart.Additionally, a stepper motor unit propels the cart via a timing belt from one end of the track, while a passive idler pulley supports the belt at the opposite end.The motor and pulley mechanisms are securely affixed to the aluminum profile structure using T-nuts.This design not only offers the flexibility to easily remove and replace these parts with similar components but also simplifies the process of tensioning the drive belt.

Track
The mechanical design integrated a V-slot profile to realize the pendulum track.This streamlined construction since it enabled the use of readily available accessories.These included a stepper motor mounting plate, an idler pulley mechanism, as well as gantry plates.

Cart
A 4-wheeled gantry plate formed the basis of the cart mechanism.During balancing operation, it traversed the V-slot aluminum track along its sides as needed to balance the pendulum pole.Wheel clearances were adjusted so the cart remained securely on the track without excessive wobbling, while also avoiding undue friction.
A thick flat PLA+ 3D-printed rectangular sheet with mounting holes was affixed to the gantry plate.This served as the support for both a ball bearing race and an encoder unit, which held and facilitated the rotation of a shaft.This shaft, in turn, held the pendulum pole, allowing it to swing freely.The incremental encoder measured the pole's angular deviation from the vertical position, as depicted in Figure 2.
Figure 2: 3D-printed pendulum cart incorporating an encoder and an inertial measurement unit (IMU).A flat-topped table can be attached to the end of the pendulum to support objects on its surface.

Shaft friction adjustment
Normally, the rotation of the pendulum shaft is resisted by a low level of friction, arising from the bearing and the incremental encoder.To increase the amount of friction and examine its effect on pendulum behavior, a spring-loaded braking assembly was constructed (Figure 3).This consisted of a semicircular brake pad section made of PLA+ that could be pressed against the pendulum rotary shaft using a compression spring, thereby hindering its rotation.By fully withdrawing the brake, it was also possible to remove its effect completely.

Standard pendulum pole
The standard pendulum pole consists of a pole crafted from a brass segment, selected for its easy machinability and high density.One end of the pole was threaded to securely screw into an attachment component connected to the main shaft, ensuring a sturdy attachment as depicted in Figure 2.This led to an overall pendulum length of 335mm.While a relatively short pole increases the balancing challenge, necessitating quicker cart reactions due to the system's elevated natural frequency, it yields several benefits.A compact pole is not only more manageable but also ensures increased safety by minimizing accidental impact risks.Moreover, it provides characteristics that better match other systems, like smaller balancing robots [60].

Additional pendulum poles
An easy way to alter the fundamental characteristics of the pendulum is to change the length of the pole.To do so, two additional pendulum poles were built (Figure 4).These poles consisted of 8mm diameter stainless steel poles, leading to pendulum lengths of 222mm and 635mm.Since they were only required for intermittent use, no screw attachment was used, thereby facilitating construction.Instead, they were simply clamped at their endpoint into another attachment component connected to the main shaft.

Pendulum pole end attachments
To provide a platform for placing objects, and to shield its endpoint for safety reasons, a round disc was 3D printed from PLA+ and slid onto the end of the pendulum pole, where it was held in place by friction.
To offer a means to change the viscous air resistance experienced by the pendulum pole as it swung, the round disc at the endpoint of the pole could be replaced with a paddle (Figure 5).The paddle consisted of a 5mm thick square measuring 100mm by 100mm and was 3D printed from PLA+.It slid onto the end of the pole via a central mounting hole and was again held in place by friction.By rotating the paddle 90°, it was possible to adjust the amount of viscous resistance the pendulum pole experienced from a low to a high value.
Figure 4: Three different pendulum poles were utilized to evaluate the controller's sensitivity to changes in pendulum length.

Stepper motor actuation
The motor drive assembly includes an aluminum plate, situated on the profile rail, which serves as firm support for a NEMA23 stepper motor.The motor is securely affixed to the plate using bolts.The motor is connected to a drive pulley at its front, and an encoder is mounted on the rear end of its shaft.This enables accurate measurement of the cart's position, although it is only needed to analyze the pendulum's behavior and is not involved in the balancing process (see Figure 6).
To operate the stepper motor, an A4988 stepper controller is employed, driven from an Arduino Mega 2560 R3 Microcontroller.The latter is programmed in C++ and provides precise control of the pendulum cart along the linear rail.

Belt
A pulley and belt mechanism are used to convert the motor's rotary motion into linear movement, thereby appropriately driving the cart along its rail.The cart traverses its designated rails using a GT2 timing belt, which is typically used in 3D printers.The belt, affixed to the cart using steel clamps, spans almost the entire length of the track.The stepper motor, located at one end of the track, has a 60-tooth GT2 motor pulley secured to its shaft.A passive idler pulley is situated at the opposite end of the track.Ball bearings, integrated into the idler pulley, minimize frictional resistance, ensuring smooth operation even under the stress of high belt tension.Adjusting the precise location of the idler provides an easy means to modify belt tension.

Inertial Measurement Unit
To support future developments of the pendulum system, a cost-effective 6-DOF accelerometer/gyro (MPU-6050) was strategically mounted to a 3D-printed support on the pendulum pole, aligning it with the pendulum shaft's rotational axis.This configuration presents an alternative method to measure the pole's angular displacement.The pendulum shaft's rotation revolves around the MPU-6050's y-axis.When in the inverted configuration, its x-axis points downward, and the pole points upwards along its negative x-axis, with its z-axis horizontal (Figure 2).

Modular adjustable pendulum design
The utilization of modular construction within the system ensures that the parameters governing the behavior of the inverted pendulum can easily be adjusted or reconfigured.Such adaptability can prove useful in educational contexts.With minimal adjustments to the apparatus, diverse tasks can be allocated to distinct student cohorts, each tackling a specific control problem.For instance, the pole's length, an essential aspect of the system's dynamics, can be altered by substituting the pole with another of a different length.Adaptability extends further to the motor unit.For example, stepper motor drive could be exchanged with actuation employing a BLDC motor, a modification that would support force control, as opposed to velocity control, of the pendulum system.

3D printing
The components for the pendulum cart were designed using AutoCAD Fusion 360.This software also facilitated the conversion of the designs into STL format files, which is a critical step for additive manufacturing.The mechanical parts were then fabricated using PLA+ material on a Creality 6SE 3D printer.It is noteworthy to mention that although tougher plastics could further enhance the durability of the design, PLA+ was chosen for its ease of printing and cost-effectiveness.

Pendulum Stand
Operating the pendulum necessitates mounting the track at an elevation that ensures unobstructed swinging of the pole.We designed a custom-engineered support stand using aluminum profiles to secure the pendulum system (refer to Figure 7).This stand offers a robust yet lightweight construction that facilitates easy transportation.
The support stand comprises two support pillars, fabricated from aluminum profile.These pillars are anchored at their base with additional lengths of aluminum profile, and 3D printed feet are used at each end to provide stable support.The top of each pillar is fitted with a 3D-printed bracket, tailor-made to accommodate the aluminum v-rail.To enhance the rigidity of the structure and to increase its resistance to mechanical stress, diagonal aluminum profile sections are incorporated, to brace the assembly.This results in a rigid structure, minimizing potential vibrations or displacements that could affect the system's performance.

Testing balancing systems
Monteleone and his team [61] presented a methodology to evaluate the balance resilience of robots, utilizing unique performance indicators and a custom-made testbed.Through extensive testing on a humanoid robot, their study demonstrated the method's effectiveness in designing more robust robotic systems.
Figure 7. Pendulum mounted on its stand: The structure uses diagonal bracing to increase its rigidity.

Tapper components
In the same vein, to conduct tests across various pendulum conditions, including different pendulum lengths, friction, and damping levels, as well as different control laws, and to compare the results, it was necessary to disturb the pendulum pole consistently.To achieve this, a tapping mechanism was constructed (Figure 8).
We built and used a testing rig to deliver repeatable disturbances to the pendulum pole whilst balancing, to examine the recovery and robustness of control.This could be carried out during balancing whilst the cart was either static or moving.

Finger-spring mechanism
The primary component of this tapping mechanism is the 'tapper finger,' which is mounted onto a baseplate.This mounting baseplate for the tapping mechanism is attached to a cart that can be maneuvered up and down a V-groove rail track by means of a stepper motor.
The finger is composed of a stainless-steel pole inserted in a PLA+ holder, which pivots around a rotary axis located 3 cm from its lower end.Two sets of springs are connected at the endpoint of the holder and at the base on either side, pulling in opposite directions.When the finger is in its undisturbed equilibrium position, these springs ensure that it maintains a 0° orientation.This finger-spring assembly forms an underdamped secondorder system.Its behavior, particularly the overshoot following appropriate excitation, serves as an effective method to strike the pendulum pole.To generate a movement suitable for producing a tap, it is necessary to displace the lower end of the finger from its equilibrium position around its pivot and then release it suddenly.This action results in a rapid movement: the finger travels back through its equilibrium position and out the other side, which enables it to impact the pendulum pole and then quickly withdraw.
Using this tapping mechanism, it is important to note that the pendulum pole must be positioned at an appropriate distance from the tapping finger before operation commences, to prevent multiple impacts.At the tap, energy is transferred from the finger to the pendulum pole, and if the distance to the target pendulum pole is set correctly, it ensures that the finger only strikes once and then retreats without making further contact.

Finger actuation
Although it would be possible to manually displace the lower end of the tapping pole and release it by hand, we incorporated an RC servomechanism into the design to achieve this action automatically and more consistently.The RC servo first displaces the finger from its equilibrium position.Then, owing to the cam mechanism's design, it releases the finger suddenly as it passes the end point.This action consequently results in a rapid underdamped second-order trajectory of the end of the tapper finger, ideal for exciting the pendulum pole.
Figure 8. 3D-printed tapping mechanism.Two sets of springs are configured to pull the bottom of the tapping pole to the left and right, thereby establishing a neutral equilibrium position at 0° as depicted.An RC servo is positioned to travel 180°, engaging and then releasing the rear of the tapping mechanism.This action, assisted by the tension of simultaneously contracted springs, causes the pole to swing in an under-damped motion, with overshoot delivering an appropriate tap to the pendulum pole.All custom parts were designed using AutoCAD Fusion 360 and printed with PLA+ material.
To achieve a consistent tap, it is essential to maintain a constant distance between the tapping pole and the pendulum pole and to ensure that the tap occurs at the same location during each trial.This consistency is achieved by visually aligning the tapping finger with the pendulum pole before a tap is initiated.

Tapper cart
In the inverted pendulum position control mode, the pendulum cart remains stationary, simplifying the process of tapping its pole.However, in the velocity control mode, the cart moves along the rail while balancing.The goal was to create a tapping mechanism suitable for both velocity and position modes, necessitating the ability of the tapping mechanism to track the pendulum cart's movement by employing an additional cart.This capability ensures taps can be delivered effectively, even while the pendulum cart is in motion.To achieve necessary synchronization, the tapping mechanism's cart is propelled along a separate V-groove aluminum profile track, using a stepper motor that receives the same control signal as the pendulum cart's stepper motor.
Figure 9. Schematic of the tapping mechanism mounted on its adjustable stand, showing all its main components.

Adjustable height tapper stand
The upper track of the tapper mechanism was mounted to the side of the support pillars, allowing for adjustable height of the tapper, as illustrated in Figures 9 and 10

Mathematical analysis
We performed a comprehensive analysis of the pendulum's dynamics, including the nonlinear differential equation, its linearization, and s-domain representation.This provided a theoretical foundation for our practical implementation.

Equilibrium positions
A pendulum exhibits two distinct equilibrium points.In the stable equilibrium state, the pendulum hangs downward, functioning like a traditional pendulum, similar to those in pendulum clocks.At this stable equilibrium point, if the pendulum is slightly displaced, it will begin to oscillate back and forth with a characteristic frequency determined by its dynamic properties.Factors such as damping in the joints and air resistance lead to a gradual decrease in oscillation amplitude over time.Eventually, the pendulum will stop moving and return to a stationary state at its equilibrium position.In contrast, an unstable equilibrium occurs when the pendulum is delicately balanced upright on its pivot point.

Analysis of non-linear pendulum dynamics
If sliding friction is neglected, the kinematics of an inverted pendulum can be characterized by the following non-linear differential equation: Here, the terms represent the following: Although exponential decay due to viscous resistance is often assumed to be the primary cause of oscillatory decay in secondorder systems like the pendulum, it is known that sliding friction leads to a linear decay of oscillatory amplitude [62][63][64][65].To account for sliding friction, we can also write In this context, an additional friction term exists, scaled by the coefficient f, which is dependent on the sign of the angular velocity.The presence of this sign term complicates formal analysis; therefore, we initially disregard the effects of friction.
We observe that the provided kinematic description suffices for deriving control, assuming reliance solely on the cart's velocity as the control input.Additionally, it's worth noting that force control, a common approach in numerous inverted pendulum implementations [66], would necessitate an extra equation to accurately capture the dynamics of the cart's force.
Refactoring Eqn. ( 1) with the highest-order differential term on the left-hand side, yields: We now write: We will now represent the constant terms using coefficients as follows: This leads to the equation for dynamics: To express the system in state space form as two first-order differential equations, selecting the first state x1 is straightforward since it represents the pendulum angle, denoted as θ: We now write the second state variable x2 as: Re-arranging Eqn.(11) gives: ⇒ ̇1 =  2 +  0   cos  1 (13) Differentiating Eqn.(12) with respect to time and using the product rule to the right-hand side terms Substituting the Equations (12,15) into Eqn.( 8) and replacing angle terms with state variables This leads to the following expression: The two equations ( 13) and ( 19) can be used in a non-linear simulation of the pendulum system.

Equilibrium
We now extend the mathematical analysis to derive the linearized state space model by calculating and evaluating the system's Jacobian around equilibrium positions.To linearize the nonlinear differential equation description of the pendulum around its equilibrium points, we first need to identify their locations.Equilibrium occurs when the control input is zero, and the state derivatives are also zero.That is Since control velocity is zero at the equilibrium points, we see that  2 = 0 and: From Eqn. (22) we see that: Thus, the system has an equilibrium in an inverted configuration at 0 radians and a non-inverted configuration at π radians.To linearize the system at these equilibrium points, we need to calculate the Jacobian of the system, denoted as   , with respect to the system state, and evaluate it at those points.We first express the two state equations as functions: We then calculate the partial derivatives of these two functions with respect to the state variables: 2  2 = − 1 + ( 0 cos  1 +  1  0 sin  1 )  (30)

Jacobian in matrix form
This leads to the Jacobian matrix: We now evaluate this matrix at the equilibria points when control is zero.For the inverted configuration equilibrium at 0 radians, we have For the non-inverted configuration equilibrium at  radians we have We now need to linearize the control of the system.To do so, we calculate the Jacobian of the control, denoted as   , with respect to the control input.This involves calculating the partial derivatives of the two system functions with respect to the control input.
Evaluating this matrix for the equilibrium at 0 and π radians we have The linearized system in state space notation takes the form: From Equations (33,37), we can write the linearized system for the inverted configuration at 0 radians in matrix form as: Since we require the state space model to generate an output corresponding to the pendulum angle θ, its output equation is therefore: 2 ] (42)

Linearized ODE
Multiplying out the matrix Equations (41,42), we see that we have two linear equations.For the first state, we have: For the second state, we have: Substituting back in  1 , ̇1, ̈1 and  2 from Eqn. ( 12)

System eigenvalues and stability
The eigenvalues (λ) of the system matrix A represent the behavior of the pendulum system.These eigenvalues are related to the poles in the transfer function.The eigenvalues, denoted as λ, of matrix  can be determined by solving the following matrix equation, involving the calculation of the determinant, where  is the identity matrix: If all eigenvalues have a negative real part, the system will be stable.Conversely, if any eigenvalue has a positive real part, the system will be unstable.It is also important to note that if the real part of an eigenvalue is zero, then the system is marginally stable, existing on the boundary of stability, neither conclusively stable nor unstable.Complex eigenvalues typically lead to oscillatory behavior, especially if they have a non-zero real part.
To incorporate feedback control into this system, the system must use a feedback mechanism.One approach involves utilizing full state feedback, as depicted in Figure 11.In this figure, the matrix K represents the gain of the state feedback, while R(t) denotes a reference input.If the reference input is zero, the state feedback can be described by the following expression: Substituting the state space system equations ( 39) and ( 40) into this expression leads to the modified state space equations, which represent the system dynamics under the influence of the feedback mechanism.
̇=  +  = ( − ) ( 52) Implementing state feedback alters the system dynamics leading to a new expression for the state derivative.This alteration involves not just multiplying the state by matrix A, but rather by (A−BK).Consequently, the eigenvalues (λ) of the full state feedback system can be determined by solving the updated characteristic equation: Consequently, by modifying the gain matrix K, we can manipulate the location of the system's eigenvalues.The method for calculating K is discussed in Section 7.

Using a Luenberger observer
Many procedures in control design assume that the full state vector is available.However, this is often not the case, as in our pendulum design.In such circumstances, we can use an observer to estimate the full state using a linear plant model.The Luenberger observer computes the state estimate according to the differential equation: The observer uses the state space matrices A and B to provide a linear model of the plant.In our case, we determine the observer gains, denoted as L, using MATLAB.Similar to the state feedback gain, the Luenberger observer gain vector L must be chosen such that all the eigenvalues of the observer system, as solutions to the characteristic equation, possess appropriate negative real values.The signal flow graph for the Luenberger observer is shown in Figure 12.The system's eigenvalues satisfy the following characteristic equation: The calculation of L is discussed in Section 7.
Figure 12.Estimation of plant state using a Luenberger observer.The observer, which simulates the real dynamics of the inverted pendulum, generates an estimated state, denoted as  ̅ .This estimated state serves as a proxy for the actual system state, labeled X, some of which may be unobservable.The signal Y(t) is employed to correct the state estimate.

Adding cart positional state
To enable control of both the cart's position and the balancing of the pole, we introduce an additional state variable x3 to explicitly represent the cart's position.We can relate the cart position to the control velocity input, since: The linearized system dynamics are then represented by a 3x3 matrix, that includes the new positional state variable.The updated matrix equation is: The output equation remains similar to before, but with an appended coefficient of zero in the C matrix: We can compute the numeric values of the matrices using MATLAB.See Figure 13 for the udpated state feedback controller signal flow graph schematic.

Adding integral action
We can further improve cart position performance and reduce its steady-state error by adding integral action on the cart position (see Figure 14).To incorporate integral action, a state is devised within the controller to compute the integral of the positional error signal.This is then used as a feedback term, as denoted by the red path on the schematic.Therefore, to achieve integral feedback, we simply augment a state-space system by adding another state Z, whereby the state Z is the integral of the error between the desired output refp (representing a reference input for cart position) and actual output Y. Thus, the standard state-space equation: Becomes: Where the output is given by: Figure 13.Adding a state for cart position provides a means to control cart position.
State feedback control is now generated from the state X and also from the state Z.That is: Thus, to add integral action to the state-space model of the cart position-augmented pendulum, and use the cart position to generate error integrated over time, we further augment the system matrices given in Eq. (58).We add a fourth state, x4, to represent the integrated cart position error.
Notice that here we update the integral state by selecting the position state x3 to generate the (Y− refp) term used for integral action.For this model, we assume the reference position, refp, is zero.
Figure 14.Illustration of integral error feedback within the system.This mechanism reduces steady-state positional error of the cart by comparing the reference setpoint with the estimated cart position, integrating the positional error, and using it in the feedback path.

Determining feedback gain
In our pendulum design, a linear full state feedback controller is employed to balance the inverted pendulum.This method enables the maintenance of balance, even in the presence of noise and disturbances.Implementing this controller requires obtaining K, the feedback gain vector.
Various strategies can be used to find K.One method is to use pole placement, whereby we calculate K in order to achieve what we consider to be a good choice of poles for the system when it is operating under full state feedback control.Alternatively, the gain K can be found by formulating gain calculation as an optimization problem, where we specify an objective function indicative of what we consider desirable performance should be.In this work, we adopted the latter optimal control approach.Specifically, we find the gain K utilizing the MATLAB lqr command (which designs a linear quadratic regulator).

Velocity control mode
To design an optimal controller to balance the inverted pendulum using velocity as the control input, we need to consider the linear 2 state model given by the equations ( 41) and (42).To build an appropriate cost function for the optimization, suitable values were implemented along the leading diagonal of the 2x2 Q matrix to penalize non-zero system states.In addition, a suitable value is used in the 1x1 R matrix to penalize the control input.
Penalization of the state serves a crucial function: It ensures that the system approaches its target value.Within the scope of this design, it assists in keeping the pendulum's angle close to zero, facilitating effective balancing.In contrast, penalizing control with R serves to reduce the speed of the cart.The penalization values were determined through experimentation.

Position control mode
To implement the control of the cart position as well as balancing the pendulum pole, we make use of the 4-state system that incorporates integral action.The linear state space system is described by equations ( 64) and (65).The diagonal entries of the 4x4 Q matrix, along with the single scalar value in the R matrix, were defined to aptly penalize state and control.The penalization values in Q and R were found by trial and error.To concurrently accomplish pendulum balancing as well as control of the cart position, we applied a larger penalty on state x4 (which represents the integral of positional error), whereas state x3 (which represents cart position) received a penalty term of zero.

Designing the Luenberger observer
To determine the Luenberger gain L, we again employed the MATLAB lqr command.We refrained from using the observer to predict the cart's velocity or position since estimating these is straightforward, given that velocity is directly used as the control signal.
As with the determination of state feedback controller gains, the leading diagonal entries of the 2x2 Q matrix and the single value in the R matrix were selected to penalize the system states and the control action, respectively.Suitable parameter values for these matrices were ascertained through trial and error.

Gain scheduling
Transitioning between velocity control of the pendulum and position control of the pendulum was realized by selecting their respective system gain K and pre-processing term  ̅ (as discussed later and presented in Table 2).We note that resetting the integral error state to zero was necessary each time the controller was switched from velocity to position mode, to ensure processing started with a zero positional error.
In position control mode, we make use of integral action.In this case, the reference position input can have a zero value to preserve the cart's current position on the track.
During the velocity control of the cart, the velocity of the cart is required to track the reference input.To ensure this takes place the controller requires an appropriate feedforward pre-emphasis term, denoted as  ̅ : For velocity control, we note that  ̅ has a value of 1 (that is, a gain of unity).Thus, the reference input directly sets the cart velocity.This is achieved by a slight update to the calculation of the control signal, which now incorporates a non-zero reference input, referred to as 'ref':

System transfer function
Laplace analysis can provide useful insights into system behaviour.Neglecting the non-linear effect of friction, the linearized differential equation that describes the pendulum can be expressed as: Applying the Laplace transform, and assuming initial conditions of zero we have: This leads to the s-domain transfer function relating output pole angle Φ() to cart position   (): We now rearrange terms in the denominator and use the relationship V() =   ().This leads to the expression relating output pole angle Φ() to cart velocity V():

2 nd order canonical form
Comparing the expression with the second-order canonical form, we can identify the coefficients and characteristics of the system.This comparison allows us to further analyze the dynamics of the inverted pendulum and gain deeper insights into its behavior and control requirements.
Here, k represents a simple gain factor.Upon examining the given expression, we find that it allows us to determine the natural frequency of the system as follows: Given that angular frequency (  ) is related to frequency (  ) in cycles per second through the relationship   = 2  we can write the expression: Similarly, by inspection, we can write down an expression for the damping ratio of the system: 2  (82)

Euler integration
To implement real-time state feedback control, some form of numerical integration is needed.Such integration can often be carried out satisfactorily on a digital computer using Euler's methods.Forward Euler integration works by incrementally calculating contributions to the integral that arise from the differential term.
The basic idea is as follows.Consider a function y=f(x) such that when x=x0 then y=y0.This is illustrated in Figure 15.As we increase the value of x by Δx we reach a point where x1=x0+Δx and similarly this increases y by Δy reaching the value y1=y0+Δy.Therefore: The gradient of the curve at (x0, y0) is the tangent at this point.From Figure 15, it is seen that the gradient at this point can be approximated by the ratio of a small change in y divided by a small change in x: This is only strictly true in the limit where Δx tends to zero.In practical numerical methods, this limit is approximated by choosing a sufficiently small Δx.We also see that we can use this relationship to iteratively estimate y1 from y0 by replacing the Δy term by two very close and successive y values: Re-arranging this equation and writing Δx as step size h gives: Writing the x-axis in terms of a time variable t, the gradient is given by:   = (, ) (87) And initial conditions are given by: ( 0 , ) =  0 (88) We then obtain the recurrence relation for step n: Where t is time, at initial time to the output is y0, at future time t(n+1) the output is y(n+1), and h is the step size.This expression can be used to iteratively find the next estimate of y1 if we know xo and the gradient at (x0, y0).This approach provides a method for integrating the differential term, which is generally satisfactory if a sufficiently small temporal step size, h, is used.This method is easily extended to vector form to perform the integration stage needed in state space models.
Figure 15.The gradient dy/dx of a curve y=f(x) can be locally approximated at the point (x0,y0) as the ratio of a small change in the value of y to a corresponding small change in the value of x.

Higher order numerical integration
Euler integration is the simplest fixed-step numerical method that can be adopted.However, other more complex integration rules can also be used.These include the midpoint, trapezoidal, and Runge-Kutta methods, which, though requiring more computational steps in the estimation of the integral, offer higher accuracy.Additional methods utilize dynamic selection of step size, such as the ode45 function in MATLAB.See [67] for a discussion of these methods.
Here, we use MATLAB's ode45 for simulations of the uncontrolled stable pendulum configuration.We use Euler Integration to model the controlled pendulum because of the method's simplicity and its ease of implementation on a microcontroller, especially considering its low computational requirements.

Large angle pendulum oscillatory behavior
Approximately estimating observable parameters of a pendulum, such as length and weight, can be done with relative ease.However, assessing other parameters is considerably more challenging, and in some cases, impossible, solely based on observations of the static mechanical system.To accurately determine values for viscous and sliding friction, it is necessary to conduct measurements during pendulum movement.
To examine the large-angle oscillatory behavior of the pendulum, we raised it from its resting, vertically hanging (noninverted) position to a horizontal alignment, corresponding to an angle of approximately 90°, before releasing it.The pendulum then oscillated until viscous damping and friction gradually brought it to a standstill in its vertical, non-inverted position.

Data logging
To examine the pendulum's oscillation decay over time, we collected time-stamped pole angle data from its shaft encoder as the pendulum swung.In addition, the pendulum cart position was recorded using readings from the encoder mounted on the rear of the cart drive stepper motor.The data were gathered using a program running on an Arduino Mega, which transmitted the time and angular measurements to a host PC equipped with Microsoft Excel.The Excel program was used to record the data at a 25Hz rate and save it to the hard disk in Excel file format.Subsequently, the data were imported into MATLAB for analysis.This allowed for the generation of a plot depicting the pendulum's decaying oscillations under various conditions, as well as further analyses.The mechanical pendulum system features three interchangeable poles, and for each pole, the level of friction could be adjusted from low to high.Similarly, the viscous damping could be altered from low to high by manipulating the wind resistance experienced by the paddle mechanism.This configuration led to a total of 9 different experimental conditions.
Figure 16 top row shows the temporal response waveforms for the undamped cases with no added friction for all three pendulum lengths, plotted on the same scale.It is observed that a longer pendulum length significantly increases the time required for the pendulum angle to decay to zero. Figure 16 middle and lower rows illustrate the responses of pendulums of three different lengths with additional friction and additional viscosity introduced, respectively.It is apparent that incorporating viscosity into the system accentuates the exponential decay.However, it is noteworthy that when friction is the dominant factor, the decay is linear rather than exponential.

Tapper mechanism
Hand tapping

Small angle pendulum oscillatory behavior
The primary interest of this study is the examination of the balancing behavior of the pendulum system in its inverted configuration; therefore, large angle behavior is not of particular relevance.In a balancing configuration, the pendulum pole is maintained close to its unstable equilibrium position by the controller.In this case, the angular deviation from the 0° position is small, which is also essential for the validity of the linear approximation made in the observer model.Therefore, to estimate the parameters of the linear model accurately, it is necessary to examine the pendulum operation at small angles of deflection and to perform system identification for all pendulum parameters under these conditions.To generate consistent excitation to the pendulum, we utilized a mechanical RC servo tapping mechanism.

Evaluating tapper consistency
To evaluate the consistency of the tapping mechanism's operation, we conducted tests on the medium pendulum pole without added friction or viscosity.Figure 17 illustrates that the tapper provides very consistent excitation of the pendulum, particularly when compared to the variability typically observed with manual tapping by hand.

Excitation of non-inverted pendulums
We examined the pendulums in their normal, stable, hangingdown mode to characterize the effects of the tapping.Figure 18 illustrate the responses of pendulums of different lengths driven by the tapper mechanism, both with and without added friction and viscosity.In comparison to the large angle oscillation tests, it is noteworthy that at small angles, the paddle has only a minor effect, and additional friction more rapidly damps out pendulum oscillation.

Estimating pendulum parameters
We performed grey-box system identification of the physical pendulum mechanism to identify parameters of viscous and static friction, and to fine-tune others, including pendulum length, weight, and moment of inertia.
To fit the small angle pendulum response data, we focused on six of the nine configurations: the three pole lengths both with and without added viscosity.This fitting was accomplished with a simulation of its nonlinear dynamics, employing an optimization procedure using the MATLAB fmincon function.We discarded the configurations with extra friction due to the dramatic impact it had on the system's behavior, which resulted in a limited amount of useful temporal data.This procedure optimized the mass, effective pole length, pole moment of inertia, sliding friction, and viscous friction parameters of the pendulum system.
We designed an objective function that minimized the sum of squared distances between the predicted oscillations and the measured data.To align the simulation with the measured data for comparison, we first trimmed the measured data to begin at its first positive peak in the pendulum's oscillation.The pendulum's angular velocity at this point is zero, and its corresponding angle was used to set the initial angular state in the non-linear simulation of the pendulum, based on Eqn.(2), that includes both viscosity and friction.This was carried out using the MATLAB ode45 solve.We initialized the simulation parameters based on direct measurements of pendulum pole length and mass.Initially, we estimated the values of the friction and viscosity parameters through a process of trial and error, which was aided by careful observation of the simulated responses.During the fitting procedure, we allowed the optimization algorithm to refine all parameter values.However, it was necessary to constrain the parameter solutions to prevent fits that deviated substantially from the known ground truth values for mass and pendulum length.To this end, the mass and length were constrained to values between 0.9 and 1.1 times their measured values.The other parameters, for which we had less grounded certainty, were allowed to vary from 0.1 to 10 times their initial estimated values.Figure 19 shows the results of using system identification to fit model parameters to the measured data for the medium-length, low-friction, low-viscosity pendulum condition.The initial guess, which incorporated insufficient damping, is shown in Figure 19 top plot.A reasonably good fit is achieved by fitting the model with only viscous damping, as demonstrated in Figure 19 middle plot.An even better fit is obtained when the model also includes sliding friction, depicted in Figure 19 1ower plot.
For each pendulum length, measured and estimated values were obtained, both with and without friction, leading to a total of six conditions.These conditions are presented in Table 1.The corresponding (no-friction) state space matrices and Luenberger gain L are shown in Table 2.The computed state feedback controller system gains K and reference pre-scaling factor  ̅ , are shown in Table 3.

Reality check using canonical form
To provide a ballpark estimate of the main parameters of the three pendulums in their low-damping modes, each pendulum was first nudged using the tapper mechanism and then allowed to sway freely, eventually settling into its stable position, as depicted in Figure 20.Measured values are shown in Table 4.We used Equations (80 and 81) to calculate the corresponding natural frequencies, which were essentially the same as the damped frequencies due to the very small damping ratio.These values aligned well (within 10%) with those obtained through system identification, confirming the appropriateness of the values found by the fitting procedure.We calculated the damping ratio from the decay to 50% in a time  50 using the equation: From Table 4 it can be seen that the system identification yielded similar values.12. MATLAB SFC controller simulations

Simulating the pendulum
In MATLAB, we simulated the pendulum balancing using both velocity and position controllers.This involved the deployment of a non-linear state space model to simulate the pendulum plant.Additionally, a linear model was implemented for Luenberger observer full state feedback control.
Following initial design of the two inverted pendulum controllers, they underwent iterative tuning and testing within MATLAB simulations.This methodology included assessing the behavior and stability of the inverted pendulum in response to cart movement and simulated impacts to the pole while it was balanced in its inverted position.Simulations carried out in both velocity control and position control modes, also involve modifying the reference input to maneuver the cart velocity or position.

Reference tracking
Simulated results of velocity tracking are shown in Figure 21 left column.The cart nearly achieved the reference velocity using a feedforward velocity command applied directly to it.In this scenario, feedback control of the cart's velocity was not utilized.As a result, the tracking was not entirely accurate; this is partly because the feedback control required for stabilizing the balance tends to counteract the cart's movement.Simulated results of position tracking are presented in Figure 21 right column.Utilizing integral action to correct the cart's position error proved effective for tracking the desired cart position.However, the response to the target location was not immediate, with a noticeable delay before the cart aligned with the desired position.

Recovery from impulsive disturbance
To simulate kick disturbances, we manipulated the state of the pendulum to mimic the effect of an elastic collision with another hard object.This involved setting the pendulum's angular state (x1) to zero and its second state (x2), which comprises an angular velocity component and a control input term, to a small positive value.The results of this simulation are shown in Figure 22.The left column of Figure 22 shows the response of the inverted pendulum to an impulsive disturbance while operating in velocity control mode.It demonstrates a successful recovery to the initial pole deviation from the vertical position.However, it is notable that the cart position shifts and does not return to its initial starting position.
The right column of Figure 22 shows the behavior of the inverted pendulum to the same disturbance while operating in position control mode.Again it can be seen that a good recovery to the initial pole deviation from the vertical orientation is achieved.However, although the cart initially drives away from its initial location, is slowly moves back after a few seconds.

Connections to controller
A DIN rail panel was tailor-made to control the inverted pendulum system.Figures 23 and 24 show the connectors and their corresponding wiring diagrams.The controller interface, located at the top of the panel enclosure, features a female USB-B port.This port connects the Arduino Mega 2560, located inside the controller assembly, to an external computer, which is used for software development and relaying control commands.
The panel features seven female D-connectors.The interfaces are configured to connect with four stepper motors, an I²C device, an SPI device, and two encoders.The use of these D-connectors allows for easy and quick connection of the panel to the inverted pendulum apparatus or other equipment.Special care was taken in the wiring of the plugs for each attached component, and they were configured with a unique connection pattern.This design feature serves to prevent accidental inappropriate connections that could result in electrical damage.The primary focus was on the power pin assignments, ensuring their isolation from other signal inputs and outputs.This safeguard ensures that potential connection errors will not result in component damage.

Panel internal layout
The controller panel's internal layout comprises three specific DIN rails, as depicted in Figure 25, which shows a photograph of the assembled unit.It consists of a microcontroller rail, a rail for motor drivers and power converters, and a power supply rail.Additionally, wiring conduit was strategically placed to manage the cabling in a tidy manner.This arrangement not only enhanced the orderly appearance but also reduced the risk of unintended cable contact with other components or causing interference.In the selection of panel components, preference was given to components equipped with rear mounts for DIN rail attachment.For other components, custom 3D printed support structures were made and fitted with clips to attach them to the DIN rails.The power rail within the controller panel was compartmentalized into three principal sections: 1.An AC circuit breaker section that is responsible for regulating overcurrent conditions and interrupting the main supply.
2. A region featuring a PULS Dimension DIN rail power supply, which delivers 24 volts at 5A, and meets the voltage and current prerequisites of the system.
3. A region containing three discrete DC circuit breakers, to permit individual disconnection of each control component.This feature provides additional protection against potential damage due to short circuits.

Stepper motor drivers
The power converter and motor driver rails were engineered to facilitate the operation of up to four stepper motors, each capable of being directly interfaced with the control panel's motor driver rail.The motor driver rail featured two 3D-printed carriers, each housing a pair of A4988 stepper motor drivers.These motor drivers were powered by a 24-volt supply operating on mains power.The A4988 driver offers eight distinct micro-stepping resolutions, providing flexibility in stepper motor control.For this project, we employed a one-fourth step resolution for all motors.To realize the one-fourth step resolution setting on the expansion board, the DIL switches were configured appropriately.The A4988 driver can operate within a voltage range of 8V to 35V and can deliver a current ranging from 1.5A to 2.2A.A potentiometer is incorporated into the driver breakout board, enabling hands-on fine-tuning of the current supplied to the stepper motor.To determine the current limit, Ilim, it's essential to gauge the reference voltage (Vref) on the potentiometer and apply the given formula to compute its desired value: This facilitates precise control over the motor current, optimizing performance and efficiency.Our adjustment of the current limit was a critical step to ensure the proper functioning of our NEMA23 stepper motors.A current limit of 1.5A was determined to be ideal for this specific application.Exceeding this current threshold may damage both the motors and the drivers.Conversely, setting the current below 1.5A could compromise the motors' operation, raising the likelihood of stalling.Thus, appropriate calibration is paramount to ensure good performance while safeguarding the components from potential harm.To prevent overheating of the motor drivers, the incorporation of a cooling solution was essential.A pair of compact DC axial fans were positioned above them to prevent thermal damage to the chips.These fans required a supply voltage of 12V, which was furnished through a Buck converter operating from the 24V power line (refer to Figure 26).This setup ensured that the motor drivers stayed at a safe temperature during operation, enhancing both their performance and longevity.
At the heart of the controller panel, on the microcontroller rail, the Arduino Mega 2560 is prominently featured.Selected for its robust I/O capabilities, it offers 54 digital input/output pins, including 15 suitable for PWM, 256KB of flash memory, and a clock speed of 16MHz (refer to Figures 27 and 28).The Arduino Mega facilitates seamless communication with the host PC, aligning perfectly with the project's requirements.Arduino software overview Control over the pendulum was overseen by the Arduino Mega, which was employed to implement a state feedback controller function within its primary polling loop.During the polling operation, the control process begins by reading the encoder to ascertain the pendulum pole's angle relative to the vertical.For the state feedback controller to operate, it required the pendulum system's full state.Since only the angle was directly available, the second state was estimated using a Luenberger observer.Using the full state estimate, the control command was generated by multiplying it with the specified feedback gain.Based on the measured angle, the feedback controller then calculated the stepper motor velocity control signal.This signal produced an output pulse train, driving the stepper motor and allowing the cart to move at the ideal speed to maintain balance.State updates were computed utilizing Euler integration.

Arduino command menu
Within the polling cycle, the system processes and interprets incoming commands received through the serial interface.The suite of accessible commands encompasses the following: • Activate control: Starts balancing when the pendulum is brought up to an inverted configuration.
• Display help menu: View controller parameters.

Main Arduino loop pseudocode
The pseudocode for the main Arduino poll loop is shown below.This makes use of function calls the can reset the encoder, calculate the motor command, and drive the stepper motor.The loop is continuously run to control the system, ensuring that the pendulum maintains its desired position or follows a certain trajectory.In addition, there are command responses from calls to the menu system so that the program can be operated from a serial monitor over a USB connection.

Online demonstration videos
Viewers can watch the inverted pendulum operations, including various tests, on the YouTube channel 'Robotics, Control and Machine Learning'.All related videos are grouped under the 'ASTESJ Inverted Pendulum' playlist.Please follow the provided link for direct access to these videos: https://youtu.be/pvF0Zhs501U?si=P7vknbwL11tvBksE

Perturbation tests
We use a straightforward approach to assess control law performance by simultaneously monitoring the cart's position and the pendulum's angle during minor system disturbances.We obtain these measurements using encoders on the cart's stepper motor and at the pendulum's axis for angle measurement.During the balance test, disturbances are introduced by systematically applying an impulse to the pendulum using a tapping mechanism.
Experiments were conducted in both position and velocity control modes, varying the pole length from shorter to longer dimensions.These tests demonstrated the system's ability to maintain stability, even when subjected to additional loads altering its dynamic characteristics.Video demonstrations of these experiments can be found on YouTube, as per the link provided above.

Position mode results
Figure 29 shows the results of the test conducted in position control mode.The pendulum was initially stabilized and held stationary in a balanced position.Following the disturbance, immediate and noticeable changes occurred in both the pendulum angle and the cart's position.The pendulum angle plot showed minor fluctuations around zero.The motor encoder data revealed that the cart moved quickly to restore balance in the system and then gradually returned to its original position.This behavior, referring to the cart's movement and pendulum stabilization, is also evident in the YouTube videos.
During tests with the long-length pole, we observed a small oscillation of the cart, even in the absence of disturbance.This oscillation likely stems from a significant mismatch between the long-length pole's parameters and those of the medium-length pole, for which the controller was originally designed.Based on these observations, modifying the control law appears necessary to effectively manage the pendulum's behavior with its increased length.

Velocity mode results
The pendulum's performance was closely examined while operating under velocity control, as illustrated in Figure 30.The velocity control operation was initiated via the keyboard on the main PC.Users could select a cart velocity, resulting in the cart moving as specified in both left and right directions.
To further evaluate the system's resilience against knocks, representing impulsive disturbances, we conducted an additional test.In this test, the pole was gently tapped while the velocity was set to zero.In all instances, the pendulum system demonstrated notable stability and effectiveness in mitigating the disturbance.Compared to the position control mode, disturbances in the velocity control mode led to uncompensated cart movements, particularly for the short pendulum, as shown in the lowest row of Figure 30.Again, this behavior is also apparent in the YouTube videos.This is also worth noting that using a longer pole again resulted in a modest reduction in performance in velocity control mode, with some cart oscillations observed after the impulsive disturbance.However, this effect was less pronounced than in position control mode.

Summary
In this study, we demonstrated the design, implementation, analysis, simulation, and testing of an inverted pendulum.The mechanical system was built utilizing V-slot rail components and custom 3D printed parts.
Novel features of this work included: 1.The construction of a physical pendulum in which the pole length, viscosity, and resistive friction could be easily modified.
2. The construction of a testing rig, designed to apply consistent taps to the pendulum pole, to evaluate its reaction to impulsive disturbances.3. Use of system identification to investigate and quantify the pendulum's uncontrolled dynamics as the physical characteristics of the pendulum system were changed.4. The design of two linear controllers, based on observerbased full state feedback control modes, supporting either velocity or position control of the pendulum cart while balancing the pendulum pole. 5. Performance testing to investigate the pendulum's controlled dynamics as its physical characteristics were changed.

Uncontrolled pendulum oscillations
We first investigated the behavior of the pendulum in its stable downward inverted configurations.This was done for all three test pendulum pole lengths, as well as under conditions of both high and low static friction and high and low viscous damping.We examined the pendulum's free oscillations following an initial large angle displacement of approximately 90°, and also after initial small angle displacements of about 5°, caused by taps from the tapping mechanism.As expected, increasing the pole length reduced the oscillatory frequency of the pendulum.
Increasing viscosity using the paddle mechanism significantly reduced the decay time of oscillations in the large angle case.In this scenario, the added viscous resistance dominated the pendulum's oscillatory decay, resulting in an exponential reduction in amplitude over time.However, in the small angle condition, where static sliding friction was a significant source of decay, the paddle had minimal effect.This was evidenced by a more linear decay of oscillatory amplitude.
When we increased static friction equally in both the large and small angle cases, the effects differed.In the large angle case, this increase led to a noticeable, albeit modestly more linear, decay of oscillations.Conversely, in the small angle condition, the same level of friction had a dramatic effect, rapidly decelerating oscillations and bringing them to a standstill within just a few cycles.
These observations indicate that the viscous resistance from the paddle is better represented by the square of the movement velocity than by the linear model commonly used in mathematical modeling.This is particularly true since the paddle's effect is significant only during faster movements.Furthermore, at small amplitudes, where the effect of gravity acting on the pole produces minimal torque, any substantial static frictional resistance can dominate the damping behavior.

System identification
To estimate the pendulums' parameters, we applied a system identification procedure to the small angle dataset.This data best represents the small angle condition occurring during the balancing of the inverted pendulum.We used optimization to fit the predicted pendulum damped oscillatory decay waveform with data recorded from the pendulum in different configurations.We noted that including a friction term in the mathematical model of the non-inverted pendulum was necessary in this process.This addition accounts for the linear aspect of decay and achieves a good fit.The fitting procedure enabled the estimation of the viscous and static friction terms, as well as an updated estimate of the effective pendulum pole length, mass, and moment of inertia.

Controlled pendulum results
We undertook a sequence of system tests, starting with the standard pendulum pole length for which the controllers were developed.We then investigated how the stabilized pendulum pole responded to light taps from the tapper mechanism, creating impulses.This testing was carried out in both velocity and position control modes.In velocity mode, the cart could be driven with a feedforward velocity command to move left or right while maintaining balance.In position control mode, which operates with integral action on the cart's position, the control system maintains the pendulum's cart at a specified location.We observed distinct behavioral differences between the two control modes.
Unsurprisingly, velocity control, unconcerned with cart position, responded to disturbances to the pendulum pole with balancing movements of the cart, typically causing a positional shift.In position control mode, a disturbance similarly resulted in balancing movement, but the cart gradually returned to its initial position.
Since the cart's movement velocity is limited, any disturbance requiring faster movement would naturally result in a loss of balance.This limitation also affects the balancing robustness in velocity control mode.If the cart is already moving in one direction, its capacity for additional corrective velocity in that direction is restricted.

Transfer of controller operation to other pole lengths
To assess controller performance, we conducted balancing system tests using both shorter and longer pendulum pole lengths, comparing them to the standard length for which the controllers were developed.We found that the controllers operated well with the shorter length pendulum pole.However, with the longer pendulum pole, we observed some oscillatory behavior of the cart, particularly in position control mode.Despite this, the inverted pendulum balance was still maintained.
We note that the gains for both controller modes, derived from the Linear Quadratic Regulator (LQR) design process, were based solely on experimentation with the standard pendulum.Naturally, there remains a strong likelihood that more optimal controllers for both modes could exist, particularly if they were specifically designed for these varying pendulum lengths.

16.6.
Future work In the current study, we examined the effects of a relatively low-intensity, fixed impulsive disturbance on pendulums using a tapper mechanism.We utilized this setup to assess how the pendulums responded as their characteristics were altered and to observe the behaviors of velocity and position control.These tests did not result in a loss of balance; rather, they only evaluated the reactions necessary to maintain equilibrium.It would be enlightening to apply a wider range of impulse intensities and compare the behaviors related to loss of balance across the various conditions and controllers examined in this study.The existing tapper mechanism could not be easily adjusted to provide a range of impulse intensities.For future research, constructing a tapper device that employs a motor to drive the tapper rod would be a valuable exercise, allowing for precise control over the impulse intensity.
Currently, we have examined the behavior of two different state feedback controller architectures for balancing a pendulum.Many other control approaches exist, and a comparison with methods such as PID (Proportional-Integral-Derivative) [16,17], and reinforcement learning [22][23][24], would be informative.
The inverted pendulum has been valuable in understanding human balance while standing [44][45][46][47][48][49][50][51][52].Future studies within the framework of our pendulum system could further explore and model human behavior in such tasks.These studies could investigate factors that constrain human performance, including sensory feedback latency, noise in the control and sensory systems, as well as the force, stiffness, and speed of movement characteristics of muscles [68].Such issues could be readily incorporated into the MATLAB simulations as well as real-time control of the physical pendulum system.

Dual
Mode Control of an Inverted Pendulum: Design, Analysis and Experimental Evaluation Laura Álvarez-Hidalgo, Ian S.Howard * School of Engineering, Computing & Mathematics, University of Plymouth, Plymouth, PL4 8AA UK A R T I C L E I N F O A B S T R A C T Article history: Received: 14 November, 2023 Accepted: 13 December, 2023 Online: 30 December, 2023

Figure 3 :
Figure 3: Shaft friction adjustment mechanism for the pendulum cart, designed to alter the sliding friction around the pendulum's rotational axis.

Figure 5 :
Figure 5: The pendulum paddle can be rotated, thus adjusting the viscous drag due to air resistance from low to high values.

Figure 6 :
Figure 6: Stepper motor actuation, showing the drive pulley and a custom-made 3D-printed encoder mount at the motor's rear. .

Figure 10 .
Figure 10.Side view of the adjustable mechanical tapper assembly.The cart supporting the tapping mechanism can be driven left and right to synchronize with the pendulum cart.The cart is mounted on a rail that can be slid up and down the outer stand legs, and then fastened firmly in place with screws, enabling adjustment of the height at which tapping occurs.
θ: Angle of the pendulum pole to the vertical axis μ: Coefficient of viscosity m: Mass of the pendulum I: The Moment of Inertia (MoI) of the pendulum pole about its center of mass l: Distance from the pivot point to the pendulum pole's center of mass (typically half the length of the pole) xp: Displacement of the pivot

Figure 11 .
Figure 11.Signal flow graph of a plant under direct full-state feedback control: The red line delineates the feedback path, which includes multiplication by the feedback gain, denoted by K. Additionally, a feedforward gain term, represented by  ̅ , is introduced to improve tracking of the reference input.

Figure 16 .
Figure 16.Pendulum large angle oscillation decay over time for three pendulum lengths.Data captured using an incremental encoder.Top row: No added viscosity or friction for short, medium, and long pole lengths.Middle row: Effect of added friction for short, medium, and long pole lengths (SF, MF, and LF, respectively).Lower row: Effect of added viscosity for short, medium, and long pole lengths (SV, MV, and LV, respectively).

Figure 17 .
Figure 17.Testing the consistency of the tapping mechanism.Mean and standard deviation of the pendulum angular response averaged over 8 trials are shown using the tapper mechanism and hand excitations of the pendulum pole.

Figure 18 :
Figure 18: Pendulum small angle oscillation decay over time.Top row: No added viscosity or friction.Middle row: Effect of added friction for short, medium, and long pole lengths (SF, MF, and LF, respectively).Lower row: Effect of added viscosity for short, medium, and long pole lengths (SV, MV, and LV, respectively).

Figure 19 .
Figure 19.Running optimization to fit the measured response of the mediumlength non-inverted pendulum without additional viscosity or friction.Top plot shows the predicted response based on an initial rough guess.Middle plot shows the estimated response after running the optimization algorithm without including the friction term.Lower plot shows the estimated response when the friction term is present.It is evident that accounting for friction leads to a significantly better fit.

Figure 20 .
Figure 20.Approximate estimation of the canonical parameters for the pendulum system by observing the frequency of oscillation and the amplitude decay to 50% of the initial value.Plots are shown here for the short, medium, and long-length pendulums (with no extra damping), respectively.

Figure 21 .
Figure 21.The pendulum angle and cart position are depicted in response to the cart movement, driven by changes in the cart position reference setpoint.Left column: MATLAB simulation of the pendulum with velocity control.The pendulum angle and cart position are shown in response to moving the cart, driven by changes in the velocity reference input.Right column: MATLAB simulation of the pendulum under position control of the cart with integral action on cart positional error.

Figure 22 .
Figure 22.The pendulum angle and cart position are depicted in response to a simulated tap.Left column: MATLAB simulation of the pendulum with velocity control.The pendulum angle and cart position are shown in response to a 40 deg/s initial velocity disturbance.Right column: MATLAB simulation of the pendulum under position control of the cart, with integral action on cart positional error.

Figure 23 .
Figure 23.View of the actual controller panel cover, which was designed in Autodesk Fusion 360 and then 3D printed.

Figure 24 .
Figure 24.Rear view of soldered D-Sub connections on the male plugs (left-hand column) and the female sockets (right-hand column) mounted on the panel.The top row shows the Inter-Integrated Circuit (I²C) pinout, the second row is for Serial Peripheral Interface (SPI), the third row is dedicated to stepper motors, and the bottom row is configured for encoders 13.3.Panel DIN rail components

Figure 25 .
Figure 25.View displaying the internal layout of the controller panel, which is partitioned into distinct sections for power management, motor control, and microcontroller functions.

Figure 26 .
Figure 26.DIN Rail holder for the A4988 Driver Module.This setup mounts two stepper motor controller breakout boards onto a DIN rail.Notably, it includes a cooling fan to ensure the controllers remain at optimal temperatures and prevent overheating.

Figure 27 .
Figure 27.Pinouts for the Arduino Mega 2560.The connections are configured to control up to three stepper motors and communicate with peripherals via the I²C and SPI data buses.

Figure 28 .
Figure 28.Arduino Mega 2560 pinout connections used for reading the system's two encoders.
Poll loop Result: Balances pendulum on track Initialization of SFC parameters and flags while program running do Call the menu object for input commands, act accordingly Read time Read pendulum pole angle Read reference value Call SFC function to compute control u Generate stepper control pulses to Drive stepper motor end 14.4.Pseudocode to implement SFCThe state feedback controller is implemented as a C++ class.Its constructor sets up the parameters for the state space model, as well as the SFC gain K and the Luenberger gain L. A SFC function is called with the current time and the measured pendulum pole position.It returns the control value U, which is subsequently used to set the rotational velocity of the stepper motor and drive the pendulum cart.State Feedback ControllerResult: state feedback control variable u Initialization state space matrices A, B, C Initialization SFC gain K Initialization Luenberger gain L Initialization state estimate;  ̂ = [0; 0; 0; 0]; while balancing pendulum do Read reference value ref Read pendulum output angle y Calculate time step: h.= time -lastTime Update last time: lastTime = time Calculate control: u = -K ̂ + ref *  ̅ Calculate Output prediction error: yErr = y -C ̂ Calculate 1 st pendulum state derivative:  .

Figure 29 .
Figure 29.Responses of real, physically position-controlled inverted pendulums (using integral action on cart position) to impulsive disturbances delivered by the tapping mechanism.Results are for all three pendulum lengths in their low damping configurations.The solid blue line represents the mean response averaged across eight aligned recordings, and the light blue shading indicates the corresponding standard deviation.

Figure 30 .
Figure 30.Responses of real, physically velocity-controlled inverted pendulums to impulsive disturbances delivered by the tapping mechanism.Results are for all three pendulum lengths in their low damping configurations.The solid blue line represents the mean response averaged across eight aligned recordings, and the light blue shading indicates the corresponding standard deviation.

Table 1 .
Physical Measurements of the three different pendulums and estimated values found by system identification.Values marked with 'F' represent estimates with friction included in the second-order nonlinear differential equation model of the pendulum.The bold values represent estimates made when only a viscous damping term is present.

Table 2 .
Values of the state-space matrix and Luenberger observer gain, presented in MATLAB syntax.

Table 3
. Computed state feedback control K gains and  ̅ values used for the two control mode (in MATLAB syntax).

Table 4 .
Measured decay and nearest integer of cycles as a function of time for all three pendulum lengths in undamped conditions.The values in brackets were found by the system identification procedure.