# A & B. Modeling and Balance Control

## Objective

The objectives of this laboratory experiment are as follows:

1. Obtain the linear state-space representation of the rotary pendulum system.
2. Design a controller that balances the pendulum in its upright position using **Pole Placement**.
3. Simulate the closed-loop system to ensure the given specifications are met.
4. Implement the balance controller on the Quanser Rotary Pendulum system and evaluate its performance.

## Equipment

* [ ] Rotary pendulum (Quanser Rotary inverted pendulum module)
* [ ] Rotary servo base (Quanser SRV02)
* [ ] Power amplifier (Quanser VoltPaq-X2)
* [ ] DAQ (Quanser Q2-USB)
* [ ] MATLAB and SIMULINK

## A. Modeling

This experiment involves modeling of the rotary inverted pendulum.

### Rotary Inverted Pendulum Model

A picture of the rotary servo base with rotary pendulum module is shown in Fig 1. The numbered components in Fig. 1 are listed in Table 1 along with the numerical values of the system parameters in Table 2.

![Figure 1 Rotary servo base with Rotary Pendulum module](https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2FltCj3u7tMYr4IUq6exwd%2Frotary_setup.png?alt=media\&token=5369625b-241c-4853-b7c0-e269b2400181)

#### Table 1 Rotary Pendulum components (Figure 1)

<table><thead><tr><th width="111.74033149171265" align="center">ID#</th><th width="271.2596685082874">Component</th></tr></thead><tbody><tr><td align="center">1</td><td>Rotary Servo</td></tr><tr><td align="center">2</td><td>Thumbscrews</td></tr><tr><td align="center">3</td><td>Rotary Arm</td></tr><tr><td align="center">4</td><td>Shaft Housing</td></tr><tr><td align="center">5</td><td>Shaft</td></tr><tr><td align="center">6</td><td>Pendulum T-Fitting</td></tr><tr><td align="center">7</td><td>Pendulum Link</td></tr><tr><td align="center">8</td><td>Pendulum Encoder Connector</td></tr><tr><td align="center">9</td><td>Pendulum Encoder</td></tr></tbody></table>

#### Table 2 Main Parameters associated with the Rotary Pendulum module

<table><thead><tr><th width="116">Symbol</th><th width="287">Description</th><th width="136">Value</th><th width="257">Unit</th></tr></thead><tbody><tr><td><span class="math">m_\rm{p}</span></td><td>Mass of pendulum</td><td>0.127</td><td><span class="math">\mathrm{kg}</span>​</td></tr><tr><td><span class="math">L_\rm{p}</span>​</td><td>Total length of pendulum</td><td>0.337</td><td><span class="math">\rm{m}</span></td></tr><tr><td><span class="math">l_\rm{p}</span>​</td><td>Distance from pivot to center of mass</td><td>0.156</td><td><span class="math">\rm{m}</span></td></tr><tr><td><span class="math">J_\rm{p,cm}</span>​</td><td>Pendulum moment of intertia about center of mass</td><td>0.0012</td><td><span class="math">\rm{kg \cdot m^2}</span></td></tr><tr><td><span class="math">B_\rm{p}</span></td><td>Pendulum viscous damping coeffi­cient as seen at the pivot axis</td><td>0.0024</td><td><span class="math">\rm{N\cdot m\cdot s/rad}</span></td></tr><tr><td><span class="math">m_\rm{arm}</span>​</td><td>Mass of rotary arm with two thumb screws</td><td>0.257</td><td><span class="math">\rm{kg}</span>​</td></tr><tr><td><span class="math">L_\rm{r}</span></td><td>Rotary arm length from pivot to tip</td><td>0.216</td><td><span class="math">\rm{m}</span>​</td></tr><tr><td><span class="math">l_\rm{arm}</span>​</td><td>Rotary arm length from pivot to center of mass</td><td>0.0619</td><td><span class="math">\rm{m}</span></td></tr><tr><td><span class="math">J_\rm{arm,cm}</span>​</td><td>Rotary arm moment of inertia about its center of mass</td><td>9.98 x 10^-4</td><td><span class="math">\rm{kg \cdot m^2}</span>​</td></tr><tr><td><span class="math">B_\rm{r}</span>​</td><td>Rotary arm viscous damping coeffi­cient as seen at the pivot axis</td><td>0.0024</td><td><span class="math">\rm{N\cdot m\cdot s/rad}</span></td></tr><tr><td><span class="math">J_\rm{arm}</span>​</td><td>Rotary arm moment of inertia about pivot</td><td>0.0020</td><td><span class="math">\rm{kg\cdot m^2}</span></td></tr><tr><td><span class="math">K_\rm{enc}</span>​</td><td>Pendulum encoder resolution</td><td>4096</td><td><span class="math">\rm{counts/rev}</span>​</td></tr></tbody></table>

### Model Convention

A simplified form of the inverted pendulum system used in the development of the mathematical model is shown in Figure 2. The rotary arm pivot is attached to the Rotary Servo system. The arm has a length of $$L\_\rm{r}$$, a moment of inertia of $$J\_\rm{r}$$, and its angle, $$\bm\theta$$, increases positively when it rotates counterclockwise (CCW). The servo (and thus the arm) should turn in the CCW direction when the control voltage is positive, i.e. $$V\_\rm{m}$$ > 0.

The pendulum link is connected to the end of the rotary arm. It has a total length of $$L\_p$$ and its center of mass is at $${L\_\rm{p}}/{2}$$ . The moment of inertia about its center of mass is $$J\_\rm{p}$$. The inverted pendulum angle, $$\bm\alpha$$, is zero when it is perfectly upright in the vertical position and increases positively when rotated CCW.

![Figure 2 Rotary inverted pendulum conventions](https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2FMrq2E0rVzDVlR0mOmhHt%2Frotary_convention.png?alt=media\&token=9246afb1-356a-4919-b493-96bce35c64e1)

### Nonlinear Equations of Motion

Instead of using classical (Newtonian) mechanics, the **Lagrange method** is used to find the equations of motion of the system. This systematic method is often used for more complicated systems such as robot manipulators with multiple joints.&#x20;

Specifically, the equations that describe the motions of the rotary arm and the pendulum with respect to the servo motor voltage, i.e., the dynamics, are obtained using the **Euler-Lagrange** equation:

$$
\frac{d}{dt}\frac{\partial L}{\partial \dot{q\_i}} - \frac{\partial L}{\partial q\_i} = Q\_i \qquad \qquad \tag{1}
$$

The variables $$q\_i$$'s are called *generalized coordinates*. $$Q\_i$$'s are called *generalised force* and $$L$$ is the *Langrangian* (difference between Kinetic and Potential energies of the system).  For this system, let

$$
q(t) =\begin{bmatrix} \theta(t) & \alpha(t) \end{bmatrix}^T \qquad \qquad \tag{2}
$$

where, as shown in Figure 2, $$\theta(t)$$ is the rotary arm angle and $$\alpha(t)$$ is the inverted pendulum angle. The corresponding angular rates are

$$
\dot{q}(t)=\begin{bmatrix} \displaystyle \frac{d\theta(t)}{dt} & \displaystyle\frac{d\alpha(t)}{dt} \end{bmatrix} ^T \qquad \qquad \tag{3}
$$

With the generalized coordinates defined, the Eule&#x72;**-**&#x4C;agrange equations for the rotary pendulum system are

$$
\frac{d}{dt} \frac{\partial L}{\partial \dot{\theta}} - \frac{\partial L}{\partial \theta} = Q\_1 \qquad \qquad \tag{4a}
$$

$$
\frac{d}{dt}\frac{\partial L}{\partial \dot{\alpha}} - \frac{\partial L}{\partial \alpha} = Q\_2 \qquad \qquad \tag{4b}
$$

The **Lagrangian** of the system is described by

$$
L = T - V \qquad \qquad \tag{5}
$$

where $$T$$ is the total kinetic energy of the system and $$V$$ is the total potential energy of the system. Thus the **Lagrangian** is the difference between a system’s kinetic and potential energies.&#x20;

The generalized forces $$Q\_i$$ are used to describe the nonconservative forces (e.g. friction) applied to a system with respect to the generalized coordinates. In this case, the generalized force acting on the rotary arm is

$$
Q\_1 = \tau - B\_\mathrm{r}\dot{\theta} \qquad \qquad \tag{6a}
$$

and acting on the pendulum is

$$
Q\_2 = -B\_\mathrm{p}\dot{\alpha} \qquad \qquad\tag{6b}
$$

​See [Table A](#table-a-main-rotary-servo-base-unit-specifications) in the Appendix for a description of the corresponding Rotary Servo parameters (e.g., such as the back-emf constant, $$k\_m$$$$k\_\rm{m}$$). Our **control variable** is **the input servo motor voltage**, $$V\_m$$$$V\_\rm{m}$$. Opposing the applied torque is the viscous friction torque, or viscous damping, corresponding to the term $$B\_\mathrm{r}$$. Since the pendulum is not actuated, the only force acting on the link is the damping. The viscous damping coefficient of the pendulum is denoted by $$B\_\mathrm{p}$$.&#x20;

Once expressions for the kinetic and potential energy are obtained and the Lagrangian is found, then the task is to compute various derivatives to get the EOMs. After going through this process, the nonlinear equations of motion for the Rotary Pendulum are:​

$$
\displaystyle\left (m\_pL\_r^2 + \frac{1}{4}m\_pL\_p^2 - \frac{1}{4}m\_pL\_p^2 \cos^2(\alpha)+J\_r \right )\ddot{\theta} - \left (\frac{1}{2}m\_pL\_pL\_r\cos(\alpha) \right)\ddot{\alpha} \\+ \displaystyle\left(\frac{1}{2}m\_pL\_p^2\sin(\alpha)\cos(\alpha)\right)\dot{\theta}\dot{\alpha} + \left( \frac{1}{2}m\_pL\_pL\_r\sin(\alpha)\right)\dot{\alpha}^2 = \tau - B\_r\dot{\theta} \qquad \qquad \tag{7}
$$

$$
\displaystyle{\left(-\frac{1}{2}m\_pL\_pL\_r\cos(\alpha) \right)\ddot{\theta} + \left(J\_p + \frac{1}{4}m\_pL\_p^2 \right) \ddot{\alpha} - \left(\frac{1}{4} m\_pL\_p^2\cos(\alpha)\sin(\alpha)\right)\dot{\theta}^2} \ -\frac{1}{2} m\_pL\_pg\sin(\alpha) = -B\_p\dot{\alpha} \qquad \qquad \tag{8}
$$

The torque applied at the base of the rotary arm (i.e. at the load gear) is generated by the servo motor as described by the equation 7. Refer to [Table A](#table-a-main-rotary-servo-base-unit-specifications) in the Appendix for the Rotary Servo parameters.

$$
\tau = \displaystyle\frac{\eta\_gK\_g\eta\_mk\_t(V\_m - K\_gk\_m\dot{\theta})}{R\_m} \qquad \qquad \tag{9}
$$

### Linearization

Linearization of a nonlinear function about a selected point is obtained by retaining upto first order term in the Taylor Series expansion of the function about the selected point. For example, linearization of a two variable nonlinear function f(z) where&#x20;

$$
z = \begin {bmatrix}  z\_1 & z\_2\end {bmatrix}^T
$$

about the point

$$
z\_0 = \begin {bmatrix}  a & b\end {bmatrix}^T
$$

can be written as

$$
f\_{lin}(z) = f(z\_0) + \frac{\partial f(z)}{\partial z\_1}\Bigr|*{z = z\_0} (z\_1 - a)+\frac{\partial f(z)}{\partial z\_2}\Bigr|*{z=z\_0}(z\_2 - b)
$$

​

### Linearization of Inverted Pendulum Equations

The nonlinear equations of the inverted pendulum system obtained as Equations (7) and (8) are linearized about the equilibrium point with the pendulum in the upright position, i.e.,&#x20;

&#x20;                               $$\theta\_o = 0$$, $$\alpha\_o = 0$$, $$\dot{\theta}\_o = 0$$, $$\dot{\alpha}\_o = 0$$, $$\ddot{\theta}\_o = 0$$, $$\ddot{\alpha}\_o = 0$$

Linearization of Equation (7) about the above equilibrium state gives

$$
(J\_r + m\_pL\_r^2)\ddot{\theta} - \frac{1}{2}m\_pL\_pL\_r\ddot{\alpha} = kV\_m-b\dot{\theta} - B\_r\dot{\theta}  \quad\quad (10)
$$

where, from Equation(9) the servo motor torque coefficient $$k$$ is&#x20;

$$
k = \frac{\eta\_gK\_g\eta\_mk\_t}{R\_m}
$$

and the back emf coefficient $$b$$ is

$$
b = \frac{\eta\_gK\_g^2\eta\_mk\_tk\_m}{R\_m}
$$

Likewise, linearization of Equation (8) about the equilibrium point with the pendulum in the upright position gives

$$
-\frac{1}{2}m\_pL\_pL\_r\ddot{\theta} + (J\_p + \frac{1}{4}m\_pL\_p^2)\ddot{\alpha} - \frac{1}{2}m\_pL\_pg\alpha= -B\dot{\alpha} \quad \quad (11)
$$

where $$g$$ is the acceleration due to gravity. Note that the negative sign of the gravity torque ($$\alpha$$ term) in Equation 11 indicates negative stiffness with the pendulum in the vertically upright position.

Equations (10) and (11) can be arranged in the matrix form as

$$
\[M]\begin{bmatrix}\ddot{\theta} \ \ddot{\alpha} \end{bmatrix} +\[D] \begin{bmatrix}\dot{\theta} \ \dot{\alpha} \end{bmatrix} + \[K] \begin{bmatrix}\theta \ \alpha \end{bmatrix} = \begin{bmatrix}k \ 0 \end{bmatrix}V\_m \quad \quad (12)
$$

Where mass matrix $$M$$, damping matrix $$D$$, and the stiffness matrix $$K$$ become

$$
\[M] = \begin{bmatrix} (J\_r + m\_pL\_r^2)  &  -\frac{1}{2}m\_pL\_pL\_r \\
-\frac{1}{2}m\_pL\_pL\_r  & (J\_p + \frac{1}{4}m\_pL\_p^2) \end{bmatrix}
$$

$$
\[D] = \begin{bmatrix} b+B\_r & 0 \ 0 & B\_p \end{bmatrix}
$$

$$
\[K] = \begin{bmatrix} 0 & 0 \ 0 & -\frac{1}{2}m\_pL\_pg \end{bmatrix}
$$

Defining the state vector $$x$$, output vector $$y$$ and the control input $$u$$ as

$$
x = \begin{bmatrix} \theta & \alpha & \dot{\theta} & \dot{\alpha}\end{bmatrix}^T , \quad y = \begin{bmatrix} \theta & \alpha \end{bmatrix}^T, \quad u = V\_m
$$

Equation (12) can be rewritten in state space form as&#x20;

$$
\dot{x} = Ax + Bu  \quad \quad (13)
$$

$$
y = Cx + Du \quad \quad (14)
$$

where the system state matrix $$A$$, control matrix $$B$$, output matrix $$C$$and the feedthrough of input to the output matrix $$D$$ become

$$
A = \begin{bmatrix} O\_{2\times2} & I\_{2\times2} \ -\[M]^{-1}\[K] & -\[M]^{-1}\[D]  \end{bmatrix}
$$

$$
B = \begin{bmatrix} O\_{2\times1} \ M^{-1} \begin{bmatrix} k \0 \end{bmatrix} \end{bmatrix}
$$

$$
C = \begin{bmatrix} 1 & 0 & 0 & 0 \ 0 & 1 & 0 & 0 \end{bmatrix}
$$

$$
D = \begin{bmatrix} 0 \ 0 \end{bmatrix}
$$

In the equations above, note that $$O\_{2\times2}$$ is a $$2 \times 2$$ matrix of zeros, $$O\_{2\times1}$$ is a $$2 \times 1$$ matrix of zeros, and $$I\_{2 \times 2}$$ is a $$2\times2$$ identity matrix. Using the parameters of the system listed in [Table 2](#table-2-main-parameters-associated-with-the-rotary-pendulum-module) and the appendix [Table A](#table-a-main-rotary-servo-base-unit-specifications), the linear model matrices$$A$$ and $$B$$ can be computed.

### Analysis: Modeling

{% file src="<https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2FZzJLq2YFS65OvbTyV3sW%2FPart%201.zip?alt=media&token=a03b4e4a-18a7-4b96-9676-c3f887e09734>" %}

1. Download the Part 1.zip file and extract the folder contents.
2. Open <mark style="background-color:orange;">rotpen\_part1\_student.mlx</mark> live script and run the **Modelling** section. It will automatically load the parameters required for the state-space representation, and subsequently generate the A, B, C and D matrices required for the upcoming analysis. Please refer to [Table 2](#table-2-main-parameters-associated-with-the-rotary-pendulum-module) and [Table A](#table-a-main-rotary-servo-base-unit-specifications) for additional information regarding the parameters.\
   \
   **Note:** The representative C and D matrices have already been included. The actuator dynamics have been added to convert your state-space matrices to be in terms of voltage. Recall that the input of the state-space model is the torque acting at the servo load gear. However, we control the servo input voltage instead of control torque directly. The script uses the voltage torque relationship given in Equation 9 to transform torque to voltage.<br>
3. **Note down** your state-space matrices for your report.\
   \
   **Note:** You may want to cross-check the state-space matrix with TAs before proceeding to balance control.<br>
4. Find the open-loop poles of the system. \
   **Hint:** Use `eig(A).`

## B. Balance Control

### Specification

The control design and time-response requirements are: \
**Specification 1:** Damping ratio: 0.6 <  $$\zeta$$  < 0.8\
**Specification 2**: Natural frequency: 3.5 rad/s <  $$\omega\_\rm{n}$$ <  4.5 rad/s\
**Specification 3:** Maximum pendulum angle deflection: $$|\alpha|$$ < 15 deg. \
**Specification 4:** Maximum control effort / voltage: $$|V\_\rm{m}|$$ < 10 V. \
\
The necessary closed-loop poles are found from specifications 1 and 2. The pendulum deflection and control effort requirements (i.e. specifications 3 and 4) are to be satisfied when the rotary arm is tracking a $$\pm 20$$ degree angle square wave.

### Stability

The stability of a system can be determined from its poles (\[1]):&#x20;

* Stable systems have poles only in the left-half of the complex plane.&#x20;
* Unstable systems have at least one pole in the right-half of the complex plane and/or poles of multiplicity greater than 1 on the imaginary axis.&#x20;
* Marginally stable systems have one pole on the imaginary axis and the other poles in the left-half of the complex plane.&#x20;

The poles are the roots of the system’s characteristic equation. From the state-space, the characteristic equation of the system can be found using

<br>

$$
\mathrm{det}(sI - A) = 0 \qquad \qquad\tag{15}
$$

where $$\mathrm{det}()$$is the determinant of a matrix, $$s$$ is the Laplace operator, and $$I$$ is the identity matrix. These are the eigenvalues of the system matrix $$A$$.

### Controllability

If the control input $$u$$ of a system can take each state variable, $$x\_i$$ where $$i = 1 ... n$$, from an initial state to a final state in finite time then the system is controllable, otherwise it is uncontrollable (\[1]).&#x20;

**Rank Test** The system is controllable if the rank of its controllability matrix

$$
W = \[B \ AB \ A^2B \ ... \ A^{n-1}B] \qquad \qquad \tag{16}
$$

equals the number of states in the system, i.e.

$$
\mathrm{rank}(W) = n \qquad \qquad \tag{17}
$$

$$
\mathrm{rank}(W) = n \qquad \qquad \tag{17}
$$

### Companion Matrix

For a controllable system with *nxn* system matrix A and *nx1* control matrix B. The companion matrices of A and B are&#x20;

$$
\tilde{A} =  \begin{bmatrix} 0 & 1 & \dots & 0& 0 \ 0 & 0 & \dots & 0& 0 \ \vdots & \vdots & \ddots & \vdots& \vdots \ 0 & 0 & \dots & 0& 1 \ -a\_1 & -a\_2 & \dots & -a\_{n-1}& -a\_n   \end{bmatrix} \qquad \qquad \tag{18}
$$

and

$$
\tilde{B} =  \begin{bmatrix} 0\\\vdots\ \1 \end{bmatrix} \qquad \qquad \tag{19}
$$

Where $$a\_1, a\_2, ...a\_n$$ are the coefficients of the characteristic equation of the system matrix A written as&#x20;

$$s^n + a\_ns^{n-1} + a\_{n-1}s^{n-2} +a\_2s + a\_1 = 0\tag{20}$$

$$
s^n + a\_ns^{n-1} + a\_{n-1}s^{n-2} + ...+a\_2s + a\_1 = 0
$$

Now define T,&#x20;

$$
T = W\tilde{W}^{-1} \qquad \qquad \tag{20}
$$

where $$W$$ is the controllability matrix defined in Equation 16 and

$$
\tilde{W} = \begin{bmatrix}\tilde{B} & \tilde{A}\tilde{B} & \cdots & \tilde{A}^{n-1}\tilde{B}\end{bmatrix} \qquad \qquad \tag{21}
$$

Then

$$
T^{-1}AT = \tilde{A} \qquad \qquad \tag{22}
$$

\
and

$$
T^{-1}B = \tilde{B} \qquad \qquad \tag{23}
$$

### Pole Placement Theory

If $$(A,B)$$ are controllable, then pole placement can be used to design the controller. Given the control law $$u = -Kx$$, the state-space model of Equation (13) becomes

$$
\dot{x} = Ax + B(-Kx) =(A - BK)x \qquad \qquad \tag{25}
$$

We can generalize the procedure to design a gain $$K$$ for a controllable $$(A,B)$$ system as follows:

**Step 1** Find the companion matrices $$\tilde{A}$$ and $$\tilde{B}$$. Compute $$T = W\tilde{W}^{-1}$$. \
\
**Step 2** Compute $$\tilde{K}$$ to assign the poles of $$\tilde{A} - \tilde{B}\tilde{K}$$ to the desired locations.

$$
\tilde{A} - \tilde{B}\tilde{K}=  \begin{bmatrix} 0 & 1 & \dots & 0& 0 \ 0 & 0 & \dots & 0& 0 \ \vdots & \vdots & \ddots & \vdots& \vdots \ 0 & 0 & \dots & 0& 1 \ -a\_1-\tilde{k\_1} & -a\_2-\tilde{k\_2} & \dots & -a\_{n-1}-\tilde{k\_{n-1}}& -a\_n -\tilde{k\_n}  \end{bmatrix} \qquad \qquad \tag{26}
$$

**Step 3** Find $$K = \tilde{K}T^{-1}$$ to get the feedback gain for the original system $$(A,B)$$. \
\
**Remark-1**: It is important to do the $$\tilde{K} \rightarrow K$$ conversion. Remember that $$(A,B)$$ represents the actual system while the companion matrices $$\tilde{A}$$ and $$\tilde{B}$$ do not.

**Remark-2:** The entire control design procedure using the pole placement method can be simply done in MATLAB using the function called 'place' or 'acker'. For a selected desired set of closed loop poles DP, the full state feedback gain matrix $$K$$ is obtained from

```
>> K = acker(A,B,DP);
```

### Desired Poles

The rotary inverted pendulum system has four poles. As depicted in Figure 3, poles $$p\_1$$ and $$p\_2$$ are the complex conjugate dominant poles and are chosen to satisfy the natural frequency, $$\omega\_n$$, and  the damping ratio, $$\zeta$$, as given in the  [Specification](#specification)s. Let the conjugate poles be

$$
p\_1 = -\sigma + j\omega\_d \qquad \qquad \tag{27a}
$$

and

$$
p\_2 = -\sigma - j\omega\_d \qquad \qquad \tag{27b}
$$

where​ $$\sigma = \zeta\omega\_n$$ and $$\omega\_d = \omega\_n \sqrt{1-\zeta^2}$$ is the damped  frequency. The remaining closed-loop poles, $$p\_3$$ and $$p\_4$$, are placed along the real-axis to the left of the dominant poles, as shown in Figure 3.

<figure><img src="https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2FUFYioHNdXXyCfERfU1vE%2FFigure3.1.png?alt=media&#x26;token=a97f7aec-0943-45d5-afc7-9516e78bbe41" alt=""><figcaption><p>Figure 3 Desired closed-loop pole locations</p></figcaption></figure>

### Simulation Model with Feedback

The feedback control loop that balances the rotary pendulum is illustrated in Figure 4. The reference state is defined as

$$
x\_d = \[\theta\_d \ 0\ 0\ 0]^ \intercal  \qquad \qquad \tag{28}
$$

where $$\theta\_d$$ is the desired rotary arm angle. The controller is&#x20;

$$
u = K(x\_d - x) \qquad \qquad \tag{29}
$$

Note that if $$x\_d = 0$$ then $$u = -Kx$$, which is the control used in the pole-placement algorithm.

<figure><img src="https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2FnC3wAwn8rw6T2RbUSlPf%2Flab4_week1_sim.png?alt=media&#x26;token=ab0a4a9d-6d4f-4f53-9f6d-495a16686c98" alt="" width="563"><figcaption><p>Figure 4 State-feedback control loop</p></figcaption></figure>

When running this on the actual system, the pendulum begins in the hanging, downward position. We only want the balance control to be enabled when the pendulum is brought up around its upright vertical position. The controller is therefore

$$
u =     \begin{cases} K(x\_d - x) & |x\_2| <\epsilon \\\  0 & \text{otherwise}  \end{cases} \qquad \qquad \tag{30}
$$

where $$\epsilon$$ is the angle about which the controller should engage. Also $$x\_2$$ is the pendulum angle. For example if $$\epsilon = 10$$ degrees, then the control will begin when the pendulum is within ±10 degrees of its upright position, i.e. when $$|x\_2| < 10$$ degrees.

### B.1 Experiment: Designing the Balance Control

1. Select $$\zeta$$ and $$\omega\_n$$ from the table below. Ensure to choose a different set of values from your groupmates &#x20;

   <table><thead><tr><th width="129">Parameter</th><th width="67" data-type="number">1</th><th width="64" data-type="number">2</th><th width="68" data-type="number">3</th><th width="71" data-type="number">4</th><th width="70" data-type="number">5</th><th width="62" data-type="number">6</th><th width="75" data-type="number">7</th><th data-type="number">8</th></tr></thead><tbody><tr><td><span class="math">w_n</span> (rad/s)</td><td>3.75</td><td>4</td><td>4.25</td><td>3.75</td><td>4.25</td><td>3.75</td><td>4</td><td>4.25</td></tr><tr><td><span class="math">\zeta</span></td><td>0.65</td><td>0.65</td><td>0.65</td><td>0.7</td><td>0.7</td><td>0.75</td><td>0.75</td><td>0.75</td></tr></tbody></table>
2. In the same <mark style="background-color:orange;">rotpen\_part1\_student.mlx</mark> live script, go to the **Balance Control** section. Enter the chosen `zeta` and `omega_n` values.
3. Determine the locations of the two dominant poles $$p\_1$$ and $$p\_2$$ based on the specifications and enter their values in the MATLAB live script. Ensure that the other poles are placed at `p3 = -30` and `p4 = -40`.\
   **Hint:** Use equation 27.
4. Find gain `K` using a predefined Compensator Design MATLAB command\
   `K = acker(A,B,DP)`, which is based on pole-placement design.\
   **Note:** `DP` is a row vector of the desired poles found in Step 3.

{% hint style="warning" %}
For sanity check, if you use damping ratio of 0.7 and natural frequency of 4 rad/s, you should get around K = \[-12    63    -5.5    7].
{% endhint %}

### B.2 Experiment: Simulating the Balance Control

The *s\_rotpen\_bal* SIMULINK diagram shown in Figure 5 is used to simulate the closed-loop response of the Rotary Pendulum using the state-feedback control described in [Balance Control](#2.-balance-control) with the control gain K found above.\
\
The Signal Generator block generates a 0.1 Hz square wave (with an amplitude of 1). The Amplitude (deg) gain block is used to change the desired rotary arm position. The state-feedback gain K is set in the Control Gain gain block and is read from the MATLAB workspace. The SIMULINK State-Space block reads the A, B, C, and D state-space matrices that are loaded in the MATLAB workspace. The Find State X block contains high-pass filters to find the angular rates of the rotary arm and pendulum.

<figure><img src="https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2FqdqtsPIFhtXCBxfz3UyF%2FFigure3.3.png?alt=media&#x26;token=c713db10-f827-43f0-b56a-b21817eac6c0" alt=""><figcaption><p>Figure 5: s_rotpen_bal SIMULINK diagram used to simulate the state-feedback control</p></figcaption></figure>

1. Run *rotpen\_part1\_student.mlx* live script. Ensure the gain K you found is loaded in the workspace (type K matrix in the command window).
2. Open and run the *s\_rotpen\_bal.mdl* for 10 seconds. The responses in the scopes shown in Figure 6 were generated using an arbitrary feedback control gain. \
   \
   **Note:** When the simulation stops, the last 10 seconds of data is automatically saved in the MATLAB workspace to the variables `data_theta`, `data_alpha`, and `data_Vm`.<br>

   <figure><img src="https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2F2sliFFue7qbZ7dybwUGZ%2FFigure3.4.png?alt=media&#x26;token=df0f8f0a-95b6-4dff-9d90-743fdca5cf92" alt=""><figcaption><p>Figure 6: Balance control simulation</p></figcaption></figure>
3. **Save** the data corresponding to the simulated response of the rotary arm, pendulum, and motor input voltage obtained using your obtained gain K.\
   \
   **Note:** The time is stored in the `data_theta(:,1)` vector, the desired and measured rotary arm angles are saved in the `data_theta(:,2)` and `data_theta(:,3)` arrays. Similarly, the pendulum angle is stored in the `data_alpha(:,2)` vector, and the control input is in the `data_Vm(:,2)` structure.
4. Measure the pendulum deflection and voltage used. Are the [specifications](#specification) given satisfied?

### B.3 Experiment: Implementing the Balance Controller

{% file src="<https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2FrTeAZw5GxXl2yWGJi7lP%2FPart%202.zip?alt=media&token=fb95a11c-7c5b-46c9-bb47-b6403c5dbbc8>" %}

In this section, the state-feedback control that was designed and simulated in the previous sections is run on the actual Rotary Pendulum device.&#x20;

**Experiment Setup**&#x20;

The q\_rotpen\_bal\_student SIMULINK diagram shown in Figure 7 is used to run the state-feedback control on the Quanser Rotary Pendulum system. The Rotary Pendulum Interface subsystem contains QUARC blocks that interface with the DC motor and sensors of the system. The feedback developed in the previous section is implemented using a Simulink Gain block.

<figure><img src="https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2F2yK7E993CCxB3K2swOgq%2Flab4_simulink.jpg?alt=media&#x26;token=8288a2ee-1d9e-4b18-bdda-032754b07c2e" alt=""><figcaption><p>Figure 7. q_rotpen_bal_student SIMULINK diagram can be used to run balance controller</p></figcaption></figure>

1. Download the Part 2.zip file, extract the folder contents and open the part2setup.m script.

2. Go to the 'Balance Control' section and put the gain K you found in [Step 4 of Designing the Balance Control experiment](#b.1-experiment-designing-the-balance-control). Run the script.

3. Open the q\_rotpen\_bal\_student SIMULINK diagram.

4. As shown in Figure 7, the SIMULINK diagram is incomplete. Add the necessary blocks from the Simulink library to implement the balance control.&#x20;
   * You need to add a switch logic to implement Equation 30. Use Multi-port switch with 2 data points and zero-based contiguous. The output from the compare to constant block will be 0 if false and 1 if true. Check your block with TA.
   * **Ensure that you connect the final signal going into the&#x20;*****u(V)*****&#x20;terminal of the Rotary Pendulum Interface, which is also connected to the&#x20;*****u*****&#x20;scope terminal.**

5. Turn ON the power amplifier.

6. Ensure the pendulum is in the hanging down position, with the **rotary arm aligned with the 0 marking**, and is motionless.&#x20;

7. To build the model, click the down arrow on **Monitor & Tune** under the Hardware tab and then click **Build** **for monitoring** ![](https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2FCq5iMDIRj3JN7fcFsx2w%2Fimage.png?alt=media\&token=6ffaf234-92d6-4de2-be27-7a37a4fe9dcc). This generates the controller code.

8. Press **Connect** <img src="https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2F1VD5IqnbVgR6hbi4YOei%2Fimage.png?alt=media&#x26;token=02e68127-9611-4c74-b03f-b7cac5c04a34" alt="" data-size="line"> button under Monitor & Tune and Press **Start** <img src="https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2F5kUOzUmpIz5Mob4x7xd1%2Fimage.png?alt=media&#x26;token=60cb4298-b97c-4538-8240-2d44c2d721b0" alt="" data-size="line">.

9. Once it is running, manually bring up the pendulum to its upright vertical position. You should feel the voltage kick-in when it is within the range where the balance control engages. Once it is balanced, the controller will introduce the ±20 degree rotary arm rotation.

10. The response should look similar to your simulation. Once you have obtained a response, click on the STOP button to stop the controller (data is saved for the last 10 seconds, so **stop SIMULINK around 18-19 seconds once the response looks similar to Figure 8**). <br>

    <div data-gb-custom-block data-tag="hint" data-style="danger" class="hint hint-danger"><p><strong>CAUTION</strong><br><br>Be careful, as the pendulum will fall down when the controller is stopped.</p></div>

11. Similar to the simulation Simulink model, the response data will be saved to the workspace. **Copy and paste** into your group's folder. **Ensure that the data variables have 10 seconds of data saved.**

<figure><img src="https://1205030739-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MIedmBPpkGaOOtNl4mm%2Fuploads%2Fplh8e530zP4jR2l8kZ4s%2FFigure8.png?alt=media&#x26;token=236a7393-ce8c-421f-ba6b-150debdc2862" alt=""><figcaption><p>Figure 8. Experiment balance control response example</p></figcaption></figure>

## Results for Report

### A) Modeling

1. The linear state-space representation of the rotary inverted pendulum system, i.e., $$A$$, $$B$$, $$C$$ and $$D$$ matrices (numerical values).
2. Open-loop poles of the system.

### B.1) Balance Control Design

1. Chosen $$\zeta$$ and $$\omega\_n$$ based on design specifications.
2. Corresponding locations of the two dominant poles $$p\_1$$ and $$p\_2$$.
3. Gain vector $$K$$.

### B.2) Balance Control Simulation

1. Plots of the commanded position of the rotary arm ($$\theta\_c$$), simulated responses of the rotary arm ($$\theta$$), pendulum ($$\alpha$$), and motor input voltage ($$V\_m$$) generated using your obtained gain *K*.
2. Are [Design Specifications 3 and 4](#specification) satisfied? Justify using the measured maximum pendulum deflection and motor input voltage values.

### B.3) Balance Controller Implementation

1. From [Step B.3.10](#b.3-experiment-implementing-the-balance-controller), plots of the commanded position of the rotary arm ($$\theta\_c$$), experimental responses of the rotary arm ($$\theta$$), pendulum ($$\alpha$$), and motor input voltage ($$u(V\_m)$$) generated using the chosen gain *K*.
2. Are [Design Specifications 3 and 4](#specification) satisfied? Justify using the measured maximum pendulum deflection and motor input voltage values.

## Questions for Report

### A) Modeling

1. Based on your open-loop poles found in [Result A.2](#a-modeling), is the system stable, marginally stable, or unstable?
2. Did you expect the stability of the inverted pendulum to be as what was determined? Justify.

### B.1) Balance Control Design

For the questions below, **calculations and intermediate steps must be shown**.

1. Determine the controllability matrix $$W$$ of the system. Is the inverted pendulum system controllable?\
   **Hint:** Use Equation 17.
2. Using the open-loop poles, find the characteristic equation of $$A$$. \
   **Hint:** The roots of the characteristic equation are the open-­loop poles.

   <div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><p>Instead of using <span class="math">\mathrm{det}(sI - A) = 0 </span>, characteristic polynomials can also be found using MATLAB function <a href="https://www.mathworks.com/help/matlab/ref/poly.html"><code>poly()</code></a>.</p></div>
3. Find the corresponding companion matrices $$\tilde{A}$$ and $$\tilde{B}$$ . \
   **Hint:** For $$\tilde{A}$$ , use the characteristic equation of A found in [Question B.1.2](#b-balance-control-design-1) and Equation 19. For $$\tilde{B}$$, use Equation 20.
4. Determine the controllability matrix $$\tilde{W}$$ of the companion system.
5. Determine the transformation matrix $$T$$.
6. Check if $$\tilde{A} = T^{-1}AT$$ and $$\tilde{B} = T^{-1}B$$ with the obtained matrices.
7. Using the locations of the two dominant poles, $$p\_1$$ and $$p\_2$$, based on the [specifications](#specification) ([Result B.1.1](#b.1-balance-control-design)), and the other poles at $$p\_3 = -30$$ and $$p\_4 = -40$$, determine the desired closed-loop characteristic equation.\
   **Hint:** The roots of the closed-loop characteristic equation are the closed-­loop poles.
8. When applying the control $$u = -\tilde{K}x$$ to the companion form, it changes $$(\tilde{A}, \tilde{B})$$ to $$(\tilde{A}-\tilde{B}\tilde{K}, \tilde{B})$$. Find the gain $$\tilde{K}$$ that assigns the poles to their new desired location.\
   **Hint:** Use Equation 26 and find the corresponding characteristic equation. Compare this equation with the desired closed-loop characteristic equation found in [Question B.1.7](#b-balance-control-design-1) to determine the gain vector $$\tilde{K}$$.
9. Once you have found $$\tilde{K}$$, find $$K$$ using [Step 3 in Pole Placement Theory](#pole-placement-theory).
10. Compare the gain vector $$K$$calculated using Pole Placement Theory ([Question B.1.9](#b.1-balance-control-design-1)) with the gain vector $$K$$ obtained using MATLAB ([Result B.1.3](#b.1-balance-control-design)).
11. Estimate the bandwidth for your balance controller. \
    **Hint:** Use 'bandwidth(sysclosed)' command in MATLAB.

    \>> sysclosed = ss((A-B\*K), B, \[1 0 0 0], 0);

    \>> bw = bandwidth(sysclosed)

    \>> bode(sysclosed)<br>

    The bode() function produces a closed-loop system frequency response plot. Include Bode plots of the closed-loop system and list the bandwidth of the system with the balance controller.
12. Estimate the stability margins (gain and phase margins) of your balance controller. \
    **Hint:** Use 'margin(sysopen)' command in MATLAB where 'sysopen' is the state space model of the open loop system with the controller.

    \>> sysopen = ss(A,B,K,0)

    \>> margin(sysopen)<br>

    We get bode plot of the open loop system with the controller with margins listed on the plots. Include the Bode plots for the balance controller.

## Appendix

### Table A Main Rotary Servo Base Unit Specifications

|                      |                                                              |                             |
| -------------------- | ------------------------------------------------------------ | --------------------------- |
| $$V\_{\rm{nom}}$$    | Motor nominal input voltage                                  | 6.0 V                       |
| $$R\_\rm{m}$$        | Motor armature resistance                                    | 2.6 Ω ± 12%                 |
| $$L\_\rm{m}$$        | Motor armature inductance                                    | 0.18 mH                     |
| $$k\_\rm{t}$$        | Motor current-torque constant                                | 7.68 × 10−3 N-m/A ± 12%     |
| $$k\_\rm{m}$$        | Motor back-emf constant                                      | 7.68 × 10−3 V/(rad/s) ± 12% |
| $$K\_\rm{g}$$        | High-gear total gear ratio                                   | 70                          |
| $$\eta\_\rm{m}$$     | Motor efficiency                                             | 0.69 ± 5%                   |
| $$\eta\_\rm{g}$$     | Gearbox efficiency                                           | 0.90 ± 10%                  |
| $$J\_\rm{m}$$        | rotor Rotor moment of inertia                                | 3.90 × 10−7 kg-m2 ± 10%     |
| $$J\_\rm{eq}$$       | High-gear equivalent moment of inertia without external load | 1.823 × 10−3 kg-m2          |
| $$B\_\rm{eq}$$       | High-gear Equivalent viscous damping coefficient             | 0.015 N-m/(rad/s)           |
| $$m\_\rm{b}$$        | Mass of bar load                                             | 0.038 kg                    |
| $$L\_\rm{b}$$        | Length of bar load                                           | 0.1525 m                    |
| $$m\_\rm{d}$$        | Mass of disc load                                            | 0.04 kg                     |
| $$r\_\rm{d}$$        | Radius of disc load                                          | 0.05 m                      |
| $$m\_\rm{max}$$      | Maximum load mass                                            | 5 kg                        |
| $$f\_\rm{max}$$      | Maximum input voltage frequency                              | 50 Hz                       |
| $$l\_\rm{max}$$      | Maximum input current                                        | 1 A                         |
| $$\omega\_\rm{max}$$ | Maximum motor speed                                          | 628.3 rad/s                 |

## Reference

\[1] Norman S. Nise. Control Systems Engineering. John Wiley & Sons, Inc., 2008.<br>
