Matlab Tutorial

439
Cơ sở MATLAB Vector Các hàm Vẽ Đa thức Ma trận In ấn Sử dụng M-files trong M ATLAB Tìm trợ giúp trong M ATLAB Các lệnh chính của MATLAB được dùng trong tài liệu này là: plot, polyval, roots, conv, deconv, inv, eig và poly. MATLAB là một chương trình tính toán bằng số và hiển thị số liệu theo kiểu tương tác. Nó được dùng chủ yếu trong phân tích và thiết kế hệ thống điều khiển tự động. Có nhiều hộp công cụ (Toolbox) để mở rộng ứng dụng các hàm cơ bản của MATLAB vào các lĩnh vực khác nhau. Trong tài liệu này, chúng tôi tập trung vào sử dụng các hộp công cụ điều khiển (Control Systems Toolbox). MATLAB có các phiên bản chạy trong môi trường Unix, Macintosh và Windows. Hiện có một phiên bản MATLAB dùng cho đào tạo, chạy trên PC. Muốn có thông tin chi tiết về MATLAB hãy liên hệ với MathWorks . Ý tưởng của chúng tôi khi viết tài liệu này là để bạn có thể hiện bài học trong một cửa sổ trong khi chạy MATLAB trong cửa sổ khác. Bạn có thể chạy các lệnh tính toán và vẽ trong tài liệu bằng cách cắt văn bản và dán vào MATLAB hoặc vào một M-file. Vector Chúng ta bắt đầu từ việc tạo một đối tượng đơn giản, như một vector. Nhập các phần tử của vector (cách nhau một dấu trống) giữa 2 ngoặc vuông và gán nó vào một biến. Ví dụ, để tạo vector a, hãy nhập dòng sau vào cửa sổ lệnh của MATLAB (bạn có thể "copy" và "paste" từ browser vào MATLAB cho dễ): a = [1 2 3 4 5 6 9 8 7] MATLAB trả về: a = 1 2 3 4 5 6 9 8 7 Nếu bạn muốn tạo một vector có các phần tử từ 0 đến 20, mỗi phần tử cách nhau 2 (phương pháp này thường được dùng để tạo vector thời gian): 1

Transcript of Matlab Tutorial

Page 1: Matlab Tutorial

Cơ sở MATLAB

VectorCác hàmVẽĐa thứcMa trậnIn ấnSử dụng M-files trong MATLABTìm trợ giúp trong MATLAB

Các lệnh chính của MATLAB được dùng trong tài liệu này là: plot, polyval, roots, conv, deconv, inv,eig và poly.

MATLAB là một chương trình tính toán bằng số và hiển thị số liệu theo kiểu tương tác. Nó được dùngchủ yếu trong phân tích và thiết kế hệ thống điều khiển tự động. Có nhiều hộp công cụ (Toolbox) đểmở rộng ứng dụng các hàm cơ bản của MATLAB vào các lĩnh vực khác nhau. Trong tài liệu này, chúngtôi tập trung vào sử dụng các hộp công cụ điều khiển (Control Systems Toolbox). MATLAB có cácphiên bản chạy trong môi trường Unix, Macintosh và Windows. Hiện có một phiên bản MATLAB dùngcho đào tạo, chạy trên PC. Muốn có thông tin chi tiết về MATLAB hãy liên hệ với MathWorks.

Ý tưởng của chúng tôi khi viết tài liệu này là để bạn có thể hiện bài học trong một cửa sổ trong khichạy MATLAB trong cửa sổ khác. Bạn có thể chạy các lệnh tính toán và vẽ trong tài liệu bằng cáchcắt văn bản và dán vào MATLAB hoặc vào một M-file.

Vector

Chúng ta bắt đầu từ việc tạo một đối tượng đơn giản, như một vector. Nhập các phần tử của vector(cách nhau một dấu trống) giữa 2 ngoặc vuông và gán nó vào một biến. Ví dụ, để tạo vector a, hãynhập dòng sau vào cửa sổ lệnh của MATLAB (bạn có thể "copy" và "paste" từ browser vào MATLABcho dễ):

a = [1 2 3 4 5 6 9 8 7]

MATLAB trả về:

a = 1 2 3 4 5 6 9 8 7

Nếu bạn muốn tạo một vector có các phần tử từ 0 đến 20, mỗi phần tử cách nhau 2 (phương pháp nàythường được dùng để tạo vector thời gian):

1

Page 2: Matlab Tutorial

t = 0:2:20

t = 0 2 4 6 8 10 12 14 16 18 20

Sử dụng các vector cũng dễ như tạo ra chúng. Trước hết, nếu muốn cộng thêm 2 vào mỗi phần tử củavector 'a', bạn hãy nhập biểu thức sau:

b = a + 2

b = 3 4 5 6 7 8 11 10 9

Bây giờ, giả sử bạn muốn cộng 2 vector với nhau. Nếu chúng có độ dài bằng nhau thì thật là dễ, chỉcần gõ vào biểu thức:

c = a + b

c = 4 6 8 10 12 14 20 18 16

Trừ các vector có cùng chiều dài được thực hiện hoàn toàn giống như cộng chúng.

Các hàm (Functions)

Để cho thuận tiện, MATLAB được tích hợp nhiều hàm chuẩn. Mỗi hàm là một khối lệnh để thực hiệnmột chức năng nhất định. MATLAB có tất cả các hàm toán học chuẩn, như sin, cos, log, exp, sqrt,...Các hằng thông dụng, như pi hay i, j trong căn bậc 2 của -1, cũng có trong MATLAB.

sin(pi/4)

ans =

0.7071

Để xem cách sử dụng hàm, gõ help [tên_hàm] trong cửa sổ lệnh của MATLAB.

MATLAB còn cho phép bạn tạo hàm riêng của mình với lệnh function.Hãy bấm vào đây để học cáchtạo hàm và xem danh sách chúng tôi tạo ra trong tài liệu này.

Vẽ (Plotting)

Việc tạo một đồ thị trong MATLAB cũng dễ dàng. Giả sử bạn muốn vẽ đồ thị hàm sin theo thời gian.Trước hết, tạo một vector thời gian (dấu chấm phảy (;) sau mỗi dòng lệnh để ngăn MATLAB đưa rangay giá trị), sau đó tính giá trị hàm sin cho mỗi giá trị t.

t=0:0.25:7;y = sin(t);plot(t,y)

2

Page 3: Matlab Tutorial

Đồ thị chứa khoảng một chu kỳ của hàm sin. Chức năng vẽ cơ bản của MATLAB rất dễ dùng, ngoài ralệnh plot còn thêm các khả năng bổ sung khác. Bạn hãy link đến trang plotting để biết thêm về khảnăng này.

Đa thức (Polynomials)

Trong MATLAB, một đa thức được biểu diễn thông qua một vector. Tạo một đa thức trong MATLABbằng cách nhập các hệ số của nó theo thứ tự giảm dần của số mũ. Ví dụ đa thức sau

được biểu diễn trong MATLAB dưới dạng vector:

x = [1 3 -15 -2 9]

x = 1 3 -15 -2 9

MATLAB hiểu một vector có n+1 phần tử là một đa thức bậc n. Vì vậy, nếu đa thức bị khuyết một sốhệ số thì ta phải điền thêm số 0 vào vị trí tương ứng. Ví dụ đa thức

sẽ được biểu diễn trong MATLAB như sau:

y = [1 0 0 0 1]

Muốn tìm giá trị của đa thức ta dùng hàm polyval. Ví dụ, tìm giá trị của đa thức trên tại s=2 như sau

z = polyval([1 0 0 0 1],2)

z = 17

Ta cũng có thể tìm nghiệm của một đa thức. Điều đó rất thuận tiện khi có đa thức bậc cao. Ví dụ tìmnghiệm của đa thức

3

Page 4: Matlab Tutorial

nhờ lệnh sau:

roots([1 3 -15 -2 9])

ans = -5.5745 2.5836 -0.7951 0.7860

Muốn nhân 2 đa thức với nhau, ta dùng hàm conv (convolution) để nhân lần lượt các hệ số của chúng.Ví dụ

x = [1 2];y = [1 4 8];z = conv(x,y)

z = 1 6 16 16

Để chia hai đa thức, ta dùng hàm deconv.Hàm này trả về cả thương số và phần dư. Ví dụ, cần chia zcho y và kiểm tra xem có nhận lại được x hay không, ta làm như sau:

[xx, R] = deconv(z,y)

xx = 1 2

R = 0 0 0 0

Ta thấy lại đúng đa thức (vector) x đã tạo ở trên. Nếu phép chia không hết thì phần dư sẽ khác không.

Ma trận (Matrices)

Trong MATLAB, ma trận được biểu diễn tương tự như vector, chỉ khác là các hàng được phân cách bởidấu chấm phảy (;) hoặc chúng được viết thành từng hàng riêng biệt:

B = [1 2 3 4;5 6 7 8;9 10 11 12]

B = 1 2 3 4 5 6 7 8 9 10 11 12

B = [ 1 2 3 4 5 6 7 8 9 10 11 12]

B = 1 2 3 4 5 6 7 8 9 10 11 12

Các ma trận được xử lý trong MATLAB theo nhiều cách. Trước hết, để tìm ma trận chuyển vị C củama trận B, ta dùng dấu lược ('):

C = B'

4

Page 5: Matlab Tutorial

C = 1 5 9 2 6 10 3 7 11 4 8 12

Nếu C có dạng phức thì dấu lược sẽ cho kết quả phức liên hợp. Để nhân được chuyển vị hãy dùng .'(hai lệnh này cho kết quả như nhau nếu C không có dạng phức).

Phép nhân 2 ma trận B và C được biểu diễn như bình thường, nhưng phải chú ý thứ tự của chúng.

D = B * C

D = 30 70 110 70 174 278 110 278 446

D = C * B

D = 107 122 137 152 122 140 158 176 137 158 179 200 152 176 200 224

Khi cần nhân các phần tử tương ứng của 2 ma trận, ta dùng toán tử .*. Khi đó 2 ma trận phải có cùngkích thước.

E = [1 2;3 4]F = [2 3;4 5]G = E .* F

E = 1 2 3 4

F = 2 3 4 5

G = 2 6 12 20

Nếu có một ma trận vuông, bạn có thể nhân nó với chính nó bao nhiêu làn tuỳ ý bằng phép nâng lũythừa:

E^3

ans = 37 54 81 118

Để tính lập phương của mỗi phần tử trong ma trận, ta làm như sau:

E.^3

5

Page 6: Matlab Tutorial

ans = 1 8 27 64

Nghịch đảo của một ma trận được tìm nhờ hàm inv:

X = inv(E)

X = -2.0000 1.0000 1.5000 -0.5000

hoặc giá trị riêng (eigenvalues):

eig(E)

ans = -0.3723 5.3723

MATLAB còn có hàm để tính các hệ số trong đa thức đặc trưng của ma trận. Hàm poly tạo ra mộtvector chứa các hệ số của đa thức đặc trưng.

p = poly(E)

p =

1.0000 -5.0000 -2.0000

Chú ý rằng các giá trị riêng (eigenvalues) của một ma trận chính là các nghiệm của đa thức đặc trưngcủa ma trận đó::

roots(p)

ans = 5.3723 -0.3723

In (Printing)

Để in trong MATLAB cần thực hiện các bước sau:

Trong Macintosh

Muốn in một đồ thị hoặc m-file trong Macintosh, chỉ cần kích chuột vào đồ thị hoặc m-file,chọn Print trong menu File và ấn Return.

Trong Windows

Muốn in một đồ thị hoặc m-file trong Windows, chọn Print trong menu File trong cửa sổ củađồ thị hoặc m-file và ấn Return.

Trong Unix

Muốn in một đồ thị hoặc m-file trong Unix thì nhập lệnh:

6

Page 7: Matlab Tutorial

print -P<printername>

Nếu muốn lưu đồ thị để in sau thì nhập lệnh:

print plot.ps

Khi cần in thì nhập lệnh "lpr -P plot.ps". Nếu bạn đang dùng máy in HP thì dùng lệnh "lpr-d plot.ps".

Muốn in một m-file thì cũng thao tác tương tự như các file khác, dùng lệnh "lpr -P <tênm-file>.m". Nếu dùng máy in HP thì dùng lệnh "lpr -d plot.ps<name of m-file>.m".

Dùng M-files trong MATLAB

Sử dụng M-file trong mỗi hệ điều hành có hơi khác nhau.

Trong Macintosh

Có một bộ soạn thảo chuyên cho m-files. Chọn "New M-file" trong menu File. Bạn có thể dùngmột bộ soạn thảo bất kỳ nhưng phải nhớ ghi các file dưới dạng text và nạp chúng mỗi khi khởiđộng MATLAB.

Trong Windows

Chạy MATLAB trong Windows tương tự như trong Macintosh. Tuy nhiên, để m-file được nạpvào bộ nhớ cần ghi nó dưới dạng file tên_file.m

Trong Unix

Bạn cần chạy một bộ soạn thảo độc lập từ MATLAB. Tốt nhất là tạo một thư mục chứa tất cảcác m-files, sau đó cd tới thư mục đó trước khi khởi động MATLAB và bộ soạn thảo. Để khởiđộng MATLAB từ cửa sổ Xterm của bạn chỉ cần gõ: matlab.

Bạn có thể gõ các trực tiếp gõ các lệnh trong cửa sổ lệnh của MATLAB hoặc đưa tất cả các lệnh cầnthiết trong một m-file và chạy file đó. Nếu bạn chứa tất cả các m-files của bạn trong cùng thư mục màtừ đó bạn khởi động MATLAB thì MATLAB sẽ luôn luôn tìm chúng.

Tìm trợ giúp (Help) trong MATLAB

MATLAB có một hệ trợ giúp trực tuyến tương đối tốt. Để tìm trợ giúp về một lệnh nào đó, gõ:

help tên_lệnh

Bạn rất cần biết tên lệnh mà bạn tìm kiếm trợ giúp. Danh sách các lệnh dùng trong tài liệu này đượccho trong danh sách lệnh. Phím MatLab Commands ở cuối mỗi trang cho phép link đến trang danhsách này.

Here are a few notes to end this tutorial.

Bạn có thể nhận được giá trị của mỗi biến bằng cách gõ tên biến:

B

B =

7

Page 8: Matlab Tutorial

1 2 3 4 5 6 7 8 9

Bạn có thể nhập nhiều lệnh trên cùng một dòng, các lệnh cách nhau bằng dấu chấm phảy (;) hoặc dấuphảy (,).

Nếu không gán phép tính hoặc kết quả cho một biến nào thì MATLAB sẽ gán nó vào một biến tạm thời,tên là "ans".

TutorialsMATLAB Cơ sở | MATLAB - Tạo mô hình | PID | Quỹ tích nghiệm | Đáp ứng tần số | Không giantrạng thái | Điều khiển số | Simulink Cơ sở | Simulink - Tạo mô hình | Các ví dụ

8

Page 9: Matlab Tutorial

Simulink Examples IndexExample Description Tutorial

Cruise ControlMotor Speed Control

Motor Position ControlBus Suspension

Inverted PendulumPitch Control

Ball and Beam

Descriptions of the MATLAB tutorial examples are available here.

Cruise Control

This is a simple example of the modeling and control of a first order system. This model takes inertia anddamping into account. Newton's laws are modeled directly in this example, where forces are summed up toprovide the acceleration of the vehicle. A simple PI controller is implemented.

1

Page 10: Matlab Tutorial

Motor Speed Control

A DC motor has second order speed dynamics when mechanical properties such as inertia and damping aswell as electrical properties such as inductance and resistance are taken into account. Newton's law andKirchoff's law are modeled directly by summing forces and summing voltages to provide the motor'sacceleration and armature current, respectively. A lag compensator is implemented.

Motor Position Control

The model of the position dynamics of a DC motor is third order, because measuring position is equivalentto integrating speed, which adds an order to the motor speed example. In this example, however, the motorparameters are taken from an actual DC motor used in an undergraduate controls course. This motor hasvery small inductance, which effectively reduces the example to second order. This uses the same model asthe motor speed example with an additional integrator to provide position from the velocity signal. In thisexample, a discrete-time model extraction and a discrete-time controller are implemented around thecontinuous plant model.

2

Page 11: Matlab Tutorial

Bus Suspension

This example looks at the active control of the vertical motion of a bus suspension. It takes into accountboth the inertia of the bus and the inertia of the suspension/tires, as well as springs and dampers. An actuatoris added between the suspension and the bus. Newton's law is modeled directly by summing forces acting oneach of the two inertias. A full-state feedback controller is implemented by extracting a set of states directlyfrom the model.

3

Page 12: Matlab Tutorial

Inverted Pendulum

The inverted pendulum is a classic controls demonstration where a pole is balanced vertically on amotorized cart. It is interesting because without control, the system is unstable. This is a fourth ordernonlinear system. This is a particularly difficult system to model in Simulink because of the algebraicconstraint. While Newton's laws are still modeled directly, some calculations must be done in advance toderive the form of the algebraic constraint. A PID controller is implemented using Simulink's built-in PIDblock.

4

Page 13: Matlab Tutorial

Pitch Control

The pitch angle of an airplane is controlled by adjusting the angle (and therefore the lift force) of the rearelevator. The aerodynamic forces (lift and drag) as well as the airplane's inertia are taken into account. Thisis a third order, nonlinear system which is linearized about the operating point. The Simulink model is basedon the State-Space model developed in the MATLAB tutorials, and the state equations are implementeddirectly. Because of this, the state vector is available for use in a full-state-feedback controller.

5

Page 14: Matlab Tutorial

Ball and Beam

This is another classic controls demo. A ball is placed on a straight beam and rolls back and forth as one endof the beam is raised and lowered by a cam. The position of the ball is controlled by changing the angularposition of the cam. This is a second order system, since only the inertia of the ball is taken into account,and not that of the cam or the beam. Rather than modeling forces and accelerations, the Lagrangianequations of motion are implemented is Simulink, eliminating the need to express the algebraic constraintexplicitly as was done in the inverted pendulum example.

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space | Digital

6

Page 15: Matlab Tutorial

Control | Simulink Basics | Simulink Modeling | Examples

7

Page 16: Matlab Tutorial

MATLAB - Tạo mô hìnhHệ thống xe lửaMô hình tách và định luật NewtonBiến trạng thái và các phương trình raBiểu diễn trong MATLAB

MATLAB có thể được dùng để mô tả hệ thống hoặc mô hình vật lý. Trong tài liệu này chúng ta sẽ họccách sử dụng phương trình vi phân để tạo mô hình trong MATLAB. Bây giờ chúng ta sẽ biểu diễn hệthống vật lý nhờ tập hợp các phương trình vi phân.

Hệ thống xe lửa

Giả thiết hệ thống chỉ có một đầu máy và một toa xe và chạy theo một hướng. Chúng ta cần điềukhiển xe sao cho nó khởi động và dừng êm và chạy với tốc độ không đổi.

Ký hiệu khối lượng của đầu máy và của toa lần lượt là M1 và M2, độ cứng của lò xo liên kết giữachúng là k, lực kéo của đầu máy là F và hệ số ma sát lăn tại các bánh xe là μ.

Mô hình tách và định luật Newton

Sau khi tách liên kết, mô hình hệ thống được biểu diễn như sau:

Từ định luật Newton, chúng ta biết rằng tổng các lực tác dụng lên vật bằng tích khối lượng của vật vớigia tốc của nó. Trong trường hợp này, hệ lực tác dụng lên M1 gồm lực lò xo, lực ma sát và lực kéo củađộng cơ. Hệ lực tác dụng lên M2 gồm lực lò xo và lực ma sát. Các lực tác dụng theo phương thẳngđứng, gồm trọng lực và phản lực vuông góc với mặt đường, cân bằng. Vì vậy không có gia tốc theophương thẳng đứng. Các phương trình chuyển động theo phương nằm ngang như sau:

1

Page 17: Matlab Tutorial

Biến trạng thái và các phương trình ra

Hệ phương trình trạng thái được xây dựng với các biến trạng thái, gồm các toạ độ X1, X2; vận tốc V1,V2 và thông số đầu vào là lực kéo F. Hệ phương trình có dạng sau:

Giả sử thông số ra của hệ thống là vận tốc của xe. Vì vậy phương trình ra sẽ là:

1. Hàm truyền

Để tìm hàm truyền của hệ thống, trước hết phải biểu diễn các phương trình vi phân dưới dạngLaplace.

Thông số ra Y(s) = V2(s) = s X2(s). Khử X1 để xuất hiện tỷ số Y(s)/F(s). Khi tìm hàm truyền, giảthiết rằng điều kiện đầu bằng 0. Hàm truyền có dạng sau:

2. Không gian trạng thái

Phương pháp khác để giải bài toán là sử dụng không gian trạng thái. Bốn ma trận A, B, C, D đặc trưngcho hệ thống sẽ được dùng để giải bàn toán. Dạng không gian trạng thái được tìm từ các biến trạngthái và phương trình thông số ra được biểu diễn như sau:

2

Page 18: Matlab Tutorial

Biểu diễn trong MATLAB

Bây giờ chúng ta sẽ đưa các phương trình trên vào m-file của MATLAB. Vì MATLAB không thể dùngcác biến ký tự, chúng ta gán giá trị cho các biến như sau:

M1 = 1 kgM2 = 0.5 kgk = 1 N/mF= 1 Nu = 0.002 sec/mg = 9.8 m/s^2

Chúng ta tạo mọt m-file với các biến sau:

M1=1;M2=0.5;k=1;F=1;u=0.002;g=9.8;

Để giải bài toán, chúng ta có 2 phương án: 1) Dùng hàm truyền, hoặc 2) Dùng không gian trạng thái.

Nếu dùng hàm truyền thì hãy thêm các dòng sau vào cuối m-file vừa tạo ra:

num=[M2 M2*u*g 1];den=[M1*M2 2*M1*M2*u*g M1*k+M1*M2*u*u*g*g+M2*k M1*k*u*g+M2*k*u*g];train=tf(num,den)

Nếu dùng không gian trạng thái thì thêm các lệnh sau, thay cho các ma trận num và den:

A=[ 0 1 0 0; -k/M1 -u*g k/M1 0; 0 0 0 1; k/M2 0 -k/M2 -u*g];B=[ 0;1/M1; 0; 0];C=[0 1 0 0];

3

Page 19: Matlab Tutorial

D=[0];train=ss(A,B,C,D)

Hãy xem cách nhập ma trận trong MATLAB cơ sở.

Tiếp tục giải bài toán

Khi hệ các phương trình vi phân mô tả hệ thống đã được nhập vào MATLAB dưới dạng hàm truyềnhoặc không gian trạng thái thì có thể nghiên cứu về hệ thống điều khiển kín hoặc hở.

Hầu hết bài toán có thể giải bằng cách sử dụng hàm truyền hoặc mô hình không gian trạng thái. Hơnnữa, có thể chuyển đổi giữa dạng này sang dạng khác. Phương pháp chuyển đổi được trình bày trongtrang Chuyển đổi.

Sau đây là danh sách 7 trang trình bày các ví dụ về tạo mô hình, bạn có thể link đến để nghiên cứu.

Modeling ExamplesCruise Control | Motor Speed | Motor Position | Bộ giảm xóc xe buýt | Inverted Pendulum |Pitch Controller | Ball and Beam

TutorialsMATLAB cơ sở | MATLAB - Tạo mô hình | PID | Quỹ tích nghiệm | Đáp ứng tần số | Không giantrạng thái | Điều khiển số | Simulink Cơ sở | Simulink - Tạo mô hình | Các ví dụ

4

Page 20: Matlab Tutorial

Ví dụ: Mô hình hệ điều khiển xe

Mô tả hệ thốngCác chỉ tiêu thiết kếMô hình MATLABĐáp ứng hệ kínHàm truyền mạch kín

Mô tả hệ thống

Mô hình điều khiển xe tương đối đơn giản. Nếu bỏ qua quán tính của các bánh xe và giả thiết rằng lựcma sát (tỷ lệ thuận với vận tốc của xe) tác dụng ngược chiều chuyển động của xe, thì mô hình trởthành mô hình khối lượng và giảm chấn như dưới đây.

Theo định luật Newton, nhận được hệ phương trình mô tả hệ thống như sau:

(1)

trong đó u là lực phát động của động cơ. Trong ví dụ này, chúng ta dùng các giá trị

m = 1000 kgb = 50N sec/m

u = 500 N

Các chỉ tiêu thiết kế

Hệ cần phải thoả mãn các chỉ tiêu thiết kế sau:. Khi lực kéo của động cơ bằng 500 N, xe sẽ đạt vận

1

Page 21: Matlab Tutorial

tốc lớn nhất là 10 m/s (22 mph) trong khoảng thời gian không quá 5 giây. Cho phép lượng quá điềukhiển tốc độ tới 10% và sai số tĩnh lớn nhất là 2%.

Thời gian gia tốc < 5 secQuá điều khiển tốc độ < 10%Sai số tĩnh < 2%

Mô hình MATLAB

1. Hàm truyền

Để tìm hàm truyền cần biến đổi hệ phương trình (1) sang Laplace. Khi xác định hàm truyền, cần giảthiết điều kiện đầu bằng 0. Dạng chuyển đổi Laplace của 2 phương trình như sau:

Vì vận tốc là thông số ra, ta thay V(s) bằng Y(s)

Vậy hàm truyền của hệ bằng

Để giải bài toán trong MATLAB, bạn copy đoạn lệnh sau vào m-file mới:

m=1000;b=50;u=500;num=[1];den=[m b];cruise=tf(num,den)

Lệnh này sẽ còn được dùng lại để tìm đáp ứng hệ kín của hệ thống trước tín hiệu vào dạng bậc thangđơn vị. Nhưng trước khi làm điều đó, ta cần xem xét mô hình không gian trạng thái.

2. Không gian trạng thái

Chúng ta viết lại hệ phương trình ban đầu (1) dưới dạng mô hình không gian trạng thái.

Muốn dùng MATLAB để giải bài toán, cần tạo m-file như sau:

m = 1000;b = 50;

2

Page 22: Matlab Tutorial

u = 500;A = [-b/m];B = [1/m];C = [1];D = 0;cruise=ss(A,B,C,D)

Ghi chú: Có thể chuyển đổi bài toán từ dạng không gian trạng thái sang dạng hàm truyền và ngượclại trong MATLAB. Chi tiết về chuyển đổi, xem Chuyển đổi

Đáp ứng hệ kín

Chúng ta hãy xem phản ứng hệ kín trước thông số vào là bậc thang đơn vị (step input). Thêm lệnh sauvào cuối m-file và chạy trong cửa sổ lệnh của MATLAB:

step(u*cruise)

Bạn sẽ nhận được đồ thị sau:

Từ đồ thị, ta thấy thời gian để xe đạt vận tốc 10 m/s vượt quá 100 giây. Điều đó không đạt yêu cầu vềthời gian tăng tốc (không quá 5 giây).

Hàm truyền mạch kín

Để cải thiện chất lượng điều khiển, ta tạo hệ điều khiển kín với mạch phản hồi đơn vị, có sơ đồ khốinhư hình sau.

Hàm truyền của đối tượng (plant) chính là hàm truyền đã xác định được ở trên {Y(s)/U(s)=1/ms+b}.Bộ điều khiển cần được thiết kế để thoả mãn các điều kiện đặt ra ban đầu. Có 4 phương pháp thiết kếbộ điều khiển được liệt kê ở cuối trang mà bạn có thể chọn, gồm PID (tỷ lệ - tích phân - vi phân),

3

Page 23: Matlab Tutorial

Root-locus (quỹ tích nghiệm), Frequency response (đáp ứng tần số), hoặc State-space (không giantrạng thái).

Các ví dụ về mô hình hoáCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Các ví dụ điều khiển xeModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB cơ sở | MATLAB - Tạo mô hình | PID | Quỹ tích nghiệm | Đáp ứng tần số | Không giantrạng thái | Điều khiển số | Simulink Cơ sở | Simulink - Tạo mô hình | Các ví dụ

4

Page 24: Matlab Tutorial

Ví dụ: Mô hình điều khiển tốc độ động cơ điện mộtchiều

Mô hình vật lý và hệ phương trìnhYêu cầu thiết kếBiểu diễn trong MATLAB và đáp ứng mạch kín

Mô hình vật lý và hệ phương trình

Động cơ điện một chiều (DC Motor) là thiết bị chấp hành được dùng phổ biến trong điều khiển. Nócung cấp chuyển động quay, và cùng với các cơ cấu truyền động cơ khí khác, như bánh răng, tangtrống, cáp,... có thể cho chuyển động tịnh tiến. Mạch điện phần ứng và sơ đồ tách của rotor như tronghình sau:

Giả thiết các thông số vật lý của hệ thống như sau.

* Moment quán tính của rotor (J) = 0.01 kg.m^2/s^2 * Hệ số giảm chấn của hệ thống cơ khí (b) = 0.1 Nms * Hằng số điện cơ (K=Ke=Kt) = 0.01 Nm/Amp * Điện trở (R) = 1 ohm * Điện cảm (L) = 0.5 H * Input (V): điện áp nguồn * Output (theta): vị trí của trục * Giả thiết rotor và trục cứng vững tuyệt đối

Mô men trên trục, T, có quan hệ với dòng điện phần ứng, i, thông qua hằng số Kt. Suất điện độngphần ứng, e, quan hệ với tốc độ quay qua các phương trình:

1

Page 25: Matlab Tutorial

Trong hệ đơn vị SI (mà chúng ta sẽ dùng), Kt (hằng số phần ứng) bằng Ke (hằng số motor) và đượcký hiệu chung là K.

Từ hình vẽ trên, chúng ta có thể viết các phương trình dựa trên định luật Newton, kết hợp với địnhluật Kirchhoff:

1. Hàm truyền

Sau biến đổi Laplace, mô hình hệ thống có dạng.

Bằng cách khử I(s) chúng ta nhận được hàm truyền mạch hở, trong đó, điện áp nguồn là thông số vàovà tốc độ quay của trục là thông số ra.

2. Không gian trạng thái

Dưới dạng không gian trạng thái, có thể biểu diễn các phương trình trên bằng cách chọn tốc độ quayvà dòng điện làm các biến hệ thống, điện áp nguồn làm input và tốc độ quay làm output.

Yêu cầu thiết kế

Thoạt đầu động cơ chỉ có thể quay với tốc độ 0.1 rad/sec với điện áp vào là 1 V (ta sẽ thấy khi môphỏng đáp ứng mạch hở). Yêu cầu cơ bản đối với động cơ là quay với vận tốc yêu cầu và sai số tĩnhdưới 1%. Yêu cầu khác về năng suất là thời gian để động cơ phải đạt tới vận tốc ổn định sau khi khởiđộng là không quá 2 giây. Để tránh sự cố do tốc độ động cơ quá cao, cần hạn chế lượng quá điềukhiển nhỏ hơn 5%.

Nếu chúng ta cấp điện áp vào dưới dạng bậc thang đơn vị thì tốc độ quay (output) phải đạt các yêucầu:

Thời gian đạt vận tốc ổn định dưới 2 giâyQuá điều khiển dưới 5%

2

Page 26: Matlab Tutorial

Sai số tĩnh dưới 1%

Biểu diễn trong MATLAB và đáp ứng mạch hở

1. Hàm truyền

Chúng ta có thể biểu diễn hàm truyền nói trên trong MATLAB bằng cách định nghĩa các ma trận tử sốvà mẫu số như sau:

Tạo m-file mới và nhập các lệnh:

J=0.01;b=0.1;K=0.01;R=1;L=0.5;num=K;den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2)];motor=tf(num,den);

Bây giờ chúng ta sẽ xem hệ thống hở ban đầu được hình thành như thế nào. Thêm các lệnh sau vàocuối m-file và chạy nó trong cửa sổ lệnh của MATLAB:

step(motor,0:0.1:3);title('Step Response for the Open Loop System');

Ta sẽ nhận được đồ thị sau:

Từ đồ thị, ta nhận thấy khi đặt điện áp 1 V vào động cơ thì nó chỉ đạt vận tốc tối đa là 0.1 rad/s, nhỏhơn 10 lần so với vận tốc yêu cầu. Hơn nữa, thời gian để động cơ đạt vận tốc ổn định kéo dài tới 3 s.

3

Page 27: Matlab Tutorial

Điều đó cũng không thoả mãn yêu cầu về thời gian gia tốc.

2. Không gian trạng thái

Chúng ta cũng có thể biểu diễn hệ thống nhờ mô hình không gian trạng thái. Hãy chạy thử đoạn lệnhtrong m-file sau:

J=0.01;b=0.1;K=0.01;R=1;L=0.5;A=[-b/J K/J -K/L -R/L];B=[0 1/L];C=[1 0];D=0;motor_ss=ss(A,B,C,D);

step(motor_ss)

Chạy m-file trong cửa sổ lệnh của MATLAB, bạn sẽ nhận được đúng kết quả như trên.

Modeling ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Motor Speed ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control: PID |Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

4

Page 28: Matlab Tutorial

Example: Modeling DC Motor PositionPhysical SetupSystem EquationsDesign RequirementsMATLAB Representation and Open-Loop Response

Physical Setup

A common actuator in control systems is the DC motor. Itdirectly provides rotary motion and, coupled with wheels ordrums and cables, can provide transitional motion. Theelectric circuit of the armature and the free body diagram ofthe rotor are shown in the following figure:

For this example, we will assume the following values for the physical parameters. These values werederived by experiment from an actual motor in Carnegie Mellon's undergraduate controls lab.

* moment of inertia of the rotor (J) = 3.2284E-6 kg.m^2/s^2* damping ratio of the mechanical system (b) = 3.5077E-6 Nms* electromotive force constant (K=Ke=Kt) = 0.0274 Nm/Amp

* electric resistance (R) = 4 ohm* electric inductance (L) = 2.75E-6 H

* input (V): Source Voltage* output (theta): position of shaft

* The rotor and shaft are assumed to be rigid

System Equations

The motor torque, T, is related to the armature current, i, by a constant factor Kt. The back emf, e, isrelated to the rotational velocity by the following equations:

1

Page 29: Matlab Tutorial

In SI units (which we will use), Kt (armature constant) is equal to Ke (motor constant).

From the figure above we can write the following equations based on Newton's law combined withKirchhoff's law:

1. Transfer Function

Using Laplace Transforms the above equations can be expressed in terms of s.

By eliminating I(s) we can get the following transfer function, where the rotating speed is the outputand the voltage is an input.

However during this example we will be looking at the position, as being the output. We can obtainthe position by integrating Theta Dot, therefore we just need to divide the transfer function by s.

2. State Space

These equations can also be represented in state-space form. If we choose motor position, motorspeed, and armature current as our state variab, we can write the equations as follows:

Design requirements

We will want to be able to position the motor very precisely, thus the steady-state error of the motorposition should be zero. We will also want the steady-state error due to a disturbance, to be zero as

2

Page 30: Matlab Tutorial

well. The other performance requirement is that the motor reaches its final position very quickly. Inthis case, we want it to have a settling time of 40ms. We also want to have an overshoot smaller than16%.

If we simulate the reference input (R) by a unit step input, then the motor speed output should have:

Settling time less than 40 millisecondsOvershoot less than 16%No steady-state errorNo steady-state error due to a disturbance

MATLAB representation and open-loop response

1. Transfer Function

We can put the transfer function into MATLAB by defining the numerator and denominator as vectors:

Create a new m-file and enter the following commands:

J=3.2284E-6;b=3.5077E-6;K=0.0274;R=4;L=2.75E-6;num=K;den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2) 0];motor=tf(num,den);

Now let's see how the original open-loop system performs. Add the following command onto the endof the m-file and run it in the MATLAB command window:

step(motor,0:0.001:0.2)

You should get the following plot:

From the plot we see that when 1 volt is applied to the system, the motor position changes by 6

3

Page 31: Matlab Tutorial

radians, six times greater than our desired position. For a 1 volt step input the motor should spinthrough 1 radian. Also, the motor doesn't reach a steady state which does not satisfy our designcriteria

2. State Space

We can put the state space equations into MATLAB by defining the system's matrices as follows:

J=3.2284E-6;b=3.5077E-6;K=0.0274;R=4;L=2.75E-6;

A=[0 1 00 -b/J K/J0 -K/L -R/L];B=[0 ; 0 ; 1/L];C=[1 0 0];D=[0]; motor=ss(A,B,C,D);

The step response is obtained using the command

step(motor)

Modeling ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Motor Position ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control:RL| Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

4

Page 32: Matlab Tutorial

Example: Modeling a Bus Suspension System usingTransfer Functions

Physical setupDesign requirementsEquations of motionTransfer function equationEntering equations into MATLABOpen-loop responseControl Block DiagramState Space Method

Physical setup

Designing an automatic suspension system for a bus turns out to be an interesting control problem. When thesuspension system is designed, a 1/4 bus model (one of the four wheels) is used to simplify the problem to a onedimensional spring-damper system. A diagram of this system is shown below:

Where:

* body mass (m1) = 2500 kg,* suspension mass (m2) = 320 kg,

* spring constant of suspension system(k1) = 80,000 N/m,* spring constant of wheel and tire(k2) = 500,000 N/m,

* damping constant of suspension system(b1) = 350 Ns/m.* damping constant of wheel and tire(b2) = 15,020 Ns/m.

* control force (u) = force from the controller we are going to design.

Design requirements:

A good bus suspension system should have satisfactory road holding ability, while still providing comfort when

1

Page 33: Matlab Tutorial

riding over bumps and holes in the road. When the bus is experiencing any road disturbance (i.e. pot holes, cracks,and uneven pavement),the bus body should not have large oscillations, and the oscillations should dissipatequickly. Since the distance X1-W is very difficult to measure, and the deformation of the tire (X2-W) is negligible,we will use the distance X1-X2 instead of X1-W as the output in our problem. Keep in mind that this is anestimation.

The road disturbance (W) in this problem will be simulated by a step input. This step could represent the buscoming out of a pothole. We want to design a feedback controller so that the output (X1-X2) has an overshoot lessthan 5% and a settling time shorter than 5 seconds. For example, when the bus runs onto a 10 cm high step, thebus body will oscillate within a range of +/- 5 mm and return to a smooth ride within 5 seconds.

Equations of motion:

From the picture above and Newton's law, we can obtain the dynamic equations as the following:

Transfer Function Equation:

Assume that all of the initial condition are zeroes, so these equations represent the situation when the bus wheelgoes up a bump. The dynamic equations above can be expressed in a form of transfer functions by taking LaplaceTransform of the above equations. The derivation from above equations of the Transfer Functions G1(s) andG2(s) of output,X1-X2, and two inputs,U and W, is as follows.

Find the inverse of matrix A and then multiple with inputs U(s)and W(s) on the right hand side as the following:

When we want to consider the control input U(s) only, we set W(s) = 0. Thus we get the transfer function G1(s)as the following:

When we want to consider the disturbance input W(s) only, we set U(s) = 0. Thus we get the transfer functionG2(s) as the following:

2

Page 34: Matlab Tutorial

Entering equations into MATLAB

We can put the above Transfer Function equations into MATLAB by defining the numerator and denominator ofTransfer Functions in the form, nump/denp for actuated force input and num1/den1 for disturbance input, of thestandard transfer function G1(s) and G2(s):

G1(s) = nump/denp

G2(s) = num1/den1

Now, let's create a new m-file and enter the following code:

m1=2500;m2=320;k1=80000;k2=500000;b1 = 350;b2 = 15020;

nump=[(m1+m2) b2 k2];denp=[(m1*m2) (m1*(b1+b2))+(m2*b1) (m1*(k1+k2))+(m2*k1)+(b1*b2) (b1*k2)+(b2*k1) k1*k2];P=tf(nump,denp);

num1=[-(m1*b2) -(m1*k2) 0 0];den1=[(m1*m2) (m1*(b1+b2))+(m2*b1) (m1*(k1+k2))+(m2*k1)+(b1*b2) (b1*k2)+(b2*k1) k1*k2];G2=tf(0.1*num1,den1);

Open-loop response

We can use MATLAB to display how the original open-loop system performs (without any feedback control). Addthe following commands into the m-file and run it in the MATLAB command window to see the response of unitstep actuated force input and unit step disturbance input. Note that the step command will generate the unit stepinputs for each input.

step(P)

From this graph of the open-loop response for a unit step actuated force, we can see that the system is under-damped. People sitting in the bus will feel very small amount of oscillation and the steady-state error is about0.013 mm. Moreover, the bus takes an unacceptably long time to reach the steady state (the settling time is verylarge). The solution to this problem is to add a feedback controller to the system.

3

Page 35: Matlab Tutorial

step(G2)

To see some details, you can change the axis:

axis([0 10 -.1 .1])

From this graph of open-loop response for 0.1 m step disturbance, we can see that when the bus passes a 10 cmhigh bump on the road, the bus body will oscillate for an unacceptably long time(100 seconds) with largeramplitude, 13 cm, than the initial impact. People sitting in the bus will not be comfortable with such an oscillation.The big overshoot (from the impact itself) and the slow settling time will cause damage to the suspension system.The solution to this problem is to add a feedback controller into the system to improve the performance. Theschematic of the closed-loop system is the following:

4

Page 36: Matlab Tutorial

From the above transfer functions and schematic, we can draw the bus-system block diagram as the following:

From the schematic above we see that:

Plant = nump/denp

F * Plant=num1/den1

so that

F=num1/(den1*Plant)

Modeling ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | Pitch Controller | Balland Beam

Bus Suspension ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

5

Page 37: Matlab Tutorial

Example: Modeling an Inverted PendulumProblem setup and design requirementsForce analysis and system equationsMATLAB representation and the open-loop response

Problem setup and design requirements

The cart with an inverted pendulum, shown below, is "bumped" with an impulse force, F. Determinethe dynamic equations of motion for the system, and linearize about the pendulum's angle, theta = Pi(in other words, assume that pendulum does not move more than a few degrees away from thevertical, chosen to be at an angle of Pi). Find a controller to satisfy all of the design requirementsgiven below.

For this example, let's assume that

M mass of the cart 0.5 kgm mass of the pendulum 0.2 kgb friction of the cart 0.1 N/m/secl length to pendulum center of mass 0.3 mI inertia of the pendulum 0.006 kg*m^2F force applied to the cartx cart position coordinatetheta pendulum angle from vertical

For the PID, root locus, and frequency response sections of this problem we will be only interested inthe control of the pendulum's position. This is because the techniques used in these tutorials can onlybe applied for a single-input-single-output (SISO) system. Therefore, none of the design criteria dealwith the cart's position. For these sections we will assume that the system starts at equilibrium, andexperiences an impulse force of 1N. The pendulum should return to its upright position within 5seconds, and never move more than 0.05 radians away from the vertical.

1

Page 38: Matlab Tutorial

The design requirements for this system are:

Settling time of less than 5 seconds.Pendulum angle never more than 0.05 radians from the vertical.

However, with the state-space method we are more readily able to deal with a multi-output system.Therefore, for this section of the Inverted Pendulum example we will attempt to control both thependulum's angle and the cart's position. To make the design more challenging we will be applying astep input to the cart. The cart should achieve its desired position within 5 seconds and have a risetime under 0.5 seconds. We will also limit the pendulum's overshoot to 20 degrees (0.35 radians), andit should also settle in under 5 seconds.

The design requirements for the Inverted Pendulum state-space example are:

Settling time for x and theta of less than 5 seconds.Rise time for x of less than 0.5 seconds.Overshoot of theta less than 20 degrees (0.35 radians).

Force analysis and system equations

Below are the two Free Body Diagrams of the system.

Summing the forces in the Free Body Diagram of the cart in the horizontal direction, you get thefollowing equation of motion:

Note that you could also sum the forces in the vertical direction, but no useful information would begained.

Summing the forces in the Free Body Diagram of the pendulum in the horizontal direction, you can getan equation for N:

If you substitute this equation into the first equation, you get the first equation of motion for thissystem:

2

Page 39: Matlab Tutorial

(1)

To get the second equation of motion, sum the forces perpendicular to the pendulum. Solving thesystem along this axis ends up saving you a lot of algebra. You should get the following equation:

To get rid of the P and N terms in the equation above, sum the moments around the centroid of thependulum to get the following equation:

Combining these last two equations, you get the second dynamic equation:

(2)

Since MATLAB can only work with linear functions, this set of equations should be linearized abouttheta = Pi. Assume that theta = Pi + ( represents a small angle from the vertical upward direction).Therefore, cos(theta) = -1, sin(theta) = - , and (d(theta)/dt)^2 = 0. After linearization the twoequations of motion become (where u represents the input):

1. Transfer Function

To obtain the transfer function of the linearized system equations analytically, we must first take theLaplace transform of the system equations. The Laplace transforms are:

Since we will be looking at the angle Phi as the output of interest, solve the first equation for X(s),

then substitute into the second equation, and re-arrange. The transfer function is:

3

Page 40: Matlab Tutorial

where,

From the transfer function above it can be seen that there is both a pole and a zero at the origin. Thesecan be canceled and the transfer function becomes:

2. State-Space

After a little algebra, the linearized system equations equations can also be represented in state-spaceform:

The C matrix is 2 by 4, because both the cart's position and the pendulum's position are part of theoutput. For the state-space design problem we will be controlling a multi-output system so we will beobserving the cart's position from the first row of output and the pendulum's with the second row.

MATLAB representation and the open-loop response

1. Transfer Function

4

Page 41: Matlab Tutorial

The transfer function found from the Laplace transforms can be set up using MATLAB by inputting thenumerator and denominator as vectors. Create an m-file and copy the following text to model thetransfer function:

M = .5;m = 0.2;b = 0.1;i = 0.006;g = 9.8;l = 0.3;

q = (M+m)*(i+m*l^2)-(m*l)^2; %simplifies input

num = [m*l/q 0];den = [1 b*(i+m*l^2)/q -(M+m)*m*g*l/q -b*m*g*l/q];pend=tf(num,den)

Your output should be:

Transfer function: 4.545 s----------------------------------s^3 + 0.1818 s^2 - 31.18 s - 4.455

To observe the system's velocity response to an impulse force applied to the cart add the followinglines at the end of your m-file:

t=0:0.01:5;impulse(pend,t)axis([0 1 0 60])

You should get the following velocity response plot:

As you can see from the plot, the response is entirely unsatisfactory. It is not stable in open loop. Youcan change the axis to see more of the response if you need to convince yourself that the system isunstable.

Although the output amplitude increases past 60 radians (10 revolutions), the model is only valid forsmall . In actuality, the pendulum will stop rotating when it hits the cart ( =90 degree).

5

Page 42: Matlab Tutorial

2. State-Space

Below, we show how the problem would be set up using MATLAB for the state-space model. If youcopy the following text into a m-file (or into a '.m' file located in the same directory as MATLAB) andrun it, MATLAB will give you the A, B, C, and D matrices for the state-space model and a plot of theresponse of the cart's position and pendulum angle to a step input of 0.2 m applied to the cart.

M = .5;m = 0.2;b = 0.1;i = 0.006;g = 9.8;l = 0.3;

p = i*(M+m)+M*m*l^2; %denominator for the A and B matricesA = [0 1 0 0; 0 -(i+m*l^2)*b/p (m^2*g*l^2)/p 0; 0 0 0 1; 0 -(m*l*b)/p m*g*l*(M+m)/p 0]B = [ 0; (i+m*l^2)/p; 0; m*l/p]C = [1 0 0 0; 0 0 1 0]D = [0; 0]pend=ss(A,B,C,D);T=0:0.05:10;U=0.2*ones(size(T));[Y,T,X]=lsim(pend,U,T);plot(T,Y)axis([0 2 0 100])

You should see the following output after running the m-file:

The blue line represents the cart's position and the green line represents the pendulum's angle. It isobvious from this plot and the one above that some sort of control will have to be designed to improvethe dynamics of the system. Several example controllers are included with these tutorials; select frombelow the one you would like to use.

6

Page 43: Matlab Tutorial

Note: The solutions shown in the PID, root locus and frequency response examples may not yield aworkable controller for the inverted pendulum problem. As stated previously, when we put thisproblem into the single-input, single-output framework, we ignored the x position of the cart. Thependulum can be stabilized in an inverted position if the x position is constant or if the cart moves at aconstant velocity (no acceleration). Where possible in these examples, we will show what happens tothe cart's position when our controller is implemented on the system. We emphasize that the purposeof these examples is to demonstrate design and analysis techniques using MATLAB; not to actuallycontrol an inverted pendulum.

Modeling ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball & Beam

Inverted Pendulum ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

7

Page 44: Matlab Tutorial

Example: Modeling a Pitch ControllerPhysical setup and system equationsDesign requirementsTransfer function and state-spaceMATLAB representation and open-loop responseClosed-loop transfer function

Physical setup and system equations

The equations governing the motion of an aircraft are a very complicated set of six non-linear coupleddifferential equations. However, under certain assumptions, they can be decoupled and linearized intothe longitudinal and lateral equations. Pitch control is a longitudinal problem, and in this example, wewill design an autopilot that controls the pitch of an aircraft.

The basic coordinate axes and forces acting on an aircraft are shown in the figure below:

Assume that the aircraft is in steady-cruise at constant altitude and velocity; thus, the thrust and dragcancel out and the lift and weight balance out each other. Also, assume that change in pitch angle doesnot change the speed of an aircraft under any circumstance (unrealistic but simplifies the problem abit). Under these assumptions, the longitudinal equations of motion of an aircraft can be written as:

(1)

Please refer to any aircraft-related textbooks for the explanation of how to derive these equations.Also, click Variables to see what each variable represents.

For this system, the input will be the elevator deflection angle, and the output will be the pitch angle.

1

Page 45: Matlab Tutorial

Design requirements

The next step is to set some design criteria. We want to design a feedback controller so that the outputhas an overshoot of less than 10%, rise time of less than 2 seconds, settling time of less than 10seconds, and steady-state error of less than 2%. For example, if the input is 0.2 rad (11 degrees), thenthe pitch angle will not exceed 0.22 rad, reaches 0.2 rad within 2 seconds, settles to 2% of thesteady-state within 10 seconds, and stays within 0.196 to 0.204 rad at the steady-state.

Overshoot: Less than 10%Rise time: Less than 2 secondsSettling time: Less than 10 secondsSteady-state error: Less than 2%

Transfer function and the state-space

Before finding transfer function and the state-space model, let's plug in some numerical values tosimplify the modeling equations (1) shown above.

(2)

These values are taken from the data from one of Boeing's commercial aircraft.

1. Transfer function

To find the transfer function of the above system, we need to take the Laplace transform of the abovemodeling equations (2). Recall from your control textbook, when finding a transfer function, zeroinitial conditions must be assumed. The Laplace transform of the above equations are shown below.

After few steps of algebra, you should obtain the following transfer function.

2. State-space

Knowing the fact that the modeling equations (2) are already in the state-variable form, we canrewrite them into the state-space model.

2

Page 46: Matlab Tutorial

Since our output is the pitch angle, the output equation is:

MATLAB representation and open-loop response

Now, we are ready to observe the system characteristics using MATLAB. First, let's obtain anopen-loop system to a step input and determine which system characteristics need improvement. Letthe input (delta e) be 0.2 rad (11 degrees). Create an new m-file and enter the following commands.

de=0.2;

num=[1.151 0.1774];den=[1 0.739 0.921 0];pitch=tf(num,den);step(de*pitch)axis([0 15 0 0.8])

Running this m-file in the MATLAB command window should give you the following plot.

From the plot, we see that the open-loop response does not satisfy the design criteria at all. In fact theopen-loop response is unstable.

If you noticed, the above m-file uses the numerical values from the transfer function. To use the

3

Page 47: Matlab Tutorial

state-space model, enter the following commands into a new m-file (instead of the one shown above)and run it in the command window.

de=0.2;

A=[-0.313 56.7 0; -0.0139 -0.426 0; 0 56.7 0];B=[0.232; 0.0203; 0];C=[0 0 1];D=[0];pitch=ss(A,B,C,D);step(de*pitch)axis([0 15 0 0.8])

You should get the same response as the one shown above.

Note: It is possible to convert from the state-space to transfer function, or vice versa using MATLAB.To learn more about conversions, see Conversions

Closed-loop transfer function

To solve this problem, a feedback controller will be added to improve the system performance. Thefigure shown below is the block diagram of a typical unity feedback system.

A controller needs to be designed so that the step response satisfies all design requirements. Severaldifferent methods to design a controller are listed at the bottom of this page.

Modeling ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Pitch Controller ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control| Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

4

Page 48: Matlab Tutorial

Ví dụ: Mô hình quả bóng và thanh đỡThiết lập bài toánPhương trình hệ thốngBiểu diễn đáp ứng của hệ thống hở trong Matlab

Thiết lập bài toán

Một quả bóng đặt trên thanh đỡ như hình bên dưới, ở đây quả bóng được lăn trên thanh đỡ, đó là mộtbậc tự do. Một tay quay được gắn 1 đầu vào thanh đỡ, đầu kia gắn vào động cơ. Khi động cơ quay 1góc teta, tay đòn sẽ làm cho thanh đỡ quay 1 góc alpha. Khi thanh đỡ thay đổi góc từ vị trí cân bằng,trọng lực sẽ khiến quả bóng lăn trên thanh đỡ. Ta cần thiết kế một bộ điều khiển để kiểm soát vị trícủa quả bóng.

Với bài toán này, chúng ta giả thiết quả bóng lăn không trượt trên thanh đỡ và ma sát giữa bóng vàthanh là không đáng kể. Các tham số và biến cho bài toán này xác định như sau:

M khối lượng của bóng 0.11 kgR bán kính của bóng 0.015 md tay quay 0.03 mg gia tốc trọng trường 9.8 m/s^2L chiều dài thanh đỡ 1.0 mJ momen quán tính của bóng 9.99e-6 kgm^2r toạ độ của bóngalpha toạ độ góc của thanh đỡtheta góc quay của động cơ

1

Page 49: Matlab Tutorial

Mục tiêu đề ra để điều khiển:

Thời gian quá độ không quá 3 giâyĐộ quá điều chỉnh nhỏ hơn 5%

Phương trình hệ thống

Đạo hàm bậc hai của góc quay alpha trên thực tế sẽ làm thay đổi toạ độ r. Tuy nhiên, chúng ta bỏ quađiều này. Phương trình Lagrange dịch chuyển của bóng được viết như sau:

Tuyến tính hoá góc quay của alpha (alpha = 0) cho ta phương trình gần đúng sau:

Phương trình mô tả mối liên hệ giữa góc quay của thanh đỡ và góc quay của động cơ viết gần đúngnhư sau:

Thay vào phương trình trước, ta được phương trình:

1. Hàm truyền

Biến đổi Laplace phương trình trên ta được phương trình mới:

Viết lại dưới dạng hàm truyền giữa góc quay của động cơ teta(s) và toạ độ dich chuyển của bóng R(s)ta có hàm truyền.

2

Page 50: Matlab Tutorial

Chú ý hàm truyền của cơ cấu chấp hành ở đây là tích phân cấp hai. Do vậy nó ở biên ổn định và sẽ rấtphức tạp để có thể điều khiển.

2. Không gian trạng thái

Phương trình tuyến tính hoá của hệ cũng có thể biểu diễn bằng không gian trạng thái. Điều này thựchiện bằng cách chọn toạ độ r và vận tốc r chấm làm biến trạng thái, góc quay teta làm đầu vào. Khônggian trạng thái được biểu diễn như sau :

Tuy nhiên, với ví dụ nay ta biểu diễn hơi khác đị một chút. Phương trình cho bóng vẫn giữ nguyênnhưng thay vì điều khiển toạ độ bóng theo góc quay teta của động cơ ta sẽ điều khiển momen quaycủa thanh đỡ. Dưới đây là phương trình biểu diễn của không gian trạng thái:

Chú ý: Với hệ thống mới này ta coi như không có tay quay và động cơ, thay vào đó là một động cơgắn vào giữa thanh đỡ để tạo momen quay điều khiển toạ độ bóng.

3

Page 51: Matlab Tutorial

Biểu diễn trong Matlab và khảo sát đáp ứng của hệ thống hở

1. Hàm truyền

Hàm truyền sau khi biến đổi Laplace có thể biểu diễn trong Matlab bằng cách khai báo tử số và mẫusố như hai vector. Để làm điều này ta tạo một m-file có các lệnh như sau:

m = 0.111;R = 0.015;g = -9.8;L = 1.0;d = 0.03;J = 9.99e-6;

K = (m*g*d)/(L*(J/R^2+m)); %simplifies input

num = [-K];den = [1 0 0];ball=tf(num,den)

Hàm truyền cuối cùng se là:

Transfer function:0.21----s^2

Bây giừo chúng ta quan sát xem quả bóng sẽ lăn như thế nào khi đầu vào là tín hiệu bậc thang 0.25 m.Thêm vào m-file lệnh sau:

step(0.25*ball)

Ta sẽ có toạ độ dịch chuyển của bóng theo thời gian như sau:

Từ đồ thị trên ta thấy rằng hệ thống hở là không ổn định, bóng sẽ lăn ra khỏi thanh đỡ. Do vậy ta cần

4

Page 52: Matlab Tutorial

một số phương pháp để điều khiển toạ độ bóng. Bạn đọc có thể chọn trong 3 phương pháp là PID,Quỹ tích nghiệm (Root Locus), và Đáp ứng tần số (Frequency Response).

2. Không gian trạng thái

Không gian trạng thái được biểu diễn trong Matlab với các lệnh sau đây (các phương trình này dùngcho điều khiển momen quay như đã đề cập ở trên).

m = 0.111;R = 0.015;g = -9.8;J = 9.99e-6;

H = -m*g/(J/(R^2)+m); A=[0 1 0 0 0 0 H 0 0 0 0 1 0 0 0 0];B=[0;0;0;1];C=[1 0 0 0];D=[0];ball=ss(A,B,C,D);

Đáp ứng với đầu vào tín hiệu bậc thang 0,25m có được sau khi thực hiện lệnh:

step(0.25*ball)

Đầu ra theo thời gian có dạng sau:

Cũng giống như đồ thị có được từ hàm truyền ta thấy rằng hệ thống hở là không ổn định, bóng sẽ lănra khỏi thanh đỡ. Do vậy ta cần một số phương pháp để điều khiển toạ độ bóng. Các ví dụ về khônggian trạng thái sẽ cho bạn một số cách để điều khiển điểu hình.

Nếu bạn muốn biết cách làm sao để chuyển từ biểu diễn trong không gian trạng thái sang biểu diễntheo hàm truyền tham khảo phần Chuyển đổi.

5

Page 53: Matlab Tutorial

Các mô hình ví dụĐiều khiển xe | Điều khiển tốc độ động cơ | Điều khiển góc quay động cơ | Bus Suspension |Điều khiển con lắc ngược | Pitch Controller | Bài toán quả bóng và thanh đỡ

Ball & Beam ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

6

Page 54: Matlab Tutorial

PIDGiới thiệuBa luật điều khiểnĐặc tính của từng luật điều khiển P, I, và DCác ví dụ

Đáp ứng bậc thang đơn vị của hệ thống vòng hởĐiều khiển tỉ lệPĐiều khiển tỉ lệ-vi phânPĐiều khiển tỉ lệ-tích phânĐiều khiển tỉ lệ-vi phân-tích phân

Những gợi ý chung để thiết kế bộ điều khiển PID

Lệnh dùng trong MATLAB để tìm hiểu về phần này là: step feedback

Giới thiệu

Phần này sẽ cho các bạn biết về đặc tính của từng luật điều khiển tỉ lệ(P), vi phân(D) và tích phân(I)và cách dùng chúng để có được đáp ứng mong muốn. Ta xét 1 hệ thống như sau:

Plant: Là 1 cơ cấu phấp hành cần điều khiểnController: Đưa ra những kích thích cho plant và được thiết kế để điều khiển toàn bộ hệ thống

Ba luậtđiều khiển

The hàm truyền của phương pháp điều khiển PID có dạng như sau:

1

Page 55: Matlab Tutorial

Kp = Hệ số tỉ lệKI = Hệ số tích phânKd = Hệ số vi phân

Trước tiên, ta tìm hiểu xem bộ điều khiển PID làm việc như thế nào, ta lấy sơ đồ hệ thống ở trên. Biếne thể hiện cho sai số giữa đầu vào mong muốn R và đầu ra chấp hành Y. Tín hiệu lệch này sẽ được gửiđến bộ điều khiển PID và bộ điều khiển PID sẽ tính được tích phân và vi phân của sai số. Tín hiệuđiều khiển u có giá trị bằng Kp lần biên độ của sai số cộng với Ki lần tích phân của sai số cộng với Kdlần vi phân của sai số.

Tín hiệu u sẽ được gửi tới cơ câu chấp hành, và cho ra đầu ra Y. Đầu ra Y sẽ được gửi đến sensor đovà ta lại có giá trị sai số e mới. Bộ điều khiển sẽ lại lấy giá trị sai số mới, tính toán tích phân, vi phânvà lại đưa ra tín hiệu điều khiển. Quá trình này sẽ được lặp đi lặp lại.

Đặc tính của luật điều khiển P, I, và D

Luật điều khiển P có tác dụng làm giảm thời gian quá độ nhưng không thể khử được steady-stateerror. Luật điều khiển I có tác dụng khử được steady-state error, nhưng nó làm giảm khả năng đáp ứngtức thời của hệ thống. Luật điều khiển D có tác dụng tăng độ ổn định của hệ thống giảm overshoot, vàcải thiện khả năng đáp ứng tức thời. Hiệu quả của từng luật điều khiển P, I, và D lên hệ thống vòngkín được tổng kết qua bảng sau.

.

CL RESPONSE RISE TIME OVERSHOOT SETTLING TIME S-S ERROR

Kp Giảm Tăng Ít thay đổi Giảm

Ki Giảm Tăng Tăng Khử đượcKd Ít thay đổi Giảm Giảm Ít thay đổi

Nên nhớ sự tương quan này không hoàn toàn tuyệt đối, vì các giá trị Kp, Ki, và Kd là phụ thuộc vàonhau. Trên thực tế, khi thay đổi giá trị của hê số luật điều khiển này sẽ làm thay đổi hiệu quả tác độngcủa luật kia. Vì vậy bảng trên chỉ là để tham khảo để trong quá trình thiết kế ta có thể chọn Ki, Kp vàKd.

Ví dụ

Giả sử ta có 1 hệ khối lượng, lò xo và chống rung như sau.

2

Page 56: Matlab Tutorial

Phương trình động lực học của hệ thống trên là

(1)

Biến đổi Laplace từ (1), ta có

Hàm truyền giữa dịch chuyển X(s) và đầu vào F(s) bây giờ là

Lấy các giá trị

M = 1kgb = 10 N.s/mk = 20 N/mF(s) = 1

Lắp các giá trị trên vào hàm truyền ta có

Mục đích của ví dụ này là minh hoạ cho việc chọn Kp, Ki và Kd sao cho

Quá độ nhanhOvershoot nhỏ nhấtKhông có steady-state error

Đáp ứng bậc thang đơn vị của hệ thống hở

Trước hết ta khảo sát đáp ứng bậc thang đơn vị của hệ thống hở. Tạo một m-file có các lệnh như sau:

num=1;den=[1 10 20];plant=tf(num,den);step(plant)

3

Page 57: Matlab Tutorial

Chạy m-file này ta sẽ có đồ thị như sau.

Giá trị DC gain của hàm truyền là 1/20, do vậy 0.05 là giá trị cuối của output đáp ứng đầu vào bậcthang đơn vị. Như vậy steady-state error là 0.95, thực sự là khá lớn. Hơn nữa, thời gian quá độ khoảng1 giây, thời gian để ổn định khoảng 1,5 giây. Bây giờ nhiệm vụ của ta là thiết kế bộ điều khiển sao chogiảm thời gian quá độ, thời gian đến ổn định ngắn, và khử được steady-state error.

Luật điều khiển P

Chúng ta đã biết luật điều khiển P làm giảm thời gian quá độ, tăng overshoot, và giảm steady-stateerror. Hàm truyền điều khiển vòng kín với luật điều khiển P bây giờ là:

Chọn Kp = 300 và thêm vào m-file đoạn mã lệnh sau:

Kp=300;contr=Kp;sys_cl=feedback(contr*plant,1);t=0:0.01:2;step(sys_cl,t)

Chạy m-file trong MATLAB ta được kết quả như sau.

4

Page 58: Matlab Tutorial

Chú ý: Hàm feedback dùng để tạo một hàm truyền vòng kín từ một hàm truyền vòng hở cho trước(thay cho việc thiết lập lại bằng tay).

Từ đồ thị trên ta thấy rằng luật điều khiển P làm giảm thời gian quá độvà steady-state error, nhưngtăng độ quá điều chỉnh, và làm kéo dài thời gian đến ổn định đi 1 chút.

Điều khiển tỉ lệ-vi phân

Bây giờ chúng ta xét đến luật điều khiển PD. Như bảng đã nêu ở phần trước, ta thấy rằng luật điềukhiển D làm giảm được độ quá điều chỉnh và làm hệ thống nhanh đến ổn định. Hàm truyền vòng kínvới luật điều khiển PD bây giờ là:

Như trước ta vẫn lấy Kp = 300, lấy Kd = 10. Như trước ta thêm vào m-file đoạn mã lệnh sau và chạycho ra đồ thị.

Kp=300;Kd=10;contr=tf([Kd Kp],1);sys_cl=feedback(contr*plant,1);t=0:0.01:2;step(sys_cl,t)

5

Page 59: Matlab Tutorial

Đồ thị này cho ta thấy ngay luật điều khiển D đã giảm được độ quá điều chỉnh và làm hệ thống nhanhđến ổn định so với trước, và tác động không đáng kể tới thời gian quá độ cũng như steady-state error.

Điều khiển tỉ lệ-tích phân

Trước khi xây dựng bộ điều khiển PID, chúng ta xem xét tới luật điều khiển PI . Như bảng tổng kết, tathấy rằng luậ điều khiển I làm giảm thời gian quá độ, nhưng làm tăng độ quá điều chỉnh và kéo dàithời gian đến ổn định của hệ thống, nhưng lại khử được steady-state error. Với hệ thống trên, chuyểnthành hàm truyền vòng kín với luật điều khiển PI ta được hàm truyền mới:

Bây giờ ta chọn lại Kp = 30, Ki = 70. Tạo m-file với các dòng lệnh sau.

Kp=30;Ki=70;contr=tf([Kp Ki],[1 0]);sys_cl=feedback(contr*plant,1);t=0:0.01:2;step(sys_cl,t)

Chạy chương trình trong MATLAB ta được đồ thị sau.

6

Page 60: Matlab Tutorial

Lý do chúng ta giảm Kp đi là vì luật điều khiển I cũng có tác dụng làm giảm thời gian quá độ và tăngđộ quá điều chỉnh như luật điều khiển P. Đồ thị trên cho ta thấy luật điều khiển I đã khử được sai sốxác lập.

Điều khiển tỉ lệ-tích phân-vi phân(PID)

Bây giờ ta xét đến bộ điều khiển PID. Hàm truyền của hệ thống trên với bộ điều khiển PID vòng kínbây giờ là:

Sau một số lần chạy thử với các tham số khác nhau, ta chọn được Kp=350, Ki=300, và Kd=50 hệthống sẽ đạt được đặc tính như mong muốn. Bạn đọc có thể thử lại bằng cách tạo m-file với các lệnhsau và chạy thử. Chúng ta sẽ được đồ thị đáp ứng như mong muốn.

Kp=350;Ki=300;Kd=50;contr=tf([Kd Kp Ki],[1 0]);sys_cl=feedback(contr*plant,1);t=0:0.01:2;step(sys_cl,t)

7

Page 61: Matlab Tutorial

Bây giờ ta đã có một hệ thống điều khiển vòng kín không có độ quá điều chỉnh, quá độ nhanh, vàkhông có sai số xác lập.

Một số gợi ý cho thiết kế bộ điều khiển PID

Khi muốn thiết kế một bộ điều khiển PID cho một hệ thống nào đó ta đi theo những bước sau đây.

Khảo sát hệt thống hở và xác định điều gì cần được cải thiện1.Thêm vào luật điều khiển P để cải thiện quá trình quá độ2.Thêm vào luật điều khiển D để giảm độ quá điều chỉnh3.Thêm vào luật điều khiển I để khử sai số xác lập4.Điệ chỉnh các giá trị Kp, Ki, và Kd cho đến khi đạt được đáp ứng như mong muốn. Bạn cũng cóthể tham khảo ở trang "PID Tutorial" để biết luật điều khiển nào tác động vào những đặc tínhnào.

5.

Cuối cùng, xin nhớ là không phỉa lúc nào ta cũng phải kết hợp cả 3 luật điều khiển (tỉ lệ, vi phân, vàtích phân) vào hệ thống. Ví dụ, nếu luật điều khiển PI cho đáp ứng đạt chất lượng tốt rồi (như ở ví dụtrên), thì chúng ta không nhất thiết thêm vào cả luật điều khiển D. Cần thiết kế làm sao để hệ thốngcủa ta càng đơn giản càng tốt.

Ví dụ về bộ điều khiển PIDĐiều khiển xe | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

8

Page 62: Matlab Tutorial

Ví dụ: Giải pháp điều khiển xe sử dụng bộ điềukhiển PID

Điều khiển tỉ lệĐiều khiển PIĐiều khiển PID

Hàm truyền của hệ thống điều khiển xe có dạng.

m = 1000b = 50U(s) = 10Y(s) = vận tốc ra

sơ đồ khối chung có feedback của hệ thống như sau.

Tiêu chuẩn đặt ra cho thiết kế điều khiển là:

Thời gian quá độ < 5 secĐộ quá điều chỉnh < 10%

Sai số xác lập < 2%

Để biết cách thiết lập mô hình hệ thống, xem trang Mô hình điều khiển xe .

Nhắc lại kiến thức từ PID tutorial, hàm truyền của 1 bộ điều khiển PID là

Trước hết ta xem xét luật điều khiển P.

Điều khiển P

Điều đầu tiên cần quan tâm là tìm ra hàm truyền điều khiển vòng kín với luật điều khiển P từ hệ thốngtrên. Bằng cách biến đổi sơ đồ khối, hàm truyền điều khiển vòng kín với luật điều khiển P bây giờ là:

1

Page 63: Matlab Tutorial

Nhắc lại kiến thức về bộ điều khiển PID, Luật điều khiển P làm giảm thời gian quá độ. Và đây cũng làvấn đề đặt ra ở phần Mô hình điều khiển xe .

Trước hết ta cho Kp = 100 và xem thử hệ thống đáp ứng như thế nào. Tạo một m-file có các lệnh sau.

Kp=100;m=1000;b=50;u=10;num=[1];den=[m b];cruise=tf(num,den);sys_cl=feedback(Kp*cruise,1);t=0:0.1:20;step(u*sys_cl,t)axis([0 20 0 10])

Chạy m-file trong MATLAB sẽ được đáp ứng bậc thang đơn vị như sau.

Như ta thấy trên đồ thị, cả sai số xác lập và thời gian quá độ đều không đạt được mục tiêu đề ra. Ta cóthể tăng hệ số Kp để cải thiện chất lượng đầu ra. Sửa lại m-file 1 chút để Kp = 10000 và chạy lại trongMATLAB. Ta sẽ có đồ thị sau

.

2

Page 64: Matlab Tutorial

Sai số xác lập đã giảm gần về 0 trong khi đó thời gian quá độ đã chỉ còn nhỏ hơn 0.5 giây. Tuy nhiên,đáp ứng trên là không thực tế lắm bởi vì một hệ thống điều khiển xe trên thực tế không thể thay đổivận tốc xe từ 0 đến 10 m/s trong thời gian nhỏ hơn 0.5 giây.

Giải pháp cho vấn đề này là chọn Kp sao cho có một thời gian quá độ hợp lý, và thêm vào điều khiểntích phân để khử sai số xác lập.

Điều khiển PI

Hàm truyền điều khiển vòng kín của hệ thống điều khiển xe với bộ luật điều khiển PI là:

Nhắc lại kiến thức phần PID tutorial, khi ta thêm điều khiển tích phân vào hệ thống thì sẽ có tác dụngkhử sai số xác lập. Bây giờ cho Kp = 600, Ki = 1 và xem đáp ứng của hệt thống bây giờ ra sao. Sửa lạim-file như sau.

m=1000;b=50;num=[1];den=[m b];cruise=tf(num,den);Kp = 600;Ki = 1;contr=tf([Kp Ki],[1 0]);sys_cl=feedback(contr*cruise,1);u=10;t=0:0.1:20;step(u*sys_cl,t)axis([0 20 0 10])

Ta được đồ thị đáp ứng đầu ra như sau:

3

Page 65: Matlab Tutorial

Bây giờ ta điều chỉnh các hệ số Kp và Ki để đạt được đáp ứng mong muốn. Khi điều chỉnh Ki, chúngta nên bắt đầu với giá trị nhỏ vì nếu Ki lớn sẽ có thể làm hệ thống mất ổn định.

Khi Kp = 800 và Ki =l 40, đáp ứng bậc thang đơn vị sẽ có dạng sau:

Như chúng ta thấy, đáp ứng này đã đạt được mục tiêu đề ra.

Điều khiển PID

Với ví dụ này, ta không cần thực hiện luật điều khiển D mà vẫn đạt được muc tiêu đề ra. Tuy nhiên, tacũng nên xem hệ thống sẽ hoạt động như thế nào nếu có bộ điều khiển PID để có thể tham khảo saunày. Hàm truyền điều khiển vòng kín của hệ thống với bộ điều khiển PID như sau.

Cho Kp = 1, Ki = 1, và Kd = 1 sau đó tạo một m-file như sau.

Kp=1; Ki=1; Kd=1; m=1000;

4

Page 66: Matlab Tutorial

b=50; u=10; cruise=tf(num,den); contr=tf([Kd Kp Ki],[1 0]); sys_cl=feedback(contr*cruise,1); t=0:0.1:20;step(u*sys_cl,t)axis([0 20 0 10])

Chạy m-file này ta sẽ có đáp ứng của hệ thống. Điều chỉnh các giá trị Kp, Kd, và Ki đến khi bạn cóđược đáp ứng như ý muốn. Chúng tôi giành việc đó cho bạn tự thực hành.

Lời khuyên: Thông thường việc chọn các giá trị tham số phải trải qua quá trình thử nhiều lần. Cách tôtnhất để tránh công việc buồn tẻ đó là bạn nên điều chỉnh từng tham số (Kp, Kd, hoặc Ki) một và quansát xem tham số đó ảnh hưởng thế nào đến đầu ra của hệt thống. Những đặc tính ảnh huởng của Kp,Kd, và Ki đã được tổng hợp trong phần PID Tutorial.

Ví dụ về bộ điều khiển PID Cruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Ví dụ về điều khiển xeModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

5

Page 67: Matlab Tutorial

Ví dụ: Điều khiển PID vận tốc động cơ một chiềuĐiều khiển tỉ lệĐiều khiển PIĐiều chỉnh hệ số

Từ ví dụ trước đây, ta có phương trình động lực học của và hàm truyền hở của mô hình động cơ 1chiều như sau:

và sơ đồ khối của hệ thống có dạng như sau:

Để biết cách thiết lập mô hình hệ thỗn, xem trang Modeling a DC Motor.

Với hàm đầu vào bậc thang 1 rad/sec, mục tiêu thiết kế là:

Thời gian ổn định nhỏ hơn 2 giâyĐộ quá điều chỉnh nhỏ hơn 5%Sai số xác lập nhỏ hơn 1%

Bây giờ ta thiết kế 1 bộ điều khiển PID để thêm vào hệt thống. Trước hết tạo một m-file gồm các câulệnh sau (tham khảo phần Modeling).

J=0.01;b=0.1;K=0.01;R=1;L=0.5;num=K;den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2)];motor=tf(num,den);

Nhớ lại hàm truyền của bộ điều khiển PID.

1

Page 68: Matlab Tutorial

Điều khiển P

Trước hết ta thử điều khiển P với Kp = 100. Để lập hàm truyền điều khiển vòng kín, ta dùng lệnhfeedback. Thêm vào cuối m-file vừa rồi các lệnh sau:

Kp=100;contr=Kp;sys_cl=feedback(contr*motor,1);

Bây giờ ta sẽ xem đáp ứng bậc thang của hê thống như thế nào. Lại thêm tiếp vàp cuối m-file vừa rồiđoạn lệnh sau:

t=0:0.01:5;step(sys_cl,t)title('Step response with Proportional Control')

Khi chạy m-file ta sẽ có đồ thị như sau:

Điều khiển PID

Từ đồ thị trên ta có thể thấy sai số xác lập và độ qua điều chỉnh đều rất lớn. Nhớ lại ở phần PIDtutorial rằng luật điều khiển I khử được sai số xác lập và luật D làm giảm độ quá điều chỉnh. Ta cùngthử bộ điều khiển PID với các giá trị nhỏ của Ki và Kd. Sửa lại m-file như dưới đây. Sau đó chạym-file ta sẽ có đồ thị.

J=0.01;b=0.1;K=0.01;R=1;L=0.5;

2

Page 69: Matlab Tutorial

num=K;den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2)];motor=tf(num,den);

Kp=100;Ki=1;Kd=1;contr=tf([Kd Kp Ki],[1 0]);sys_cl=feedback(contr*motor,1);step(sys_cl)title('PID Control with small Ki and Kd')

Điều chỉnh hệ số

Hiện tại ta thấy thời gian để ổn định là quá lớn. Ta phải tăng giá trị Ki để giảm thời gian ổn đạt ổn định.Sửa lại giá trị Ki trong m-file bằng 200. Cho chạy m-file ta sẽ có đồ thị như sau:

3

Page 70: Matlab Tutorial

Bây giờ ta có thể thấy đáp ứng đã nhanh ổn định hơn trước, nhưng giá trị Ki lớn làm giảm khả năngđáp ứng tức thời (độ quá điều chỉnh lớn). Ta tăng Kd để giảm độ qú điều chỉnh. Sửa lại giá trị Kd trongm-file bằng 10. Cho chạy m-file ta sẽ có đồ thị như sau:

Bây giờ ta đã có bộ điều khiển PID với

Kp=100,Ki=200,Kd=10,

thoả mãn mục tiêu đặt ra

4

Page 71: Matlab Tutorial

Ví dụ về bộ điều khiển PIDĐiều khiển xe | Điều khiển tốc độ động cơ | Điều khiển góc quay động cơ | Bus Suspension |Inverted Pendulum | Pitch Controller | Ball and Beam

Motor Speed ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

5

Page 72: Matlab Tutorial

Ví dụ: Điều khiển PID góc quay động cơĐiều khiển tỉ lệĐiều khiển PIDĐiều chỉnh hệ số

Đặt vấn đề, phuơng trình động lực học hàm truyền của hệ thống như sau:

và sơ đồ khối của hệ thống:

Để biết cách thiết lập mô hình hệ thống tham khảo trang Mô hình động cơ 1 chiều

Với đầu vào bậc thang 1 rad, mục tiêu thiết kế là:

Thời gian ổn định nhỏ hơn 0,04 giâyĐộ quá điều chỉnh nhỏ hơn 16%Không có sai số thiết lậpKhông bị phát sinh sai số thiết lập do nhiễu

Ta thiết kế 1 bộ điều khiển PID cho vào trong hệ thống trên. Trước tiên ta tạo mới 1 m-file có các dònglệnh sau (tham khảo hàm truyền phía trên).

J=3.2284E-6;b=3.5077E-6;K=0.0274;R=4;L=2.75E-6;num=K;den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2) 0];motor=tf(num,den);

Nhớ lại hàm truyền của bộ điều khiển PID có dạng:

1

Page 73: Matlab Tutorial

Điều khiển tỉ lệ

Trước tiên ta thử điều khiển tỉ lệ với hệ số Kp = 1,7. Để lập hàm truyền điều khiển vòng kín ta dùnglệnh feedback. Thêm các lệnh sau vào m-file:

Kp=1.7;contr=Kp;sys_cl=feedback(contr*motor,1);

Bây giờ muốn xem đáp ứng của hệ thông như thế nào ta thêm các lệnh tiếp theo vào m-file và chạy:

t=0:0.001:0.2;step(sys_cl,t)

Ta có đồ thị như sau:

Bây giờ muốn biết đáp ứng với nhiễu như thế nào ta thêm các lệnh sau vào cuối m-file, sau đó chạytrong Matlab:

dist_cl=feedback(motor,contr);step(dist_cl,t)

Ta sẽ có đồ thị sau:

2

Page 74: Matlab Tutorial

Điều khiển PID

Từ đồ thị trên ta thấy rằng sai số thiết lập là chấp nhận được nhưng thời gian ổn định quá lớn cũng nhưđộ quá điều chỉnh là cao. Cũng có thể thấy rằng sai số thiết lập do nhiễu tác động cũng lớn. Nhớ lạiphần PID tutorial rằng luật P khử được sai số thiết lập và luật D làm giảm độ quá điều chỉnh. Nhưngtrước hết hãy thử điều khiển PI để khắc phục ảnh hưởng của nhiễu. Sửa lại m-file như sau:

J=3.2284E-6;b=3.5077E-6;K=0.0274;R=4;L=2.75E-6;num=K;den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2) 0];motor=tf(num,den);

Kp=1.7;Ki=20;contr=tf([Kp Ki],[1 0]);sys_cl=feedback(contr*motor,1);t=0:0.001:0.4;step(sys_cl,t)

Ta sẽ có đồ thị như sau:

3

Page 75: Matlab Tutorial

Và xem ảnh hưởng của nhiễu bậc thang như thế nào, hãy thêm các lệnh sau vào m-file:

figuredist_cl=feedback(motor,contr);step(dist_cl,t)

Ta sẽ có đồ thị sau:

Như vậy luật I đã có tác dụng làm giảm sai số thiết lập về giá trị 0.

Điều chỉnh hệ số

Ta thấy thời gian để đạt tới ổn định vẫn quá dài. Ta phải tăng giá trị các hệ số để quá trình ổn địnhnhanh hơn nữa. Sửa lại giá trị Ki = 200 và Kp = 17 trong m-file. Cho chạy trong Matlab ta sẽ có đồ thịnhư sau:

4

Page 76: Matlab Tutorial

Bây giờ có thể thấy thời gian đạt ổn định đã nhanh hơn, nhưng giá trị Ki lớn lại làm tăng độ quá điềuchỉnh. Bây giờ ta phải dùng luật D để giảm độ quá điều chỉnh. Sửa lại m-file như sau rồi cho chạy trongMatlab.

Kp=17;Ki=200;Kd=0.15;contr=tf([Kd Kp Ki],[1 0]);sys_cl=feedback(contr*motor,1);t=0:0.001:0.1;step(sys_cl,t)

Ta sẽ có đồ thị sau:

5

Page 77: Matlab Tutorial

Và đồ thị đáp ứng với đầu vào nhiễu bậc thang như sau:

Bây giờ ta có thể thấy quá trình quá độ đã tôt hơn hẳn, độ quá điều chỉnh nhỏ hơn 16% thời gian quáđộ chỉ khoảng 40ms, và không có sai số thiết lập. Tuy nhiên đáp ứng với nhiễu lại ổn định chậm. Ta sẽtăng Ki để đáp ứng với nhiễu ổn định nhanh hơn. Cho Ki = 600 trong m-file chạy trong Matlab. Ta sẽcó đồ thị sau:

6

Page 78: Matlab Tutorial

Bây giờ ta có kế quả là quá trình quá độ chỉ khoảng 40ms, độ quá đìeu chỉnh nhỏ hơn 16%, và khôngcó sai số thiết lập. Đáp ứng với nhiễu đã không bị sai số thiết lập. Như vậy bộ điều khiển PID với

Kp=17,Ki=600,Kd=.15,

thoả mãn yêu cầu điều khiển đề ra.

Ví dụ về bộ điều khiển PIDĐiều khiển xe | Điều khiển tốc độ động cơ | Điều khiển góc quay động cơ | Bus Suspension |Inverted Pendulum | Pitch Controller | Ball and Beam

Ví dụ về đìều khiển góc quay động cơ

7

Page 79: Matlab Tutorial

Modeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

8

Page 80: Matlab Tutorial

Example:PID Design Method for the Bus SuspensionSystem

Adding a PID controllerPlotting the closed-loop responseChoosing the gains for the PID controller

From the main problem, the dynamic equations in transfer function form are the following:

and the system schematic looks like:

For the original problem setup and the derivation of the above equations and schematic, please refer to the busmodeling page.

We want to design a feedback controller so that when the road disturbance (W) is simulated by a unit step input,the output (X1-X2) has a settling time less than 5 seconds and an overshoot less than 5%. For example, when thebus runs onto a 10 cm high step, the bus body will oscillate within a range of +/- 5 mm and will stop oscillatingwithin 5 seconds.

The system model can be represented in MATLAB by creating a new m-file and entering the following commands(refer to main problem for the details of getting those commands).

m1=2500;m2=320;k1 = 80000;k2 = 500000;b1 = 350;b2 = 15020;

nump=[(m1+m2) b2 k2]denp=[(m1*m2) (m1*(b1+b2))+(m2*b1) (m1*(k1+k2))+(m2*k1)+(b1*b2) (b1*k2)+(b2*k1) k1*k2];G1=tf(nump,denp);

num1=[-(m1*b2) -(m1*k2) 0 0];

1

Page 81: Matlab Tutorial

den1=[(m1*m2) (m1*(b1+b2))+(m2*b1) (m1*(k1+k2))+(m2*k1)+(b1*b2) (b1*k2)+(b2*k1) k1*k2];G2=tf(num1,den1);

numf=num1;denf=nump;F=tf(numf,denf);

Adding a PID controller

Recall that the transfer function for a PID controller is:

where KP is the proportional gain, KI is the integral gain, and KD is the derivative gain. Let's assume that we willneed all three of these gains in our controller. To begin, we might start with guessing a gain for each: KP=208025,KI=832100 and KD=624075. This can be implemented into MATLAB by adding the following code into yourm-file:

KD=208025;KP=832100;KI=624075;contr=tf([Kd Kp Ki],[1 0]);

Now let's simulate the response of the system (the distance X1-X2) to a step disturbance on the road. From theschematic above we can find the transfer function from the road disturbance W to the output(X1-X2), andsimulate:

sys_cl=F*feedback(F*G1,contr);

Plotting the closed-loop response

Now we have created the closed-loop transfer function in MATLAB that will represent the plant, the disturbance,as well as the controller. Let's see what the closed-loop step response for this system looks like before we beginthe control process. Keep in mind that we are going to use a 0.1 m high step as our disturbance, to simulate this,all we need to do is to multiply sys_cl by 0.1. Add the following code your m-file:

t=0:0.05:5;step(0.1*sys_cl,t)title('closed-loop response to 0.1m high step w/ pid controller')

you should see the response (X1-X2) to a step W like this:

2

Page 82: Matlab Tutorial

From the graph, the percent overshoot is 9mm, which is larger than the 5mm requirement, but the settling time issatisfied, less than 5 seconds. To choose the proper gain that yields reasonable output from the beginning, we startwith choosing a pole and two zeros for PID controller. A pole of this controller must be at zero and one of thezeros has to be very close to the pole at the origin, at 1. The other zero, we will put further from the first zero, at 3,actually we can adjust the second-zero's position to get the system to fulfill the requirement. Add the followingcommand in the m-file, so you can adjust the second-zero's location and choose the gain to have a rough ideawhat gain you should use for KD,KP, and KI.

z1=1;z2=3;p1=0;numc=conv([1 z1],[1 z2]);denc=[1 p1];contr=tf(numc,denc);rlocus(contr*G1)title('root locus with PID controller')[K,p]=rlocfind(contr*G1)

you should see the closed-loop poles and zeros on the s-plane like this and you can choose the gain and dominantpoles on the graph by yourself:

3

Page 83: Matlab Tutorial

We will explain root locus method in more detail in the "Root Locus" page.

Choosing the gains for the PID controller

Now that we have the closed-loop transfer function, controlling the system is simply a matter of changing theKD,KP,and KI variab. From the figure above, we can see that the system has larger damping than required, butthe settling time is very short. This response still doesn't satisfy the 5% overshoot requirement. As mentionedbefore, this can be rectified by adjusting the KD, KP and KI variab to find better response. Let's increaseKP,KI,KD by a factor of 2 to see what will happen. Go back to your m-file and multiply KP,KI,KD by 2 andthen rerun the program, you should get the following plot:

To compare this graph with the graph of low-gain PID controller, you can change the axis:

axis([0 5 -.01 .01])

4

Page 84: Matlab Tutorial

Now we see that the percent overshoot and settling time meet the requirements of the system. The percentovershoot is about 5% of the input's amplitude and settling time is 2 seconds which is less than the 5 secondrequirement.

For this problem, it turns out that the PID design method adequately controls the system. This can been seen bylooking at the root locus plot. Such a task can be achieved by simply changing only the gains of a PID controller.Feel free to play around with all three of the parameters,KD,KP and KI, as we suggested, but you will most likelyget the response to have either large percent overshoot or very long settling time.

PID ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | Pitch Controller | Balland Beam

Bus Suspension ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

5

Page 85: Matlab Tutorial

Ví dụ: Giải pháp điều khiển PID cho con lắc ngượcBiểu diễn hệ thống hởHàm truyền của hệ thống điều khiển vòng kínTích hợp bộ điều khiển PIDĐiều gì xảy ra với vị trí của xe

Hàm truyền của cơ cấu chấp hành như sau:

ở đây,

Mục tiêu thiết kế (với điều kiện lúc đầu con lắc nhận được xung lực1N từ xe) là:

Thời gian ổn định nhỏ hơn 5 giây.Con lắc di chuyển không quá 0,05 rad so với phương thẳng đứng.

Để biết cách xây dựng mô hình bài toán này như thế nào tham khảo phần mô hình con lắc ngược

Biểu diễn hệ thống hở

Điều đầu tiên cần làm khi muốn thiết kế bộ PID là tìm hàm truyền của hệ thống và xem xét nó. Hàmtruyền sau khi biến đổi Laplace với đầu ra Phi (góc quay của con lắc) có thể được biểu diễn trongMatlab với tử số và mẫu số là hai vector. Tạo một m-file có các lệnh sau để thiết lập hàm truyền:

M = .5;m = 0.2;b = 0.1;i = 0.006;g = 9.8;l = 0.3;

q = (M+m)*(i+m*l^2)-(m*l)^2; %simplifies input

num = [m*l/q 0];den = [1 b*(i+m*l^2)/q -(M+m)*m*g*l/q -b*m*g*l/q];

1

Page 86: Matlab Tutorial

pend=tf(num,den);

Hàm truyền của hệ thống điều khiển vòng kín

Mô hình của hệ thống này có thể hơi khác so với những mô hình truyền thống mà ta quen biết. Do vậyở đây đặt bài toán là điều khiển con lắc ở vị trí thăng bằng với đầu vào nhiễu là một xung lực ban đầu,tín hiệu reference là 0. Xung lực ban đầu ở đây chính là một xung nhiễu. Sơ đồ hệ thống như vậy sẽ códạng sau.

Để dễ dàng chuyển đổi thành hàm truyền trong Matlab ta biến đởi tương đương thành sơ đồ sau:

Tích hợp bộ điều khiển PID

Hàm truyền trên được thiết lập trong Matlab bằng các lệnh sau:

Kd = 1;Kp = 1;Ki = 1;contr=tf([Kd Kp Ki],[1 0]);sys_cl=feedback(pend,contr);

Để cho tiện với hàm truyền này ta lấy luôn cả 3 luật điều khiển P, I và D (điều này cũng không bắtbuộc, bạn đọc vẫn có thể bắt đầu từng bước một với các bộ điều khiển PI, PD tuỳ theo ý mình).

contr=tf([Kp Ki],[1 0]); % PI controlcontr=tf([Kd Kp],1); % PD control

Bây giờ là lúc ta bắt đầu điều khiển hệ thống hiện tại. Trước hết ta xem đáp ứng xung của hệ thốnghiện tại ra sao. Thêm các câu lệnh sau vào M-Enter the following code to the end of your m-file:

t=0:0.01:5;impulse(sys_cl,t)axis([0 1.5 0 40])

Ta có đáp ứng dịch chuyển của hệ thống như sau:

2

Page 87: Matlab Tutorial

Đáp ứng này chưa ổn định. Trước hết ta tăng hê số Kp để xem tác động như thế nào, cho Kp=100, vàđặt lại hệ toạ độ bằng lệnh axis([0, 2.5, -0.2, 0.2]), ta sẽ có đồ thị sau:

Thời gian quá độ 2 giây ở đây là chấp nhận được. Vì sai số xác lập đã về 0 nên ta không cần điều khiểnKi thêm nữa. Bạn có thể thấy điều đó bằng cách thử thay đổi Ki và chạy lại. Dễ nhận thấy là độ quáđiều chỉnh là quá lớn và ta cần giả quyết vấn đề này. Để giải quyết ta tăng giá trị Kd. Với Kd = 20, tacó kết quả như mong muốn. Hãy xem đáp ứng với giá trị Kd = 20:

3

Page 88: Matlab Tutorial

Như ta thấy, độ quá điều chỉnh đã giảm xuống nhỏ hơn 0,05 rad như thế nghĩa là con lắc dịch chuyểnxung quanh vị trí thẳng đứng không quá 0,05 rad. Mục tiêu điều khiển đã đạt, không cần thiết phảiđiều chỉnh tiếp nữa.

Điều gì xảy ra với vị trí của xe?

Ngay từ đầu, chúng ta đã đưa ra mô hình của hệ thống. Nhưng mô hình đó chưa thực sự hoàn thiện.Chúng ta đã bỏ qua dịch chuyển của xe vì ta đang quan tâm tới góc quay của con lắc. Sẽ rất hay nếu taxem xét dịch chuyển của xe ra sao khi ta đang điều khiển góc quay của con lắc. Để có thể, trước hết taxem sơ đồ khối thực tế như sau:

Biến đổi lại 1 chút ta có sơ đồ khối như sau

:

4

Page 89: Matlab Tutorial

Vòng kín ở trên là hệ thống ta vừa thiết kế với bộ điều khiển PID cho góc quay con lắc. Hàm truyềnvới đầu ra là dịch chuyển của xe bây giờ như sau:

Bây giờ ta đã có thể xây dựng hàm truyền cho toàn bộ hệ thống, hãy xem đáp ứng của nó ra sao.Trước hết ta tìm hàm truyền cho dich chuyển của xe. Để có đuợc điều này ta phải sử dụng biến đổiLaplace cho phương trình hệ thống rồi tìm mối liên hệ giữa X(s) và U(s). Ta có phương trình sau:

ở đây,

Để biết thêm về biến đổi Laplace tham khảo phần mô hình con lắc ngược.

Lúc này lại xuất hiện pole/zero ở hàm truyền mà lúc trước đã được giản ước trong hàm truyền của Phi.Do đó den1 = den2. Bây giờ tạo 1 m-file với các dòng lệnh sau:

M = .5;m = 0.2;b = 0.1;i = 0.006;g = 9.8;l = 0.3;

q = (M+m)*(i+m*l^2)-(m*l)^2; %simplifies input

num1 = [m*l/q 0 0];den1 = [1 b*(i+m*l^2)/q -(M+m)*m*g*l/q -b*m*g*l/q 0];G1=tf(num1,den1);

num2 = [(i+m*l^2)/q 0 -m*g*l/q];den2 = den1;G2=tf(num2,den2); kd = 20;kp = 100;ki = 1;contr=tf([kd kp ki],[1 0]);

xpos=feedback(1,G1*contr)*G2;

t=0:0.01:5;impulse(xpos,t)

5

Page 90: Matlab Tutorial

Như ta thấy, xe chuyển động theo chiều âm với vận tốc là hằng số nghĩa là theo thời gian vị trí xe sẽtiến ra vô cùng. Như vậy mặc dù bộ điều khiển PID ổn định được góc quay của con lắc nhưng thiết kếđó không khả thi để ứng dụng thực tế.

Ví dụ về bộ điều khiển PIDĐiều khiển xe | Điều khiển tốc độ động cơ | Điều khiển góc quay động cơ | Bus Suspension |Điều khiển con lắc ngược | Pitch Controller | Ball & Beam

Inverted Pendulum ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

6

Page 91: Matlab Tutorial

Example: PID Design method for the PitchController

Proportional controlProportional-Derivative controlProportional-Integral-Derivative control

In the Pitch Controller Modeling page, the transfer function was derived as

The input (elevator deflection angle, delta e) will be 0.2 rad (11 degrees), and the output is the pitchangle (theta).

The design requirements are

Overshoot: Less than 10%Rise time: Less than 2 secondsSettling time: Less than 10 secondsSteady-state error: Less than 2%

To see the original problem setup, please refer to the Pitch Controller Modeling page.

Recall from the PID Tutorial page, the transfer function of a PID controller is:

We will implement combinations of proportional (Kp), integral (Ki), and derivative (Kd) controllers inan unity feedback system shown below to study the system output.

Let's first take a look at a proportional control.,

Proportional control

The first thing in solving this problem using PID control is to find a closed-loop transfer function with aproportional control (Kp). A closed-loop transfer function can be obtained either by hand or using theMATLAB function called feedback. By hand, you should obtain the closed-loop transfer function as:

1

Page 92: Matlab Tutorial

Note: MATLAB cannot manipulate symbolic variab. To use the function feedback, enter the followingcommands to an m-file and run it in the MATLAB command window.

Kp=[1];num=[1.151 0.1774];den=[1 0.739 0.921 0];pitch=tf(num,den);contr=tf(Kp,1);sys_cl=feedback(contr*pitch,1);

For now, let the proportional gain (Kp) equal 2 and observe the system behavior. Enter the followingcommands into a new m-file and run it in the MATLAB command window. You should obtain the stepresponse similar to the one shown below:

de=0.2;Kp=2;sys_cl=feedback(Kp*pitch,1);t=0:0.01:30;step(de*sys_cl,t)

As you see, both the overshoot and the settling time need some improvement.

PD control

Recall from the PID Tutorial page, the derivative controller will reduce both the overshoot and thesettling time. Let's try a PD controller. The closed-loop transfer function of the system with a PDcontroller is:

2

Page 93: Matlab Tutorial

Using the commands shown below and with several trial-and-error runs, a proportional gain (Kp) of 9and a derivative gain (Kd) of 4 provided the reasonable response. To confirm this, change your m-fileto the following and run it in the MATLAB command window. You should obtain the step responsesimilar to the one shown below:

de=0.2;Kp=9;Kd=4;contr=tf([Kd Kp],1);sys_cl=feedback(contr*pitch,1);t=0:0.01:10;step(de*sys_cl,t)

This step response shows the rise time of less than 2 seconds, the overshoot of less than 10%, thesettling time of less than 10 seconds, and the steady-state error of less than 2%. All designrequirements are satisfied.

PID Control

Even though all design requirements were satisfied with the PD controller, the integral controller (Ki)can be added to reduce the sharp peak and obtain a smoother response. After several trial-and-errorruns, the proportional gain (Kp) of 2, the integral gain (Ki) of 4, and the derivative gain (Kd) of 3provided a smoother step response that still satisfies all design requirements. To confirm this, enter thefollowing commands to an m-file and run it in the command window. You should obtain the stepresponse shown below:

de=0.2;Kp=2;Kd=3;Ki=4;

num=[1.151 0.1774];den=[1 0.739 0.921 0];

pitch=tf(num,den);contr=tf([Kd Kp Ki],[1 0]);

sys_cl=feedback(contr*pitch,1); t=0:0.01:10; step(de*sys_cl,t)

3

Page 94: Matlab Tutorial

Comments

To find appropriate gains (Kp, Kd, and Ki), you can use the table shown in PID Tutorial page;however, please keep in your mind that changing one gain might change the effect of the othertwo. As a result, you may also need to change the other two gains.

1.

Our system with a PI controller does not provide the desired response; thus, a PI Controlsection was omitted from this page. You may confirm this by using the m-file shown in PIDControl section, and set Kd to zero.

2.

PID ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchControl | Ball and Beam

Pitch Control ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

4

Page 95: Matlab Tutorial

Ví dụ: Giải pháp cho bài toán Bóng &Thanh đỡ sửdụng bộ điều khiển PID

Biểu diễn hệ thống vòng kínĐiều khiển Tỉ lệĐiều khiển Tỉ lệ-Vi phân

Hàm truyền hệ thống hở đã thiết lập trong phần mô hình như sau:

Mục tiêu thiết kế bộ điều khiển:

Thời gian quá độ nhỏ hơn 3 giâyĐộ quá điều chỉnh nhỏ hơn 5%

Để biết cách thiết lập mô hình toán học trên, tham khảo trang mô hình bóng và thanh đỡ.

Biểu diễn hệ thống điều khiển vòng kín

Sơ đồ khối hệ thống điều khiển vòng kín như sau:

Trước tiên, ta xem đáp ứng của hệ thống ra sao với bộ điều khiển P. Sau đó sẽ thêm vào các luật Dhoặc I nếu cần thiết.

Nhắc lại rằng hàm truyền của bộ điều khiển PID có dạng:

Điều khiển tỉ lệ

Hàm truyền của hệ thống điều khiển tỉ lệ vòng kín với Kp = 100 được thiết lập trong Matlab bằng cáchtạo ra một m-file có lệnh sau:

1

Page 96: Matlab Tutorial

m = 0.111;R = 0.015;g = -9.8;L = 1.0;d = 0.03;J = 9.99e-6;

K = (m*g*d)/(L*(J/R^2+m)); %simplifies input

num = [-K];den = [1 0 0];ball=tf(num,den);

kp = 1;sys_cl=feedback(kp*ball,1);

Để xem đáp ứng của hệ thống với đầu vào là tín hiệu bậc thang 0.25 m. Thêm lệnh sau vào cuối m-filevà chạy:

step(0.25*sys_cl)

Ta sẽ có đồ thị sau:

Như ta thấy Kp không làm hệ thống ổn định. Hãy thử một số giá trị khác cả Kp, bạn sẽ vẫn thấy hệthống không thể ổn định.

Điều khiển Tỉ lệ - Vi phân

Bây giờ ta thêm luật D vào bộ điều khiển. Tạo một m-file có các lệnh sau rồi chạy.

m = 0.111;R = 0.015;g = -9.8;L = 1.0;d = 0.03;J = 9.99e-6;

K = (m*g*d)/(L*(J/R^2+m)); %simplifies input

2

Page 97: Matlab Tutorial

num = [-K];den = [1 0 0];ball=tf(num,den);

kp = 10;kd = 10;contr=tf([kd kp],1);

sys_cl=feedback(contr*ball,1);

t=0:0.01:5;step(0.25*sys_cl)

Đồ thị sau khi chạy chương trình sẽ có dạng sau:

Bây giờ hệ thống đã ổn định song độ quá điều chỉnh lại rất lớn, và thời gian quá độ cũng cần điềuchỉnh nhanh hơn 1 chút. Ở phần PID tutorial trong bảng tổng kết về các luật điều khiển P, I, và D tabiết rằng nếu tăng Kd lên thì sẽ cải thiện được độ quá điều chỉnh và thời gian quá độ một chút. Do đó,thay đổi m-file cho Kd = 20 và chạy lại ta sẽ có đồ thị sau:

3

Page 98: Matlab Tutorial

Độ quá điều chỉnh đã đạt nhưng cần giảm thời gian quá độ một chút. Ta tiếp tục tăng Kd lên một chút.Tăng Kd cũng có tác dụng làm giảm độ quá điều chỉnh do Kp tạo ra. Sau một số lần điều chỉnh với Kp= 15 và Kd =40 ta có đáp ứng:

Như ta thấy chỉ cần sử dụng điều khiển P và D là ta đã giải quyết yêu cầu đặt ra (thời gian quá độthậm chí còn bé hơn 2% thời gian yêu cầu). Nên nhơ rằng với bất kì vấn đề điều khiển nào ta cũngphải có lớn hơn 1 phương án thì mới đảm bảo.

Xem các liên kết bên dưới để có thêm những phương pháp điều khiển khác cho bài toán bóng và thanhđỡ.

PID ExamplesĐiều khiển xe | Điều khiển tốc độ động cơ | Điều khiển góc quay động cơ | Bus Suspension |

4

Page 99: Matlab Tutorial

Điều khiển con lắc ngược | Pitch Controller | Bài toán bóng và thanh đỡ

Ví dụ về bài toán bóng và thanh đỡModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

5

Page 100: Matlab Tutorial

Quỹ tích nghiệm (Root Locus)Cực của hệ kínĐồ thị quỹ tích nghiệm của một hàm truyềnChọn giá trị K từ quỹ tích nghiệmĐáp ứng mạch kín

Các lệnh MATLAB quan trọng trong phần này: feedback, rlocfind, rlocus, sgrid, step

Cực của hệ kín

Quỹ tích nghiệm (mạch hở) của một hàm truyền H(s) là đồ thị thể hiện vị trí của tất cả các cực của hệkín với hệ số tỷ lệ K và phản hồi đơn vị:

Hàm truyền mạch kín với phản hồi đơn vị bằng:

và vì vậy, cực của hệ kín là các giá trị, sao cho 1 + K H(s) = 0.

Nếu viết H(s) = b(s)/a(s), thì phương trình có dạng:

Gọi n là bậc của đa thức a(s) và m là bậc của đa thức b(s) [bậc của một đa thức là số mũ cao nhất cótrong đa thức đó].

Chúng ta để ý tất cả các giá trị dương của K. Tại giới hạn K -> 0, cực của hệ kín ứng với a(s) = 0 hoặccực của H(s). Tại giới hạn K -> vô cùng, cực của hệ kín ứng với b(s) = 0 hoặc điểm 0 của H(s).

Dù K ứng với điểm nào đi nữa thì hệ kín cũng phải luôn luôn có n cực, trong đó n chính là số cựccủa H(s). Đường quỹ tích phải có n nhánh, mỗi nhánh xuất phát từ cực của H(s) và chạy đến điểm 0của H(s). Nếu H(s) có số cực nhiều hơn số điểm 0 (điều thường xảy ra), m < n thì ta nói rằng H(s) có

1

Page 101: Matlab Tutorial

điểm 0 ở vô cùng. Trong trường hợp này, giới hạn của H(s) khi s -> vô cùng bằng 0. Số điểm 0 ở vôcùng là hiệu n-m, nghĩa là hiệu giữa số cực và số điểm 0 và là số nhánh của quỹ tích nghiệm tiến tới vôcùng (tiệm cận).

Vì quỹ tích nghiệm biểu diễn mọi vị trí có thể của các cực của hệ kín, nên từ quỹ tích nghiệm chúng tacó thể chọn hệ số truyền để đạt các tính năng đặt ra cho hệ thống. Nếu có bất kỳ một cực nào nằmtrong nửa mặt phẳng phía phải thì hệ kín sẽ không ổn định. Cực càng nằm ở gần trục ảo thì ảnh hưởngcàng nhiều đến đáp ứng hệ kín. Vì vậy, dù hệ có tới 3 hay 4 cực thì nó cũng chỉ hoạt động như hệ bậchai, thậm chí bậc 1, tuỳ thuộc vào vị trí của các cực chủ đạo.

Vẽ quỹ tích nghiệm của hàm truyền

Giả sử có hệ hở với hàm truyền sau:

Chúng ta cần thiết kế một bộ điều khiển có phản hồi bằng phương pháp quỹ tích nghiệm theo các chỉtiêu kỹ thuật sau: quá điều khiển 5% và thời gian ổn định 1 giây. Tạo một m-file với tên rl.m. Nhậphàm truyền và lệnh vẽ quỹ tích nghiệm như sau:

num=[1 7];den=conv(conv([1 0],[1 5]),conv([1 15],[1 20]));sys=tf(num,den);rlocus(sys)axis([-22 3 -15 15])

Chọn giá trị của K từ quỹ tích nghiệm

Đồ thị trên biểu diễn vị trí của tất cả các cực của bộ điều khiển thuần tuý tỷ lệ. Tất nhiên, không phảitất cả các cực đều thoả mãn các chỉ tiêu thiết kế. để xác định xem cực nào có thể chấp nhận được,chúng ta dùng lệnh sgrid(Zeta,Wn) để vẽ các đường có hệ số giảm chấn và tần số dao động riêngbằng hằng số. Hai tham số của lệnh chính là hệ số giảm chấn (Zeta) và tần số dao động riêng (Wn)

2

Page 102: Matlab Tutorial

[chúng có thể là các vector nếu chúng ta muốn nhìn thấy khoảng các giá trị có thể chấp nhận được].Trong bài toán này, chúng ta cần lượng quá điều khiển dưới 5% (nghĩa là hệ số giảm chấn Zeta > 0.7)và thời gian xác lập bé hơn 1 giây (nghĩa là tần số dao động riêng Wn > 1.8). Nhập thêm chúng vàocuối m-file trước đó:

zeta=0.7;Wn=1.8;sgrid(zeta, Wn)

Trên đồ thị, 2 đường nét chấm nghiêng gần 45 độ thể hiện vị trí của các cực ứng với giá trị Zeta = 0.7.Nằm giữa 2 đường này là các cực ứng với Zeta > 0.7 và phía ngoài là các cực với Zeta < 0.7. Nửavòng tròn thể hiện các cực với tần số dao động riêng Wn = 1.8. Các cực nằm phía trong ứng với Wn <1.8, phía ngoài ứng với Wn > 1.8.

Trở lại bài toán, để lượng quá điều khiển nhỏ hơn 5%, thì các cực phải nằm giữa 2 đường nét chấm,còn muốn có thời gian xác lập ngắn hơn 1 giây thì các cực phải nằm ngoài nửa vòng tròn. Như vậy,chỉ có đoạn quỹ tích nghiệm nằm ngoài nửa vòng tròn và giữa 2 đường nét chấm là thoả mãn yêu cầu.Tất cả các cực trên đoạn này đều nằm ở nửa mặt phẳng bên trái, nên hệ kín thiết kế ra sẽ ổn định.

Từ đồ thị trên, ta thấy chỉ có một phần của quỹ tích nghiệm là nằm trong vùng mong muốn. Vì vậy,chúng ta chỉ cần 1 bộ điều khiển tỷ lệ để đưa các cực về vùng này. Chúng ta dùng lệnh rlocfind đểtìm các cực mong muốn trên quỹ tích:

[k,poles] = rlocfind(sys)

Dùng chuột kích vào điểm mà chúng ta định dùng làm cực của hệ kín. Bạn có thể chọn các điểm nhưtrong hình dưới để thoả mãn các chỉ tiêu thiết kế.

3

Page 103: Matlab Tutorial

Chú ý rằng, vì quỹ tích nghiệm có trên 1 nhánh nên khi chọn một cực, bạn có thể tìm ra vị trí của cáccực khác. Nhớ rằng chúng cũng ảnh hưởng đến đáp ứng của hệ thống. Từ đồ thị trên, chúng ta có thểthấy tất cả các cực đã chọn (có dấu +) là thoả mãn yêu cầu. Bây giờ chúng ta tiếp tục sử dụng giá trịK đã chọn cho bộ điều khiển tỷ lệ.

Phản ứng hệ kín

Để tìm đáp ứng của hệ với tín hiệu vào bậc thang, chúng ta cần biết hàm truyền hệ kín. Ta có thể thựchiện điều đó bằng phương pháp rút gọn sơ đồ khối, hoặc yêu cầu MATLAB thực hiện:

sys_cl= feedback(k*sys,1)

Hai tham số của hàm feedback là tử số và mẫu số của hàm truyền hệ hở. Bạn cần thêm vào đó hệ sốtruyền K đã chọn, và giả thiết dùng phản hồi đơn vị.

Nếu bạn gặp trường hợp phản hồi khác đơn vị thì xem trợ giúp (help) với hàm feedback để biếtcách tìm hàm truyền hệ kín có hệ số phản hồi khác 1.

Để kiểm tra phản ứng của hệ kín, dùng lệnh:

step(sys_cl)

4

Page 104: Matlab Tutorial

Đúng như mong muốn, lượng quá điều khiển nhỏ hơn 5% và thời gian xác lập dưới 1 giây.

Root Locus ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball & Beam

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

5

Page 105: Matlab Tutorial

Ví dụ: Giải pháp điều khiển xe bằng phương phápquỹ tích nghiệm

Bộ điều khiển tỉ lệBộ điều khiển Lag

Hàm truyền của hệ hở có dạng:

Ở đây

m=1000b=50U(s)=10Y(s)=vận tốc đầu ra

Mục tiêu thiết kế bộ điều khiển:

Thời gian quá độ < 5 secĐộ quá điều chỉnh < 10%

Sai số xác lập < 2%

Để biết cách thiết lập phương trình hệ thống, tham khảo Mô hình điều khiển xe .

Bộ điều khiển tỉ lệ

Nhớ lại kiến thức từ phần Root-Locus Tutorial , quỹ tích nghiệm cho chúng ta biết tất cả các vị trí củacác cực của hệ kín khi hệ số tỉ lệ thay đổi từ 0 đến vô cùng. Do đó, ta chỉ quan tâm tới bộ điều khiểntỉ lệ để giải quyết vấn đề này. Ở đây ta có hàm truyền của hệ kín:

Từ phầm Root-Locus Tutorial, ta cũng biết lệnh sgrid được dùng để tìm vùng mong muốn trên quỹtích nghiệm. Để dùng lệnh sgrid, hai hệ số cần xác định trước là hệ số giảm chấn zeta và tần số daođọng riêng Wn cần được xác định trước. Hai phương trình sau được dùng để xác định hai hệ số trên:

1

Page 106: Matlab Tutorial

Ở đây

Wn=Tần số dao động riêngzeta=Hệ số giảm chấnTr=Thời gian quá độMp=Độ quá điều chỉnh lớn nhất

Một trong những mục tiêu điều khiển của ta là thời gian quá độ nhỏ hơn 5 giây. Từ phương trình đầutiên ta thấy tần số dao động riêng cần nhỏ hơn 0,36. Từ phương trình thứ hai ta thấy hệ số giẩm chấnphải lớn hơn 0,6 thì độ quá điều chỉnh sẽ nhỏ hơn 10%.

Bây giờ chúng ta sẽ vẽ quỹ đạo nghiệm và dùng lệnh sgrid để tìm các vùng mong muốn. Tạo 1 m-filecó các lệnh sau.

m=1000;b=50;u=10;num=[1];den=[m b];cruise=tf(num,den);

rlocus(cruise)axis([-0.6 0 -0.6 0.6]);sgrid(0.6, 0.36)[Kp, poles]=rlocfind(cruise)sys_cl=feedback(Kp*cruise,1);

t=0:0.1:20;step(u*sys_cl,t)axis ([0 20 0 10])

Cho chạy m-file ta có quỹ tích nghiệm như sau.

2

Page 107: Matlab Tutorial

Hai đường nét chấm thể hiện vị trí các cực ứng với zeta=0,6, nằm giữa 2 đường này là các cực ứngvới Zeta > 0,6 và phía ngoài là các cực với Zeta < 0,6. Nửa vòng elip thể hiện các cực với tần số daođộng riêng Wn = 0,36. Các cực nằm phía trong ứng với Wn < 0,36, phía ngoài ứng với Wn > 0,36.

Nếu chạy chương trình trong cửa sổ lệnh của Matlab ta sẽ thấy có dấu nhắc ta chọn 1 điểm trên quỹđạo nghiệm. Như vậy, ta cần chọn điểm nằm giữa hai đường nét chấm (zeta>0.6) và nằm ngoài nửavòng elip (Wn>0.36), hãy kích vào điểm nằm ngoài elip (toạ độ trên trục thực khoảng 0,4).

Ta sẽ có gí trị Kp và các điểm cực trong cửa sổ lệnh của Matlab. Đồng thời ta cũng thấy đáp ứng vớiđầu vào tín hiệu bậc thang như sau.

Với giá trị Kp này (do ta vừa chọn), thời gian quá độ và độ quá điều chỉnh đã đạt yêu cầu; tuy nhiênsai số xác lập vẫn còn lớn hơn 10%.

Bộ điều khiển Lag

3

Page 108: Matlab Tutorial

Để giảm sai số xác lập, bộ điều khiển Lag được đặt vào hệ thống. Hàm truyền của bộ điều khiển Laglà:

Hàm truyền của hệ hở (chưa có Kp) bây giờ là:

Hàm truyền của hệ kín với bộ điều khiển tỉ lệ bây giờ là:

Nếu ta tra mục "Lag or Phase-Lag Compensator using Root-Locus" trong phần Lead and LagCompensator điểm không và điểm cực phải được đặt gần nhau. Cũng từ đó, sai số xác lập sẽ giảmxuống 1 lương khoảng bằng Zo/Po. Vì hai lý do trên, ta chọn Zo = -0.3 và Po = -0.03.

Tạo một m-file, có các lệnh sau.

m = 1000;b = 50;u = 10;Zo=0.3;Po=0.03;

num=[1];den=[m b];cruise=tf(num,den);

contr=tf([1 Zo],[1 Po]);

rlocus(contr*cruise);axis([-0.6 0 -0.4 0.4])sgrid(0.6,0.36);[Kp, poles]=rlocfind(contr*cruise);sys_cl=feedback(Kp*contr*cruise,1);

t=0:0.1:20;step(u*sys_cl,t)axis ([0 20 0 12])

Chạy m-file sẽ cho ta quỹ tích nghiệm như sau:

4

Page 109: Matlab Tutorial

Chọn 1 điểm như như lúc trước (trên trục thực với toạ độ trục thực khoảng -0.4). Ta sẽ có đáp ứngsau.

Như ta thấy, sai số xác lập đã nhỏ gần bằng 0. Ta cũng thấy 1 lượng quá điều chỉnh nhỏ do có điểmkhông trong bộ điều khiển Lag.

Bây giờ mục tiêu điều khiển đã hoàn thành và ta không cần phải điều chỉnh thêm gì nữa.

Root Locus ExamplesĐiều khiển xe | Điều khiển tốc độ động cơ | Điều khiển góc quay động cơ | Bus Suspension |Điều khiển con lắc ngược | Pitch Controller | Bài toán bóng và thanh đỡ

Cruise Control ExamplesModeling | PID | Quỹ tích nghiệm | Frequency Response | State Space | Digital Control |Simulink

5

Page 110: Matlab Tutorial

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

6

Page 111: Matlab Tutorial

Ví dụ: Phương pháp quỹ tích nghiệm cho điềukhiển tốc độ động cơ 1 chiều

Vẽ quỹ đạo nghiệm của hệ hởTìm các hệ số bằng lệnh rlocfindĐặt thêm bộ điều khiển LagĐáp ứng của hệ thống điều khiển kín

Ta có phương trình động lực học và hàm truyền của hệ hở như sau:

và sơ đồ khối của hệ thống như sau:

Để biết cách thiết lập hệ mô hình trên, tham khảo phần Mô hình động cơ điện 1 chiều.

Với đầu vào tín hiệu bậc thang 1 rad/sec, mục tiêu thiết kế là:

Thời gian đạt ổn định nhỏ hơn 2 giâyĐộ quá điều chỉnh nhỏ hơn 5%Sai số xác lập nhỏ hơn 1%

Ta sẽ thiết kế 1 bộ điều khiển sủ dung phương pháp quỹ đạo nghiệm.

Tạo 1 m-file có các lệnh sau để tạo hàm truyền trong Matlab (tham khảo phần mô hình).

J=0.01;b=0.1;K=0.01;R=1;L=0.5;num=K;den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2)];motor=tf(num,den);

1

Page 112: Matlab Tutorial

Vẽ quỹ tích nghiệm của hệ hở

Mục đích chính của việc tìm quỹ tích nghiệm là xác định đáp ứng của hệ kín từ quỹ tích nghiệm củahệ hở. Sau đó bằng cách thêm vào khâu chấp hành các điểm cực hoặc điểm không để sửa đổi đáp ứngcủa hệ kín theo yêu cầu. Trước tiên ta hãy xem xét quỹ tích nghiệm của khâu chấp hành. Thêm cáclệnh sau vào m-file.

rlocus(motor)sgrid(.8,0)sigrid(2.3)title('Root Locus without a controller')

Hàm sigrid là một hàm do người dùng tạo ra. Ta cần copy file sigrid.m vào cùng thư mục với m-filecủa ta để có thể gọi dẽ dàng. Để biết hàm này có chức năng gì, tham khảo phần functions.

Hai đối số của lệnh sgrid là hệ số về giảm chấn zeta (0,8 tương ứng với độ quá điều chỉnh là 5%), vàvề tần số dao động riêng Wn (= 0 nghĩa là không có điều kiện về thời gian quá độ). Đối số duy nhấtcủa lệnh sigrid là sigma (4.6/2 giây = 2.3). Sau khi đã có file sigrid.m trong thư mục hiện hành, chạym-file trên ta sẽ có qũy tích nghiệm như sau:

Tìm hệ số bằng lệnh rlocfind

Nhớ rằng, ta cần thời gian quá độ và độ quá điều chỉnh càng nhỏ càng tốt. Đọ giảm chấm lớn tươngứng với việc những điểm trên quỹ tích nghiệm sẽ ở gần trục thực hơn. Với đáp ứng càng nhanh thì cácđiểm trên quỹ tích nghiệm càng ra xa về phía bên trái trục ảo. Để tìm hệ số tương ứng với 1 điểm trênquỹ tích nghiệm, ta dùng lệnh rlocfind. Ta sẽ tìm được hệ số đó và xem ngay được với hệ số ấy thì đápứng của hệ thống bây giờ như thế nào. Để làm điều này, thêm các câu lệnh sau vào m-file rồi chạy.

[k,poles] = rlocfind(motor)sys_cl=feedback(k*motor,1);t=0:0.01:3;step(sys_cl,t)title('Step response with gain')

2

Page 113: Matlab Tutorial

Trở về cửa sổ plot và chọn 1 điểm ở khoảng giữa trục thực và điều kiện sigma, gần điểm -6+2.5i.Matlab se tính cho ta kết quả sau.

selected_point = -5.9596 + 2.0513i

k = 10.0934

poles = -6.0000 + 2.0511i -6.0000 - 2.0511i

Ta cũng sẽ có đáp ứng sau:

Như ta thấy, ở đây độ quá điều chỉnh là không có và thời gian quá độ khoảng 1 giây, như vậy là thoảmãn yêu cầu. Vấn đề duy nhất là sai số xác lập quá lớn (khoảng 50%). Nếu ta tăng giá trị của hệ số đểgiảm sai số xác lập thì độ quá điều chỉnh sẽ rất lớn (hãy thử vài lần). Chúng ta cần đặt thêm vào bộđiều khiển Lag để giảm sai số xác lập.

Đặt thêm bộ điều khiển Lag

Quỹ tích nghiệm ta gặp ở đây là khá đơn giản. Độ giảm châm và thời gian quá độ đạt được dễ dàngvới bộ điều khiển tỉ lệ. Chỉ có sai số xác lập là chưa đạt được. Một cơ cấu bù Lag sẽ làm giảm sai sốxác lập. Khi thực hiện như vậy, chúng ta một phần nào đó sẽ làm tăng thời gian quá độ. Ban đầu hãy thử bộ điều khiển Lag sau:

Công việc này thực hiện trong m-file như sau:

J=0.01;b=0.1;

3

Page 114: Matlab Tutorial

K=0.01;R=1;L=0.5;

num=K;den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2)];Zo=1;Po=0.01;

motor=tf(num,den);contr=tf([1 Zo],[1 Po]);

rlocus(contr*motor)sgrid(.8,0)sigrid(2.3)title('Root Locus with a lag controller')

Ta sẽ có quỹ tích nghiệm của hệ hở gần giống như ban đầu như sau:

Biểu diễn đáp ứng của hệ kín

Bây giờ ta sẽ tìm đáp ứng của hệ kín. Thêm vào m-file các lệnh sau:

[k,poles]=rlocfind(contr*motor)sys_cl=feedback(k*contr*motor,1);t=0:0.01:3;step(sys_cl,t)title('Step response with a lag controller')

Chạy m-file trên trong Matlab. Khi được yêu cầu chọn 1 điểm trên quỹ tích nghiệm, hãy chọn điểmgần đường giảm chấn (đường nét đứt chéo). Ta sẽ có đáp ứng sau:

4

Page 115: Matlab Tutorial

Giá trị hệ số tỉ lệ sẽ gần bằng 20. Như ta thấy đáp ứng trên cũng chưa được tốt. Và ta cũng nhận thấyrằng với việc chọn 1 điểm ở gần đường điều kiện giảm chấn như vậy, độ quá điều chỉnh vẫn chưa thểbằng 5%. Đó là do ảnh hưởng của bộ điều khiển Lag (giá trị điểm cực của nó nhỏ). Điều này có nghĩalà ta có thể vượt qua đường điều kiện giảm chấn để chọn hệ số tỉ lệ lớn hơn mà không phải lo tới độquá điều chỉnh. Hãy chạy lại m-file, chọn điểm vừa đủ vượt ra khỏi đường nét đứt. Thử một vài lầnđến khi ra được đáp ứng mong muốn. Nó sẽ có dạng như sau (lúc đó hệ số tỉ lệ có giá trị xấp xỉ 50):

Sai số xác lập bây giờ đã nỏ hơn 1%, thời gian quá độ cũng như độ quá điều chỉnh cũng đạt yêu cầuđặt ra. Và như ta thấy, phương pháp thiết kế theo quỹ đạo nghiệm cần nhiều đến kỹ năng thử sai. Điềunày khá hay vì ta thực hiện vẽ quỹ tích nghiệm, chọn hệ số, và vẽ đáp ứng trong cùng 1 bước. Nếu tagặp khó khăn trong việc chọn hệ số, ta có thể thay đổi bộ điều khiển Lag khác, hoặc có thể thêm vàocả bộ điều khiển Lead.

5

Page 116: Matlab Tutorial

Root Locus ExamplesĐiều khiển xe | Điều khiển tốc độ động cơ | Điều khiển góc quay động cơ | Bus Suspension |Inverted Pendulum | Pitch Controller | Ball and Beam

Motor Speed ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

6

Page 117: Matlab Tutorial

Ví dụ: Phương pháp quỹ tích nghiệm cho điềukhiển góc quay động cơ 1 chiều

Vẽ quỹ đạo nghiệm hệ hởTối giản hóa mô hìnhĐiều khiển Tích phânĐiều khiển Tỉ lệ-Tích phânĐiều khiển Tỉ lệ-Tích phân-Vi phânTìm hệ số sử dụng lệnh rlocfind và vẽ đáp ứng của hệ điều khiể kín

Từ bài toán chính, phương trình động lực học và hàm truyền của hệ thống như sau:

và sơ đồ khối của hệ thống như sau:

Để biết cách thiết lập hệ mô hình trên, tham khảo phần Mô hình động cơ điện 1 chiều.

Với đầu vào tín hiệu bậc thang 1 rad, mục tiêu điều khiển là:

Thời gian quá độ nhỏ hơn 0.04 giâyĐộ quá điều chỉnh nhỏ hơn 16%Không có sai số xác lập với đầu vào referenceKhông có sai số xác lập do nhiễu

Ta sẽ thiết kế bộ điều khiển bằng phương pháp quỹ tích nghiệm.

Tạo 1 m-file có các lệnh sau để lập hàm truyền (thao khảo phần mô hình).

J=3.2284E-6;b=3.5077E-6;K=0.0274;R=4;L=2.75E-6;

1

Page 118: Matlab Tutorial

num=K;den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2) 0];motor=tf(num,den);

Vẽ quỹ tích nghiệm của hệ hở

Mục đích chính của việc tìm quỹ tích nghiệm là xác định đáp ứng của hệ kín từ quỹ tích nghiệm củahệ hở. Sau đó bằng cách thêm vào khâu chấp hành các điểm cực hoặc điểm không để sửa đổi đáp ứngcủa hệ kín theo yêu cầu. Trước tiên ta hãy xem xét quỹ tích nghiệm của khâu chấp hành. Thêm cáclệnh sau vào m-file.

rlocus(motor)sgrid(.5,0)sigrid(100)

Hàm sigrid là một hàm do người dùng tạo ra. Ta cần copy file sigrid.m vào cùng thư mục với m-filecủa ta để có thể gọi dẽ dàng. Để biết hàm này có chức năng gì, tham khảo phần functions.

Hai đối số của lệnh sgrid là hệ số về giảm chấn zeta (0,5 tương ứng với độ quá điều chỉnh là 16%), vàvề tần số dao động riêng Wn (= 0 nghĩa là không có điều kiện về thời gian quá độ). Đối số duy nhấtcủa lệnh sigrid là sigma (4/0,04 giây = 100). Sau khi đã có file sigrid.m trong thư mục hiện hành, chạym-file trên ta sẽ có quỹ tích nghiệm như sau:

Nhìn vào tỉ lệ xích của các trục ta thấy có 1 điểm cực ở rất xa về phía trái (xa hơn -1x10^6). Điểm cựcnày không ảnh hưởng tới quá trình động lực học của hệ kín trừ khi ta sử dụng các hệ số rất lớn, ở đóhệ thống trở nên mất ổn định. Chúng ta bỏ qua điểm cực này và thực hiện tối giản hoá mô hình hệthống.

Tối giản hóa mô hình hệ thống

Nếu hàm truyền có 1 cực (hoặc hơn) ở xa về phía bên trái so với các cực chính, thì cực này sẽ khôngảnh hưởng lắm tới hệ thống với các hệ số nhỏ (với hệ số lớn các cực này sẽ đẩy quỹ tích nghiệm sangphía phải mặt phẳng toạ độ, dẫn đến mất ổn định). Có một cách để có thể bỏ qua cực này là giữ hệ số

2

Page 119: Matlab Tutorial

DC của hàm truyền là hằng bằng cách xấp xỉ như sau:

Ta hãy xem các điểm cực của hàm truyền là gì. Gọi lệnh sau trong Matlab:

roots(den)

Ta có kết quả sau:

ans =

1.0e+06 *

0 -1.4545 -0.0001

Ta muốn bỏ qua điểm cực -1.45e6. Thực hiện điều này bằng đoạn lệnh sau:

J=3.2284E-6;b=3.5077E-6;K=0.0274;R=4;L=2.75E-6;num=K;den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2) 0];poles=roots(den);den2=deconv(den,[1/max(abs(poles)) 1]);

motor=tf(num,den2);

Bây giờ ta có thể kiểm tra lại bằng lệnh

roots(den2)

trong cửa sổ lệnh của Matlab.

Bây giờ ta vẽ quỹ đạo nghiệm của hệ đã được tối giản. Thêm những lệnh sau vào m-file trên.

rlocus(motor)sgrid(.5,0)sigrid(100)

Ta có quỹ tích nghiệm như sau và có thể thấy chỉ với các hệ số nhỏ là hệ kín sẽ ổn định.

3

Page 120: Matlab Tutorial

Từ quỹ tích nghiệm trên ta thấy, các cực của hệ kín không bao giờ đủ nhanh để thoả mãn tốt điều kiệnvề thời gian ổn định (nghĩa là chúng không bao giờ tiến tới đường thẳng đứng sigma=100). Và cũngcần nhớ rằng ta phải thêm vào luật điều khiển tích phân cho bộ điều khiển (không chỉ cho hệ thống)để khử sai số xác lập do nhiễu gây nên.

Điều khiển tích phân

Ta hãy thử thêm điều khiển tích phân để khử sai số xác lập do nhiễu. Sửa lại m-file như sau:

J=3.2284E-6;b=3.5077E-6;K=0.0274;R=4;L=2.75E-6;num=K;den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2) 0];poles=roots(den);den2=deconv(den,[1/max(abs(poles)) 1]);motor=tf(num,den2);

contr=tf(1,[1 0]);

rlocus(contr*motor)sgrid(.5,0)sigrid(100)

Như trên là ta đã nhân hệ hở với 1/s. Chạy m-file và ta có quỹ tích nghiệm sau.

4

Page 121: Matlab Tutorial

Từ quỹ tích trên ta thấy hệ kín sẽ không thể ổn định được, do vậy ở đây ta phải sử dụng bộ điều khiểnkhác.

Điều khiển Tỉ lệ-Tích phân

Bây giờ ta sửa bộ điều khiển tích phân thành bộ điề khiển PI. Việc sử dụng bộ điều khiển PI thay cho Isẽ thêm 1 điểm không vào hệ hở. Ta cho điểm không này là s=-20. Điểm không này sẽ nằm giữa cácđiểm cực của hệ hở và trong trường hợp này hệ kín sẽ trở nên ổn định. Thay đổi câu lệnh thiết lập bộđiều khiển trong m-file như sau:

contr=tf([1 20],[1 0]);

Chạy m-file mới ta sẽ có quỹ tích nghiệm sau.

Chú ý: Ta có thể không có được hình vẽ như trên trong Matlab, điều này phụ thuộc vàobạn sử dụng version nào của lệnh rlocus. Nếu không được quỹ đạo như trên, hoặc không

5

Page 122: Matlab Tutorial

được như ý, bạn sẽ phải xác định các hệ số mà bạn muốn Matlab biểu diễn. Trong trườnghợp này lệnh sau cho ta biểu diễn tốt hơn.

gain = 0:0.1:20;rlocus(contr*motor,gain)

Bây giờ ta đã ổn định được hệ thống và không có sai số xác lập do nhiễu, nhưng đáp ứng của hệ thốngvẫn chưa đủ nhanh.

Điều khiển Tỉ lệ-Tích phân-Vi phân

Để kéo quỹ đạo nghiệm dịch về phía trái cho đáp ứng của hệ thống nhanh hơn, ta cần thêm 1 điểmkhông nữa vào hệ hở, kết quả là ta có một bộ điều khiển PID. Sau một số lần thử, ta có thể chọn haiđiểm không là s=-60 và s=-70. Thay đổi lại đoạn mã lệnh xác định bộ điều khiển trong m-file.

numc=conv([1 60],[1 70]);denc=[1 0];contr=tf(numc,denc);

Chạy m-file và ta có quỹ tích nghiệm sau.

Bây giờ ta có thể thấy có các điểm cực của hệ kín nằm trong vùng thoả mãn cả về thời gian quá độ vàđộ quá điều chỉnh. Điểm cực thứ ba của hê hở chạy từ cực s=-59.2 tới điểm không s=-60. Điểm cựcnày của hệ kín ở rất sát điểm không (điểm này vẫn tồn tại ở hàm truyền của hệ kín). Do vậy, ta có thểbỏ qua ảnh hưởng của của điểm cực này. Tuy nhiên, điểm không của hệ hở vẫn tồn tại trên hệ kín, nósẽ ảnh hưởng đến đáp ứng của hệ thống làm cho hệ thống đáp ứng chậm đi và tăng độ quá điều chỉnh.Vì thế, ta phải chú ý khi chọn vị trí của điểm cực trên quỹ tích nghiệm.

Tìm hệ số bằng lệnh rlocfind

Mục tiêu của chúng ta là giảm thời gian quá độ và độ quá điều chỉnh càng nhỏ càng tốt, đặc biệt làgiảm ảnh hưởng của điểm không mới. Độ giảm chấn lớn ứng với các điểm trên quỹ tích nghiệm nằmgần trục thực. Khả năng đáp ứng nhanh tương ứng với các điểm nằm xa về phía trái trục ảo. Để tìm hệsố tương ứng với 1 điểm trên quỹ đạo nghiệm ta dùng lệnh rlocfind. Chúng ta cũng vẽ đáp ứng của hệ

6

Page 123: Matlab Tutorial

thống với hệ số đó luôn. Thực hiện điều này bằng cách lập trình cho m-file như dưới đây và chạychương trình.

[k,poles] = rlocfind(contr*motor)sys_cl=feedback(k*contr*motor,1);t=0:0.001:.1; step(sys_cl,t)

Chọn trên đồ thị điểm nằm về phía bên trái của đường cong và nằm gần trục thực (dấu + như hình bêndưới). Điểm này sẽ cho ta đáp ứng nhanh và độ quá điều chỉnh bé nhất. Ví trí các điểm cực này cho tađộ quá điều chỉnh nhỏ nhất, và lưu ý là điểm không thì lại làm tăng độ quá điều chỉnh.

Sau khi chọn điểm xong, ta sẽ có kết quả trong cửa sổ lệnh Matlab như sau.

selected_point =

-1.3943e+02+ 1.8502e+01i

k =

0.1309

poles =

1.0e+06 *

-1.4542 -0.0001 + 0.0000i -0.0001 - 0.0000i -0.0001

Lưu ý là có thể kết quả do bạn chọn sẽ không chính xác như trên, nhưng cũng phải xấp xỉ. Và ta cũngcó đáp ứng của hệ thống với các hệ số như sau:

7

Page 124: Matlab Tutorial

Như ta thấy, độ quá điều chỉnh khoảng 15%, thời gian quá độ xấp xỉ 0,04 giây, không có sai số thiếtlập.

Bây giờ ta hãy xem ảnh hưởng của nhiễu như thế nào, lập hàm truyền của nhiễu và vẽ đáp ứng bằngcác lệnh sau.

dist_cl=feedback(motor,k*contr);step(dist_cl,t)

Chạy m-file, chọn lại điểm trên quỹ tích nghiệm như khi nãy ta được đáp ứng với nhiễu như sau.

Như ta thấy sai số xác lập do nhiễu gần bằng 0, thực tế là khoảng 0,02 (hay 2%) sau 0,04 giây. Do đó,chỉ tiêu thiết kế đã được thoả mãn.

Trong ví dụ này, ta được quyền lựa chọn vị trí của điểm không . Do đó cần 1 số lần thử sai, điều nàygiúp ta hiểu rõ hơn về cách vẽ quỹ tích nghiệm, công cụ Matlab đã giúp chúng ta xác minh và chọnlọc vị trí theo để đạt được kết quả mong muốn.

8

Page 125: Matlab Tutorial

Root Locus ExamplesĐiều khiển xe | Điều khiển tốc độ động cơ | Điều khiển góc quay động cơ | Bus Suspension |Điều khiển con lắc ngược | Pitch Controller | Bài toán bóng và thanh đỡ

Motor Position ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

9

Page 126: Matlab Tutorial

Example: Root Locus Design Method for the BusSuspension System

Plotting the root locusAdding a notch filterFinding the gain from the root locusPlotting closed-loop response

From the main problem, the dynamic equations in transfer function form are the following:

and the system schematic looks like:

For the original problem setup and the derivation of the above equations and schematic, please refer to the busmodeling page.

If you are interested in running an animation of this example based on the control techniques used in the rootlocus tutorial please go to the bus suspension animation page after completing this tutorial.

We want to design a feedback controller so that when the road disturbance (W) is simulated by a unit step input,the output (X1-X2) has a settling time less than 5 seconds and an overshoot less than 5%. For example, when thebus runs onto a 10 cm high step, the bus body will oscillate within a range of +/- 5 mm and will stop oscillatingwithin 5 seconds.

The system model can be represented in MATLAB by creating a new m-file and entering the following commands(refer to main problem for the details of getting those commands).

m1=2500;m2=320;k1 = 80000;k2 = 500000;b1 = 350;b2 = 15020;

1

Page 127: Matlab Tutorial

nump=[(m1+m2) b2 k2];denp=[(m1*m2) (m1*(b1+b2))+(m2*b1) (m1*(k1+k2))+(m2*k1)+(b1*b2) (b1*k2)+(b2*k1) k1*k2];G1=tf(nump,denp);

num1=[-(m1*b2) -(m1*k2) 0 0];den1=[(m1*m2) (m1*(b1+b2))+(m2*b1) (m1*(k1+k2))+(m2*k1)+(b1*b2) (b1*k2)+(b2*k1) k1*k2];G2=tf(num1,den1);

numf=num1;denf=nump;F=tf(numf,denf);

We are now ready to design a controller using the root locus design method.

First let's see what the open loop poles of the system are:

R=roots(denp)

MATLAB should return:

R = -23.9758 +35.1869i -23.9758 -35.1869i -0.1098 + 5.2504i -0.1098 - 5.2504i

Therefore the dominant poles are the roots -0.1098+/-5.2504i, which are close to the imaginary axis with a smalldamping ratio.

Plotting the root locus

The main idea of root locus design is to estimate the closed-loop response from the open-loop root locus plot. Byadding zeros and/or poles to the original system (adding a compensator), the root locus and thus the closed-loopresponse will be modified. Let's first view the root locus for the plant. In your m-file, add the following commandand then run the file, you should get the root locus plot below:

rlocus(G1)z=-log(0.05)/sqrt(pi^2+(log(0.05)^2))sgrid(z,0)

Note from the specification, we required the overshoot, %OS, to be less than 5% and damping ratio, zeta, can be

2

Page 128: Matlab Tutorial

find from approximation damping ratio equation, z = -log(%OS/100)/sqrt(pi^2+[log(%OS/100)^2]). The commandsgrid is used to overlay the desired percent overshoot line on the close-up root locus; you can find moreinformation from commands list.

From the plot above, we see that there are two pair of poles and zeros that are very close together. These polesand zeros are almost on the imaginary axis, they might make the bus system marginally stable, which might causea problem. We have to make all of the poles and zeros move into the left-half plane as far as possible to avoid anunstable system. We have to put two zeros very close to the two poles on the imaginary axis of uncompensatedsystem for pole-and-zero cancellation. Moreover, we will put another two poles further to the left on the real axisto get fast response.

Adding a notch filter

We will probably need two zeros near the two poles on the complex axis to draw the root locus, leading thosepoles to the compensator zeros instead of to the plant zeros on the imaginary axis. We'll also need two polesplaced far to the left to pull the locus to the left. It seems that a notch filter (2-lead controller) will probably do thejob. Let's try putting the poles at 30 and 60 and the zeros at 3+/-3.5i. In your m-file add the following lines ofcode:

z1=3+3.5i;z2=3-3.5i;p1=30;p2=60;numc=conv([1 z1],[1 z2]);denc=conv([1 p1],[1 p2]);contr=tf(numc,denc);

rlocus(contr*G1)

Rerun the m-file; you should get a new root locus plot looking like this:

Now let's change the axis to see the details of the root locus.

axis([-40 10 -30 30])z=-log(0.05)/sqrt(pi^2+(log(0.05)^2))sgrid(z,0)

3

Page 129: Matlab Tutorial

Finding the gain from the root locus

Now that we have moved the root locus across the 5% damping ratio line, we can choose a gain that will satisfythe design requirements. Recall that we want the settling time and the overshoot to be as small as possible.Generally, to get a small overshoot and a fast response, we need to select a gain corresponding to a point on theroot locus near the real axis and far from the imaginary axis or the point that the root locus crosses the desireddamping ratio line. But in this case, we need the cancellation of poles and zeros near the imaginary axis, so weneed to select a gain corresponding to a point on the root locus near the zeros and percent overshoot line. There isa method to do this with the rlocfind command in MATLAB. Enter the following command into the MATLABcommand window:

[k,poles]=rlocfind(contr*G1)

Go to the plot and select the point at the position mentioned above (indicated by the cross on the plot below:

You should see something similar to the following:

4

Page 130: Matlab Tutorial

selected_point =

-2.9428 -13.0435i

K =

1.0678e+08

poles =

1.0e+02 *

-0.6322 + 6.1536i -0.6322 - 6.1536i -0.0294 + 0.1306i -0.0294 - 0.1306i -0.0292 + 0.0367i -0.0292 - 0.0367i

Note that the value returned from your MATLAB command window may not be exactly the same, but should atleast have the same order of magnitude. This returned value can be used as the gain for the compensator. Recallthat the schematic of the system is the following:

and the closed-loop transfer function can be derived as following:

sys_cl=F*feedback(G1,k*contr);

Plotting the closed-loop response

Let's see what the closed-loop step response looks like with this compensator. Keep in mind that we are going touse a 0.1 m high step as the disturbance. To simulate this, simply multiply sys_cl by 0.1. Add the followingcommands into the m-file and put % marks in front of all rlocus and rlocfind commands.

t=0:0.01:2;step(0.1*sys_cl,t)title('closed-loop response to 0.1m high step w/ notch filter')

and you should see the following plot:

5

Page 131: Matlab Tutorial

From this plot we see that when the bus encounters a 0.1 m step on the road, the maximum deviation of the busbody from the wheel (or the road) is about 3.75 mm, and the oscillations settle in 2 seconds. Thus this response issatisfactory.

Note: A design problem does not necessarily have an unique answer. Using the root locus method (or any othermethod) may result in many different compensators. For practice, you may want to go back to the originalopen-loop root locus and try to find other good ways to add zeros and poles to get a better response.

If you are interested in running an animation of the bus suspension example based on the control techniques usedin this tutorial please go to the Bus Suspension Animation Page.

Root Locus ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | Pitch Controller | Balland Beam

Bus Suspension ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink | Animation

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

6

Page 132: Matlab Tutorial

Ví dụ: Giải pháp điều khiển con lắc ngược bằng phương pháp quỹ tích nghiệm

Hàm truyềnThiết kế quỹ đạo nghiệmBộ điều khiển Lead-lagĐiều gì xảy ra với vị trí của xe

Hàm truyền của khâu chấp hành như sau:

ở đây,

Mục tiêu thiết kế (với điều kiện ban đầu con lắc nhận được 1 xung lực 1N từ xe) đặt ra là:

Thời gian ổn định nhỏ hơn 5 giây.Con lắc dao động không quá 0,05 rad xung quanh trục thẳng đứng.

Để biết cách thiết lập mô hình, tham khảo phần mô hình con lắc ngược.

Hàm truyền

Lệnh rlocus trong Matlab cho ta quỹ tích nghiệm của hệ thống được mô tả bởi phương trình trongkhông gian trạng thái hoặc hàm truyền. Với bài toán này ta sử dụng hàm truyền sẽ thuận tiện hơn (lýdo chúng ta sẽ tìm hiểu sau). Hàm truyền được lập nên từ phép biến đổi Laplace với đầu ra Phi (gócquay của con lắc) được thiết lập trong Matlab bằng cách khai báo tử số và mẫu số như hai vecto. Tạo1 m-file có đoạn mã lệnh sau:

M = .5;m = 0.2;b = 0.1;i = 0.006;g = 9.8;

1

Page 133: Matlab Tutorial

l = 0.3;

q = (M+m)*(i+m*l^2)-(m*l)^2; %simplifies input

num = [m*l/q 0];den = [1 b*(i+m*l^2)/q -(M+m)*m*g*l/q -b*m*g*l/q];pend=tf(num,den);

Sơ đồ khối hệ thống

Mô hình của hệ thống này có thể hơi khác so với những mô hình truyền thống mà ta quen biết. Do vậyở đây đặt bài toán là điều khiển con lắc ở vị trí thăng bằng với đầu vào nhiễu là một xung lực ban đầu,tín hiệu reference là 0. Xung lực ban đầu ở đây chính là một xung nhiễu. Sơ đồ hệ thống như vậy sẽ códạng sau.

Để dễ dàng chuyển đổi thành hàm truyền trong Matlab ta biến đổi tương đương thành sơ đồ sau:

Thiết kế quỹ tích nghiệm

Hàm truyền của hệ kín này có thể được biểu diễn trong Matlab. Điều đầu tiên cần làm là khảo sát quỹtích nghiệm của khâu chấp hành khi chưa có khâu bù. Khi chọn hệ số điều khiển tỉ lệ cần nhớ rằngthời gian quá độ phải nhỏ hơn 5 giây. Điều này nghĩa là sigma lớn hơn 4,6/5=0,92. Ta có thể đặt điềukiện này lên quỹ tích nghiệm bằng cách sử dụng hàm sigrid, hàm này có thể được lưu trong 1 m-file.Để vẽ quỹ tích nghiệm, thêm các lệnh sau vào m-file :

rlocus(pend)sigrid(0.92)axis([-6 6 -6 6])

Sau khi chạy ta có quỹ đạo nghiệm như sau:

2

Page 134: Matlab Tutorial

Như ta thấy, có 1 nghiệm của hàm truyền hệ kín nằm phía nửa bên phải mặt phẳng toạ độ, nghĩa là hệthống sẽ mất ổn định. Hãy nhìn vào quỹ tích nghiệm để biết tại sao. Một phần của quỹ tích nghiệmnằm giữa gốc tọa độ và điểm cực bên phải mặt phẳng toạ độ. Do vậy mà cho dù chọn hệ số như thếnào thì ta vẫn luôn có 1 cực nằm ở vùng này và nó làm đáp ứng xung của hệ thống mất ổn định. Đểgiải quyết vấn đề này, ta cần thêm vào gốc toạ độ một điểm cực, để các điểm không và điểm cực tạigốc toạ độ triệt tiêu lẫn nhau và làm xuất hiện các nghiệm bội ở nửa bên phải mặt phẳng toạ độ. Cácnghiệm bội có thể được dịch về nửa phía trái mặt phẳng toạ độ để hoàn tất mục tiêu đề ra. Thêm cáccâu lệnh sau vào m-file:

contr=tf(1,[1 0]);rlocus(contr*pend)sigrid(0.92)axis([-10 10 -10 10])

Ta có quỹ tích nghiệm với các nghiệm bội ở nửa bên phải mặt phẳng toạ độ như sau:

3

Page 135: Matlab Tutorial

Bây giờ ta hãy thử vẽ các nhánh của quỹ tích nghiệm về phía bên trái của mặt phẳng toạ độ. Thêmvào m-file các lệnh sau:

[num,den]=tfdata(contr*pend,'v');roots(num)roots(den)

Ta sẽ có kết quả sau trong cửa sổ lệnh Matlab,

ans = 0 ans = 0 -5.6041 5.5651 -0.1428

Bây giờ ta có 4 cực và 1 điểm không. Điều này nghĩa là sẽ có 3 đường tiệm cận: một đường dọc theochiều âm của trục thực, hai đường còn lại ở vị trí 120o so với đường thứ nhất.

Nhưng với dạng đường này ta sẽ không thể có các nghiệm bội ở nửa bên trái mặt phẳng toạ độ. Chúngta cần giảm số lượng đường tiệm cận xuống còn 2 bằng cách thêm 1 điểm không nữa vào bộ điềukhiển. Nếu chỉ có 1 điểm không được thêm vào thì giao điểm alpha của các đường tiệm cận sẽ là[(-5.6041+5.5651-0.1428+0+0)-(0+0+z2)]/2. Điều này nghĩa là hai đường tiệm cận sẽ là -0.1-(1/2)z2.Cho dù chọn z2 nhỏ nhất có thể (giả sử là ở sát gốc toạ độ) thì cũng không thể đẩy các nghiệm bội rađủ xa về phía bên trái mặt phẳng toạ độ để đạt được các chỉ tiêu điều khiển đề ra (giao điểm cácđường tiệm cận sẽ gần điểm trên trục thực-0.1).

Bộ điều khiển Lead-lag

Giải pháp cho vấn đề này là thêm 1 điểm cực xa hẳn về phía trái so với các điểm cực và điểm không

4

Page 136: Matlab Tutorial

khác. Và để giữ nguyên số đường tiệm cận, ta cũng cần thêm 1 điểm không nữa. Cách xác định vị tríđiểm cực và điểm không là không quan trọng trừ việc giá trị của điểm cực phải tương đối lớn và giá trịcủa điểm không phải tương đối nhỏ.

Hãy thử chạy m-file sau và xem ảnh hưởng của các điểm cực và điểm không lên quỹ tích nghiệm.

M = .5;m = 0.2;b = 0.1;i = 0.006;g = 9.8;l = 0.3;

q = (M+m)*(i+m*l^2)-(m*l)^2; %simplifies input

num = [m*l/q 0];den = [1 b*(i+m*l^2)/q -(M+m)*m*g*l/q -b*m*g*l/q];pend=tf(num,den);

z1 = 3;p1 = 0;z2 = 4;p2 = 50;numlag = [1 z1];denlag = [1 p1];numlead = [1 z2];denlead = [1 p2];numc = conv(numlead, numlag);denc = conv(denlead, denlag);contr=tf(numc,denc);

rlocus(contr*pend)sigrid(0.92)axis([-50 50 -50 50])figurerlocus(contr*pend)sigrid(0.92)axis([-10 10 -10 10])[k,poles]=rlocfind(contr*pend)sys_cl=feedback(pend,k*contr);

figureimpulse(sys_cl)axis([0 2 -0.05 0.05])

Chú ý: Với 1 số version của Matlab, quỹ tích nghiệm đôi khi không được chính xác vìvecto hệ số được chọn 1 cách tự động. Nếu điều này xảy ra với version của bạn thì bạnnên truy cập vào trang chủ MathWorks để download phần sửa lỗi. Bạn cũng có thể tự đặtcho biết Matlab miền tham số nào mà bạn đang quan tâm. Trong trường hợp đó, các lệnhsau được dùng thay cho lệnh rlocus.

gain=0:10:2000;rlocus(contr*pend,gain)

Quỹ tích nghiệm sẽ được vẽ bởi dấu "x" thay vì đường nét liền, nhưng lệnh rlocfind vẫnsẽ được thực hiện đúng đắn.

Các điểm cực và điểm không được xác định sau 1 số lần thử sai. Bạn chỉ cần nhớ là ta cần phải có 1điểm cực ở gốc toạ độ và 1 điểm cực khác ở xa về phía bên trái mặt phẳng toạ độ, và hai điểm cực

5

Page 137: Matlab Tutorial

phải tương đối nhỏ. Hơn nữa, hai điểm không mà khá gần nhau và gần về phía phải của điểm cực xanhất ở bên trái thì càng tốt. Ta sẽ thấy đồ thị thứ nhất của quỹ tích nghiệm tương ứng với các điểm cựcvà điểm không ở trên:

Đồ thị thứ hai là phóng to của đồ thị thứ nhất để nhìn rõ thấy vùng gần gốc toạ độ.

Khi chọn 1 điểm trên quỹ tích nghiệm, chọn 1 điểm trên các nghiệm bội trước khi nó quay về trụcthực. Đáp ứng xung của ta sẽ có dạng sau:

6

Page 138: Matlab Tutorial

Đáp ứng trên đã thoả mãn các yêu cầu đặt ra và ta không cần điều chỉnh thêm gì nữa.

Điều gì xảy ra với vị trí của xe?

Ngay từ đầu, chúng ta đã đưa ra mô hình của hệ thống. Nhưng mô hình đó chưa thực sự hoàn thiện.Chúng ta đã bỏ qua dịch chuyển của xe vì ta đang quan tâm tới góc quay của con lắc. Sẽ rất hay nếuta xem xét dịch chuyển của xe ra sao khi ta đang điều khiển góc quay của con lắc. Để có thể, trướchết ta xem sơ đồ khối thực tế như sau:

Biến đổi lại 1 chút ta có sơ đồ khối như sau:

Vòng kín ở trên là hệ thống ta vừa thiết kế với bộ điều khiển PID cho góc quay con lắc. Hàm truyềnvới đầu ra là dịch chuyển của xe bây giờ như sau:

7

Page 139: Matlab Tutorial

Bây giờ ta đã có thể xây dựng hàm truyền cho toàn bộ hệ thống, hãy xem đáp ứng của nó ra sao.Trước hết ta tìm hàm truyền cho dich chuyển của xe. Để có đuợc điều này ta phải sử dụng biến đổiLaplace cho phương trình hệ thống rồi tìm mối liên hệ giữa X(s) và U(s). Ta có phương trình sau:

ở đây,

Để biết thêm về biến đổi Laplace tham khảo phần mô hình con lắc ngược.

Thêm đoạn lệnh sau vào m-file và cho chạy:

num2 = [(i+m*l^2)/q 0 -m*g*l/q];den2 = [1 b*(i+m*l^2)/q -(M+m)*m*g*l/q -b*m*g*l/q 0];G2=tf(num2,den2);

figure;t=0:0.01:6;subplot(2,1,1);impulse(sys_cl,t)axis([0 6 -0.05 0.05])subplot(2,1,2);xpos=feedback(1,k*contr*pend)*G2;impulse(xpos,t)axis([0 6 -0.1 0.1])

Ta sẽ có đáp ứng như sau:

8

Page 140: Matlab Tutorial

Đáp ứng phía trên là góc quay của con lắc, đáp ứng phía dưới là vị trí của xe. Như ta thấy, lúc đầu xecó dịch chuyển , sau đó vị trí ổn định trong khoảng 5 giây, rồi bị mất ổn định. Có thể trên thực tế masát (bị bỏ qua ở mô hình này) sẽ làm cho xe ổn định. Hãy nhớ là trên thực tế có xảy ra như vậy,nhưng nó có là nhờ may mắn, bởi ta đâu có đặt vấn đề điều khiển vị trí của xe.

Root Locus ExamplesĐiều khiển xe | Điều khiển tốc độ động cơ | Điều khiển góc quay động cơ | Bus Suspension |Điều khiển con lắc ngược | Pitch Controller | Bài toán bóng và thanh đỡ

Inverted Pendulum ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

9

Page 141: Matlab Tutorial

Example: Root-Locus Design method for the PitchController

Original root-locus plotLead compensatorQuick summary

In the Pitch Controller Modeling page, the transfer function was derived as

The input (elevator deflection angle, delta e) will be 0.2 rad (11 degrees), and the output is the pitchangle (theta).

The design requirements are

Overshoot: Less than 10%Rise time: Less than 2 secondsSettling time: Less than 10 secondsSteady-state error: Less than 2%

To see the original problem setup, please refer to the Pitch Controller Modeling page.

Original root-locus plot

Recall from the Root-Locus Tutorial page, a root-locus plot shows all possible closed-loop polelocations for a pure proportional controller. Since not all poles are acceptable, the MATLABfunction called sgrid should be used to find an acceptable region of the locus. This sgrid functionrequires two arguments: Natural frequency (Wn) and damping ratio (zeta). These two arguments canbe determined from the rise time, the settling time, and the overshoot requirements and threeequations shown below.

where,

1

Page 142: Matlab Tutorial

Wn=Natural frequencyzeta=Damping ratioTs=Settling timeTr=Rise timeMp=Maximum overshoot

From these three equations, we can determine that the natural frequency (Wn) must be greater than0.9 and the damping ratio (zeta) must be greater than 0.52.

Let's generate a root-locus plot and use the sgrid to find the acceptable region of the locus. Create anew m-file and enter the following commands:

num=[1.151 0.1774];den=[1 0.739 0.921 0];plant=tf(num,den);Wn=0.9;zeta=0.52;

rlocus (plant)sgrid (zeta,Wn)axis ([-1 0 -2.5 2.5])

Run this m-file in the MATLAB command window. You should see the root-locus plot similar to theone shown below:

The two dotted lines in an angle indicate the locations of constant damping ratio, and the dampingratio is greater than 0.52 in between these lines. The dotted semi-ellipse indicates the locations ofconstant natural frequency, and the natural frequency is greater than 0.9 outside the semi-ellipse (thiswould be a semi-circle if the axes were uniformly scaled). As you may have noticed, there is noroot-locus plotted in our desired region. We need to bring the root-locus in between two dotted linesand outside the semi-ellipse by modifying the controller.

Lead compensator

We need to shift the root-locus more toward the left to get it inside our desired region. If you refer tothe Designing Lead and Lag Compensators page, you will notice that the lead compensator can move

2

Page 143: Matlab Tutorial

the root locus to the left. The transfer function of a typical lead compensator is:

Zo=zeroPo=poleZo < Po

In general, the zero is placed in the neighborhood of the natural frequency criterion, and the pole isplaced at a distance 3 to 20 times the value of the zero location. Let's place the zero (Zo) at 0.9 andthe pole (Zo) at 20.

Let the MATLAB functions conv and feedback determine the closed-loop transfer function with thelead compensator. Enter the following commands to an new m-file and run it in the MATLABcommand window. You should obtain the following root-locus plot:

num=[1.151 0.1774];den=[1 0.739 0.921 0];plant=tf(num,den);

Zo=0.9;Po=20;contr=tf([1 Zo],[1 Po]);

Wn=0.9; zeta=0.52;rlocus (contr*plant)axis ([-3 0 -2 2])sgrid (zeta,Wn)

The root-locus has been generated in our desired region. Now, we are ready to pick a gain (K) andgenerate the step response corresponding to that gain. Add the following commands to the m-fileshown above and run it in the command window. You should see a prompt asking you to pick a pointon the root-locus plot. Pick a point close to the zero on the natural frequency criterion, say around -1on real axis. This point should give you a gain around 200. You should see a step response similar tothe one shown below.

[K, poles]=rlocfind (contr*plant)

3

Page 144: Matlab Tutorial

de=0.2;sys_cl=feedback (K*contr*plant,1); step(sys_cl)

This response satisfies all the design requirements.

How to solve a problem using Root-Locus method: QuickSummary

Obtain a root-locus plot with the sgrid using the original plant transfer function.1.Add a lead (or lag) compensator to bring the root-locus to the desired region, if necessary.2.Pick a point on the root-locus and obtain the corresponding gain (K).3.Generate the step response with the chosen gain (K).4.Determine what needs to be changed from the step response.5.Add or modify the lead (or lag or lead-lag) compensator.6.Obtain new root-locus plot with the sgrid command active.7.Repeat steps 3 to 7 until you obtain a satisfactory result.8.

Root-Locus ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchControl | Ball and Beam

Pitch Controller ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control| Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

4

Page 145: Matlab Tutorial

Ví dụ: Giải pháp cho bài toán Bóng & Thanh đỡ sửdụng phương pháp quỹ tích nghiệm

Quỹ tích nghiệm hệ hởBộ điều khiển LeadChọn hệ sốVẽ đáp ứng của hệ kín

Hàm truyền hệ thống hở đã thiết lập trong phần mô hình như sau:

Mục tiêu điều khiển:

Thời gian quá độ nhỏ hơn 3 giâyĐộ quá điều chỉnh nhỏ hơn 5%

Để biết cách thiết lập mô hình toán học trên, tham khảo phần mô hình bóng và thanh đỡ. Sơ đồ khốihệ thống điều khiển vòng kín như sau:

Quỹ tích nghiệm của hệ hở

Ý tưởng chính của việc thiết kế quỹ tích nghiệm là ước đoán đáp ứng của hệ kín thông qua quỹ tíchnghiệm của hệ hở. Bằng cách thêm vào hệ thống các điểm không và điểm cực (thêm khâu bù), quỹtích nghiệm và đáp ứng của hệ kín sẽ được điều chỉnh theo ý muốn. Trước hết chúng ta hãy khảo sátquỹ tích nghiệm của hệ hở. Tạo 1 m-file với các lệnh sau để lập mô hình hệ hở và vẽ quỹ tích nghiệm.

m = 0.111;R = 0.015;g = -9.8;L = 1.0;d = 0.03;J = 9.99e-6;

K = (m*g*d)/(L*(J/R^2+m)); %simplifies input

1

Page 146: Matlab Tutorial

num = [-K];den = [1 0 0];plant=tf(num,den);

rlocus(plant)

Chạy m-file ta sẽ có quỹ tích nghiệm như sau:

Như ta thấy, hệ thống có hai điểm cực tại gốc toạ độ và đi về vô cùng dọc theo trục ảo.

Tiêu chuẩn điều khiển cũng được biểu diễn bằng lệnh sgrid. Lệnh này sẽ tạo ta 1 lưới cố định phụthuộc vào giá trị hệ số giảm chấn và tần số dao động riêng. Hệ số giảm chấn và tần số dao đọng riêngtính theo hai phương trình sau, chúng phụ thuộc vào phần trăm độ quá điều chỉnh (PO) và thời gianquá độ (Ts):

Chú ý, phương trình với Ts được lập nên khi đáp ứng đã đạt tới lân cận trong khoảng 2% so với giá trịổn định cuối cùng. Từ các phương trình trên, từ các phương trình trên ta tính được hệ số giảm chấn vàtần số dao động riêng là 0.7 và 1.9.

sgrid(0.70, 1.9)axis([-5 5 -2 2])

2

Page 147: Matlab Tutorial

Vùng giới hạn bởi các đường gạch chéo là vùng độ quá điều chỉnh nhỏ hơn 5%. Vùng bên ngoài nửađường cong elip là vùng thời gian quá độ nhỏ hơn 3 giây. Ta chú ý và thấy là quỹ đạo nghiệm khôngcó điểm nào nằm vào vùng thoả mãn mục tiêu điều khiển. Để giải quyết vấn đề này ta phải làm saodịch quỹ đạo nghiệm về phía bên trái, ta sẽ thêm vào hệ thống khâu bù lead.

Bộ điều khiển Lead

Trước tiên ta chỉ quan tâm tới tác dụng của bộ điều khiển Lead là làm cho quỹ đạo nghiệm dịch vềphía trái mặt phẳng toạ độ. Để biết chi tiết hơn về bộ điều khiển này, tham khảo phần Thiết kế khâubù Lead & Lag. Một khâu bù Lead có hàm truyền như sau:

ở đây, zo bé hơn po.

Bây giờ ta sẽ thêm bộ điều khiển Lead vào và xem quỹ tích nghiệm bây giờ thay đổi như thế nào. Tasẽ đặt một điểm không ở gần gốc toạ độ để khử đi một cực. Cực của khâu bù sẽ được đặt ở phía bêntrái gốc toạ độ để kéo quỹ tích nghiệm về phía trái mặt phẳng toạ độ. Thêm các lệnh sau vào m-file.

zo = 0.01;po = 5;contr=tf([1 zo],[1 po]);

rlocus(contr*plant)sgrid(0.70, 1.9)

Chạy m-file trong cửa sổ lệnh của Matlab ta có quỹ tích nghiệm như sau:

3

Page 148: Matlab Tutorial

Bây giờ ta có thể thấy các nhánh của quỹ tích nghiệm đã nằm trong vùng mong muốn.

Chọn hệ số

Bây giờ quỹ tích nghiệm đã dịch về nửa bên trái mặt phẳng toạ độ, ta có thể tiến hành chọn các hệ sốđể thoả mãn mục tiêu đề ra. Ta dùng lệnh rlocfind để thực hiện chọn. Thêm các lệnh sau vào m-file.

[k,poles]=rlocfind(contr*plant)

Chọn 1 điểm ở gần một trong các điểm được đánh dấu + như hình vẽ dưới:

Ta sẽ thấy trong cửa sổ lệnh của Matlab kết quả ra gần giốn như sau (có thể giá trị kết quả có hơi khác1 chút):

4

Page 149: Matlab Tutorial

selected_point = -2.4988+ 1.2493i k = 37.3131 poles = -2.4950+ 1.2493i -2.4950- 1.2493i -0.0101

Và bây giờ ta có thể xem đáp ứng của hệ thống như thế nào với các hệ số như trên.

Vẽ đáp ứng của hệ kín

Giá trị này của kc được đặt vào hệ thống và ta có thể thu được đáp ứng với đầu vào bậc thang 0,25m.Thêm đoạn lệnh sau vào m-file để vẽ đặc tính của hệ thống.

sys_cl=feedback(k*contr*plant,1);t=0:0.01:5;figurestep(sys_cl,t)

Chạy m-file và chọn điểm như đã nói ở trên. Ta có đáp ứng như sau:

Từ đáp ứng trên ta thấy với đầu vào tín hiệu bậc thang 0.25m thì cả thời gian quá độ và độ quá điềuchỉnh đều đạt yêu cầu.

Chú ý: Mỗi ví dụ đều có nhiều phương án giải quyết. Với phương án này (hoặc bất kì phương án nàokhác) ta có thể có nhiều khâu bù khác nhau. Hãy thử chạy m-file nhiều lần và mỗi lần chọn 1 điểnkhác nhau, ta sẽ có đáp ứng khác nhau và qua đó ta se hiểu hơn về mức độ ảnh hưởng của các điểm

5

Page 150: Matlab Tutorial

trên quỹ tích nghiệm tới đáp ứng của hệ thống. Và bạn cũng có thể thay đổi các điểm không và cựccủa khâu bù tuỳ ý để tìm ra những đáp ứng tốt hơn.

Root Locus ExamplesĐiều khiển xe | Điều khiển tốc độ động cơ | Điều khiển góc quay động cơ | Bus Suspension |Điều khiển con lắc ngược | Pitch Controller | Bài toán bóng và thanh đỡ

Ball & Beam ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

6

Page 151: Matlab Tutorial

Phân tích đáp ứng tần số (Frequency ResponseAnalysis)

I. Biểu đồ Bode [ Biên của hệ số và pha | Dải băng tần | Đáp ứng của hệ kín ]

II. Biểu đồ Nyquist [ Tính ổn định của hệ kín | Biên của hệ số | Biên của pha ]

Các lệnh chủ yếu dùng trong phần này là bode, nyquist, nyquist1, lnyquist, margin, lsim, step, andfeedback

Phương pháp phân tích đặc tính tần số có vẻ ít trực quan hơn các phương pháp khác mà ta đã nghiêncứu. Tuy vậy, nó có nhiều ưu điểm, đặc biệt là trong các tình huống thực tế ví dụ như hàm truyền từcác dữ liệu vật lý.

Đáp ứng tần số của hệ thống có thể được biểu diễn theo hai cách: thông qua biểu đồ Bode hoặcNyquist. Chúng là cùng 1 vấn đề; chỉ khác nhau cách biểu diễn thông tin. Trong phần này ta nghiêncứu cả hai cách trên.

Đáp ứng tần số là biểu diễn đáp ứng của hệ thống với đầu vào dạng sin với các tần số khác nhau. Đầura của hệ tuyến tính với đầu vào sin cũng có dạng sin cùng tần số với đầu vào chỉ khác pha và biên độ.Đáp ứng tần số được định nghĩa là sự khác nhau về biên độ và pha giữa đầu ra và đầu vào sin. Trongphần này, ta sẽ tìm hiểu xem làm cách nào mà ta có thể tiên đoán được hành vi của hệ kín thông quađáp ứng của hệ hở.

Để biểu diễn đáp ứng tần số của hệ hở, ta tạo ra 1 vecto tần số (các giá trị chạy từ 0 hoặc "DC" đếnvô cùng) và tính giá trị của hàm truyền tại các tần số đó. Nếu G(s) là hàm truyền của 1 hệ hở và w làvecto tần số, thì ta sẽ biểu diễn G(j*w) và w. Vì G(j*w) có giá trị phức nên ta biểu diễn cả biên độ vàpha riêng (biểu đồ Bode) hoặc biểu diễn trên mặt phẳng phức (biểu đồ Nyquist). Để biết thêm, thamkhảo phần biểu diễn đáp ứng tần số.

Biểu đồ Bode

Như đã nhấn mạnh ở trên, biểu đồ Bode biểu diễn cả biên độ và pha của G(j*w) (vecto tần số w chỉgồm những tần số dương). Để xem biểu đồ Bode của 1 hàm truyền, ta dùng lệnh bode. Ví dụ,

num = 50;den = [1 9 30 40];sys = tf(num,den);bode(sys)

sẽ cho ta biểu đồ Bode như sau:

1

Page 152: Matlab Tutorial

50 ----------------------- s^3 + 9 s^2 + 30 s + 40

Chú ý đơn vị của biểu đồ. Tần số lấy theo loga, pha lấy theo độ, biên độ lấy theo dexiben..

Chú ý: 1 dexiben được định nghĩa bằng 20*log10 ( |G(j*w| )

Kích vào đây để xem 1 số biểu đồ Bode điển hình.

Biên của hệ số và pha

Giả sử ta có hệ thống sau:

K là 1 hệ số có giá trị thay đổi và G(s) là khâu chấp hành. Biên của hệ số được định nghĩa là sự thayđổi của hệ số trong hệ hở để cho hệ thống bị mất ổn định. Những hệ thống có biên hệ số lớn thì có thểổn định với cả những thay đổi lớn của các thông số hệ thống trước khi trở nên mất ổn định.

Hãy ghi nhớ rằng giá trị biên độ bằng 1 ứng với giá trị bằng 0 DB.

Biên của pha được định nghĩa là sự thay đổi pha đủ để làm cho hệ kín mất ổn định.

Qua biên của pha cũng đo được dung sai về thời gian trễ của hệ thống. Nếu xuất hiện mộtthời gian trễ lớn hơn180/Wpc (với Wpc là tần số mà tại đó pha bị lệnh đi 180 độ), thì hệkín sẽ không ổn định. Thời gian trễ được coi như là một khối phụ thêm trong sơ đồ khốilàm tăng pha của hệ thống. Nghĩa là, một khoảng thời gian trễ có thể được biểu diễn nhưmột khối với biên độ bằng 1 và pha bằng w*(thời gian trễ) [đơn vị là radian/giây).

Bây giờ ta không quan tâm ngay tới việc vấn đề này bắt nguồn từ đâu mà tập trung luôn vào xác định

2

Page 153: Matlab Tutorial

biên của hệ số và pha trên biểu đồ Bode.

Biên của pha là độ lệch pha giữa đường cong pha và đường -180o tại tần số mà biên độ đáp ứng tần sốbằng 0dB (điểm Wgc). Cũng tương tự như vậy, biên hệ số là độ lệch giữa đường cong biên độ vàđường 0dB tại tần số mà pha của đáp ứng tần số bằng -180o (điểm Wpc).

Một điều rất hay là ta không cần vẽ lại biểu đồ Bode để xác định lại biên của pha khi thay đổi hệ sốkhâu tỉ lệ. Ta nhớ lại rằng khi thêm khâu tỉ lệ thì biểu đồ biên-tần sẽ chỉ bị đẩy dọc theo chiều của trụctung. Ví dụ, giả sử ta gọi lệnh bode(sys). Ta sẽ có biểu đồ Bode như sau:

Ta thấy rằng biên của pha là 100o. Bây giờ giả sử ta có khâu tỉ lệ là 100, gọi lệnh bode(100*sys) tacó biểu đồ sau (lưu ý là ta không thay đổi trục toạ độ nên tỉ lệ các trục vẫn như vậy, biểu đồ có thểkhông giống y như trước vì còn phải tuỳ vào hệ số mà ta chọn):

3

Page 154: Matlab Tutorial

Như ta thấy biểu đồ pha-tần số vẫn giữ nguyên, biểu đồ biên-tần bị đẩy xuống 1 khoảng là 40dB (vì tỉlệ là 100). Biên của pha bây giờ là -60o. Kết quả này cũng được tìm thấy nếu ta tìm biên pha trên biểuđồ cũ tại tần số cho đáp ứng biên độ là -40dB.

Ta có thể trực tiếp tìm biên hệ số và pha với lệnh margin trong Matlab. Lệnh này tìm cho ta biên hệsố và pha, tần số tại đó và cả trên đồ thị :

margin(sys)

Dải băng tần

Dải băng tần được định nghĩa là tần số mà tại đó đáp ứng biên độ của hệ kín bằng -3 dB. Tuy nhiên,khi thiết kế hệ thống dự trên đáp ứng tần số, ta quan tâm tới việc phán đoán hành vi của hệ kín từ đápứng tần số của hệ hở. Do vậy, ta dùng phát biểu gần đúng là dải băng tần là các tần số tại đó biên độ

4

Page 155: Matlab Tutorial

đáp ứng tần số của hệ hở nằm trong khoảng -6 đến - 7.5dB, và thừa nhận đáp ứng pha của hệ hở nằmtrong khoảng -135o đến -225o. Để xem đầy đủ các dẫn xuất của phát biểu gần đúng này, hãy thamkhảo thêm trong sách in.

Nếu bạn muốn tìm hiểu thêm về cách tìm dải băng tần từ hệ số giảm chấn và tần số dao động riêngcủa hệ kín thi có thể tham khảo phần Bandwidth Frequency.

Để minh hoạ tầm quan trọng của dải băng tần, chúng ta đưa ra ví dụ về sự thay đổi của đầu ra với cáctần số của đầu vào khác nhau. Chúng ta sẽ tìm tất cả đầu ra tương ứng với các tần số nhỏ hơn Wbw(dải băng tần). Các đầu vào sin với tần số lớn hơn Wbw nhưng biên độ nhỏ hơn (bằng 0,707) hoặc lớnhơn 1 chút.

Giả sử ta có hàm truyền của hệ kín như sau:

1---------------s^2 + 0.5 s + 1

Trước tiên, ta tìm dải băng tần từ biểu đồ Bode:

num = 1;den = [1 0.5 1];sys = tf(num,den);bode (sys)

Từ hàm truyền trên, dải băng tần của ta sẽ là tần số cho đáp ứng biên độ là -3 dB. Nhìn vào biểu đồ, tathấy tần số đó khoảng 1.4 rad/s. Ta cũng thấy ngay rằng với tần số đầu vào 0.3 rad/s, đầu ra sin cóbiên độ bằng 1 và bị lệch pha vài độ chậm sau so với đầu vào. Với tần số đầu vào 3 rad/s, biên độ đầura khoảng -20dB (bằng 1/10 so với đầu vào) và pha gần bằng -180 (gần như ngược pha). Ta có thểdùng lệnh lsim để mô phỏng đáp ứng đầu ra với đầu vào sin.

Trước tên, ta xem xét đầu vào sin với tần số nhỏ hơn Wbw. Và ta nên nhớ rằng ta đang quan tâm tớiđáp ứng của hệ thống ở trạng thái ổn định. Do vậy, ta sẽ thay đổi khung nhìn để có thể thấy đáp ứngcủa hệ thống ở giai đoạn ổn định dễ dàng hơn (bỏ qua đáp ứng tức thời).

w = 0.3;

5

Page 156: Matlab Tutorial

num = 1;den = [1 0.5 1];sys = tf(num,den);t = 0:0.1:100; u = sin(w*t);[y,t] = lsim(sys,u,t);plot(t,y,t,u)axis([50,100,-2,2])

Chú ý đầu ra (đường màu xanh) khá bám theo đầu vào (đường màu tím); chỉ chậm sau vài độ.

Tuy nhiên, nếu tần số đầu vào cao hơn dải băng tần, ta sẽ có đầu ra khác hẳn với đầu vào:

w = 3;num = 1;den = [1 0.5 1];sys = tf(num,den);t = 0:0.1:100; u = sin(w*t);[y,t] = lsim(sys,u,t);plot(t,y,t,u)axis([90, 100, -1, 1])

Biên độ đầu ra chỉ bằng 1/10 đầu vào, như suy đoán trước, và chúng gần như ngược pha nhau (đầu rachậm pha 180o). Bạn hãy tự nhiên thực hiện với một số tần số khác và xem những gì xảy ra có đúngnhư dự báo trên biểu đồ Bode không.

Biểu hiện của hệ kín

Để suy đoán biểu hiện của hệ kín từ đáp ứng tần số của hệ hở chúng ta cần thống nhất với nhau 1 sốquan niệm sau:

Khi thiết kế bằng phương pháp biểu đồ Bode, thì yêu cầu hệ hở phải là ổn định.Nếu đường gióng biên bé hơn đường gióng pha (nghĩa là Wgc < Wpc), thì hệ kín sẽ ổn định.Với các hệ thống dẫn xuất, hệ số giảm chấn bằng biên của pha chia cho 100 nếu biên của pha

6

Page 157: Matlab Tutorial

nằm trong khoảng 0 đến 60o. Ta sẽ chú ý tới điều này khi dải băng tần lớn hơn 60o.Với các hệ thống dẫn xuất, quan hệ giữa hệ số giảm chấn, dải băng tần và thời gian quá độ đượcbiểu diễn thông qua 1 phương trình nêu ở phần dải băng tần.Với 1 ước lượng rất thô ta có thể coi dải băng tần xấp xỉ bằng tần số dao động riêng.

Với những quan niệm như trên, ta tiến hành thiết kế 1 bộ điều khiển cho hệ thống có dạng sau:

Gc(s) là bộ điều khiển và G(s) là:

10 ---------- 1.25s + 1

Yêu cầu thiết kế:

Không có sai số xác lập.Độ quá điều chỉnh lớn nhật cho phép phải nhỏ hơn 40%.Thời gian quá độ phải nhỏ hơn 2 giây.

Có hai phương pháp để thực hiện là: phương pháp đồ thị và phương pháp số. Với Matlab, tiếp cậntheo đồ thị là tốt nhất, ta sẽ dùng cách này. Trước hết, ta xem biểu đồ Bode. Tạo 1 m-file có các lệnhsau:

num = 10;den = [1.25,1];sys = tf(num,den);bode(sys)

Qua biểu đồ này ta có thể thấy ngay một số đặc tính của hệ thống. Trước tiên, ta thấy dải băng tầnkhoảng 10 rad/s. Vì dải băng tần được lấu thô là bằng tần số dao động riêng (với hệ thống dạng dẫn

7

Page 158: Matlab Tutorial

xuất thứ nhất), thời gian quá độ là 1,8/BW=1,8/10=1,8 giây. Đây chỉ là 1 ước lượng thô, ta có thể nóithời gian quá độ bằng 2 giây.

Biên của pha bây giờ khoảng 95 độ. Hệ số giảm chấn = pm/100 chỉ có ý nghĩa với PM < 60. Vì hệthống có dạng dẫn xuất thứ nhất nên không có độ quá điều chỉnh.

Điều cuối cùng cần lưu ý là sai số xác lập. Sai số xác lập có thể được tìm trực tiếp từ biểu đồ Bode.Các hằng số (Kp, Kv, hoặc Ka) được xác định là giao điểm của đường tiệm cận dưới với đường w=1.Biên độ tại điểm này là hằng số. Với hệ thống này ta có đường tiệm cận dưới nằm ngang (độ dốc = 0),nên hệ thống này có dạng 0. Do đó, giao điểm được xác đinh dễ dàng. Biên độ loga 20dB (biên độ =10). Điều này nghĩa là tham số của hàm sai số là 10. Kích vào đây để xem bảng thống kê các dạnghàm và hàm sai số của chúng. Sai số xáclập ở đây bằng 1/(1+Kp)=1/(1+10)=0.091. Nếu hệ thống códạng 1, thì tham số của hàm sai số được xác định giống như hình sau

Hãy xem các phán đoán của ta về đáp ứng của hệ kín có đúng không. Thực hiện hai lệnh sau.

sys_cl = feedback(sys,1);step(sys_cl)

Như ta thấy phán đoán của ta là đúng. Thời gian quá độ của hệ thống khoảng 2 giây, không có độ quáđiều chỉnh, sai số xác lập khoảng 9%. Bây giờ ta thiết kế 1 bộ điều khiển để thoả mãn yêu cầu đặt ra.Ta nên chọn 1 bộ điều khiển PI vì nó sẽ cho sai số xác lập bằng 0 với tín hiệu đầu vào bậc thang. Bộ

8

Page 159: Matlab Tutorial

điều khiển PI cũng cho ta 1 điểm không mà ta có thể đặt tuỳ ý. Điều này làm cho ta có thêm khả năngđiều kiển mềm dẻo hơn nữa. Nhắc lại kiến thức cũ, một bộ điều khiển PI có hàm truyền như sau:

K*(s+a)Gc(s) = -------

s

Việc đầu tiên là tìm là hệ số giảm chấn tương ứng với độ quá điều chỉnh 40%. Thay giá trị 40% vàophương trình biểu diễn quan hệ giữa hệ số giảm chấn và độ quá điều chỉnh (hoặc tham khảo đồ thị củaquan hệ này), ta tìm được hệ số giảm chấn xấp xỉ bằng 0,28. Do đó, biên của pha ít nhất cũng khoảng30o. Từ Ts*Wbw và hệ số giảm chấn, ta tìm được Ts*Wbw ~ 21. Ta phải có dải băng tần lớn hơn hoặcbằng 12 nếu muốn thời gian quá độ nhỏ hơn 1,75 giây như mong muốn.

Bây giờ ta đã xác định được dải băng tần và biên của pha cần thiết, ta có thể bắt đầu công việc thiếtkế. Lưu ý rằng ta đang xem xét biểu đồ Bode của hệ hở. Do đó, dải băng tần sẽ là tần số tương ứngvới biên độ xấp xỉ bằng -7 dB.

Bây giờ ta hãy xem bộ điều khiển PI ảnh hưởng tới hệ thống như thế nào. Thay đổi m-file như sau (chỉcó điều khiển I, chưa có điều khiển P):

num = 10;den = [1.25 1];plant = tf(num,den);numPI = 1;denPI = [1 0];contr = tf(numPI,denPI);bode(contr * plant, logspace(0,2))

Biên của pha và dải băng tần là quá nhỏ. Ta thêm điểm không vào để tăng chúng lên. Đặt điểm khôngtại là 1 và xem điều gì xảy ra. Thay đổi m-file như sau:

num = 10;den = [1.25 1];plant = tf(num,den);numPI = [1 1];denPI = [1 0];contr = tf(numPI,denPI);

9

Page 160: Matlab Tutorial

bode(contr * plant, logspace(0,2))

Điểm không 1 với tỉ lệ là 1 đã cho ta lời giải đáp. Biên của pha đã lớn hơn 60o (độ quá điều chỉnhcũng tốt hơn mong đợi) và dải băng tần xấp xỉ 11 rad/s, như thế ta sẽ có được đáp ứng mong muốn.Mặc dù đã thoả mãn, nhưng đáp ứng cũng chưa hẳn đã tốt đối với chúng ta. Do đó, ta hãy thử cho dảibăng tần cao lên mà không làm thay đổi nhiều đến biên của pha xem sao. Ta tăng tỉ lệ của điểm khônglên bằng 5 và xem điều gì xảy ra.

num = 10;den = [1.25 1];plant = tf(num,den);numPI = 5*[1 1];denPI = [1 0];contr = tf(numPI,denPI);bode(contr * plant, logspace(0,2))

Như vậy là đã tốt thực sự. Hãy xem đáp ứng với đầu vào tín hiệu bâc thang và kiểm nghiệm lại. Thêmcác lệnh sau vào m-file:

10

Page 161: Matlab Tutorial

sys_cl = feedback(contr * plant,1);step(sys_cl)

Như ta thấy bây giờ đáp ứng đã tốt hơn hẳn những gì mong đợi. Tuy nhiên chúng ta cũng cần 1 chútmay mắn trong quá trình điều chỉnh các điểm cực và điểm không để đạt các yêu cầu đặt ra.

Chủ đề này sẽ còn được bàn trong phần biểu đồ Nyquist.

Biểu đồ Nyquist

Frequency response ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

11

Page 162: Matlab Tutorial

Ví dụ: Giải pháp điều khiển xe dùng biểu đồ đápứng tần số

Biểu đồ Bode và đáp ứng của hệ hởBộ điều kiển tỉ lệBộ điều khiển Lag

Hàm truyền hệ hở của hệ như sau:

m=1000b=50U(s)=10Y(s)=Velocity output

Mục tiêu điều khiển là:

Thời gian quá độ < 5 secĐộ quá điều chỉnh < 10%

Sai số xác lập < 2%

Để biết cách thiết lập mô hình, tham khảo phần Mô hình điều khiển xe.

Biểu đồ Bode và đáp ứng của hệ hở

Bước đầu tiên để giải quyết vấn đề này là xác định hàm truyền hệ hở. Cũng giống như phưong phápQuỹ đạo nghiệm, chúng ta chỉ sử dụng bộ điều khiển tỉ lệ để giải quyết. Sơ đồ khối hệ thống và hàmtruyền như sau.

Để dùng được biểu đồ Bode, đáp ứng của hệ hở nhất thiết phải ổn định. Cho Kp = 1 và xem đáp ứngcủa hệ hở như thế nào. Tạo 1 m-file có các lệnh sau.

m = 1000;b = 50;u = 500;

1

Page 163: Matlab Tutorial

Kp = 1;num = 1;den = [m b];cruise = tf(num,den);contr = Kp;step(u*contr*cruise)

Chạy m-file ta sẽ có đáp ứng sau.

Như ta thấy, hệ hở ổn định; ta có thể làm tiếp và tìm biểu đồ Bode. Thay đổi m-file bằng cách thaylệnh step bằng lệnh sau.

bode(contr*cruise)

Chạy m-file và ta sẽ có biểu đồ Bode như sau.

Bộ điều khiển tỉ lệ

Hãy xem ta có thể xác định được đặc tính gì từ biểu đồ trên. Nhắc lại kiến thức từ phần Quỹ đạonghiệm, dải băng tần (BW) (tần số tại đó tỉ lệ biên độ M(dB)=-6~-7,5dB) xấp xỉ thô bằng tần số daođộng riêng (Wn). Dùng phương trình sau,

2

Page 164: Matlab Tutorial

thời gian quá độ (Tr) của hệ thống có thể được xác định quá lớn vì hệ số tỉ lệ biên độ ở trên chưa thựcsự nằm trong khoảng -6~-7,5dB. Hơn nữa, hệ số giảm chấn xấp xỉ thô bằng biên của pha (tính theođộ) chia cho 100.

Vì biên của pha trong trường hợp này xấp xỉ 155o, nên hệ số giảm chấn là 1,55. Như vậy, ta hệ thốngcủa ta bị giảm chấn quá mức (hệ số giảm chấn lớn hơn 1). Cuối cùng, sai số xác lập có thể được tínhtheo phương trình sau:

Với hệ thống của ta, vì hệ số tỉ lệ biên độ tần thấo M(dB) xấp xỉ -35dB nên sai số xác lập khoảng98%. Ta có thể kiểm tra lại bằng các lệnh sau.

u=10;sys_cl=feedback(contr*cruise,1);step(u*sys_cl);

Với biểu đồ Bode, nếu ta tăng hệ số tỉ lệ lên thì cả dải băng tần và hệ số tỉ lệ biên độ tần thấp sẽ tănglên và thời gian quá độ cũng như sai số xác lập sẽ đuợc cải thiện. Chúng ta có thể thực hiện điều đóbằng cách tăng hệ số tỉ lệ Kp. Hãy choKp = 100 và xem điều gì xảy ra. Thay đổi m-file thành như sau.

m = 1000;b = 50;u = 10;Kp = 100;num = 1;den = [m b];cruise = tf(num,den);contr = Kp;

3

Page 165: Matlab Tutorial

bode(contr*cruise)

Chạy m-file trong Matlab ta có biểu đồ Bode như sau.

Bây giờ, hệ số tỉ lệ biên độ tần thấp khoảng 6dB (biên độ là 2) ta có thể đoán trước sai số xác lậpkhoảng 33%. Dải băng tần khoảng 0.1 rad/sec nên thời gian quá độ sẽ khoảng 18 giây. Ta hãy xemđáp ứng của hệ kín để kiểm chứng lại.

sys_cl=feedback(contr*cruise,1);step(u*sys_cl);

Như ta đã dự đoán, cả sai số xác lập và thời gian quá độ đã được cải thiện. Ta thử tăng hệ số tỉ lệ lênnữa xem điều gì xảy ra. Chỉ cần thay đổi m-file 1 chút và chạy lại. Ta có biểu đồ Bode như sau.

m = 1000;b = 50;u = 10;Kp = 500;num = 1;den = [m b];cruise = tf(num,den);contr = Kp;bode(contr*cruise)

4

Page 166: Matlab Tutorial

Bây giờ, hệ số tỉ lệ biên độ tần thấp là 20dB (biên độ là 10) tức sai số xác lập khoảng 9%, và dải băngtần khoảng 0,6 tức thời gian quá độ dự đoán khoảng 3 giây (giá trị chấp nhận được). Như vậy là cảsai số xác lập và thời gian qua độ đã được cải thiện. Một lần nữa ta lại kiểm nghiệm lại đáp ứng của hệkín.

sys_cl=feedback(contr*cruise,1);step(u*sys_cl);

Nếu bạn để ý, sai số xác lập cuối cùng cũng sẽ đạt yêu cầu với hệ số tỉ lệ tăng cao hơn nữa. Tuy nhiên,cùng với việc sai số xác lập đạt yêu cầu thì thời quá trình quá độ lại quá nhanh (điều này không thựctế với hệ vật lý). Do vậy, hãy để giá trị Kp như thế và tiến hành bố trí thêm bộ điều khiển Lag để xứ lýsai số xác lập.

Bộ điều khiển Lag

Nếu bạn xem mục "Khâu bù Lag hoặc Pha-Lag using có sử dung Đáp ứng tần số" trong phần Bộ bùLead và Lag, bộ điều khiển Lag có tác dụng làm tăng hệ số tỉ lệ biên độ trong khi vẫn giữ nguyên dảibăng tần.. Và đó chính là điều ta mong muốn: hệ số tỉ lệ biên độ lớn hơn để giảm sai số xác lập và giữnguyên dải băng tần để bảo đảm thời gian quá độ. Hàm truyền của bộ điều khiển Lag như sau.

5

Page 167: Matlab Tutorial

Bây giờ, ta cần chọn giá trị cho a và T. Nhớ lại kiến thức trong phần "Khâu bù Lag hoặc Pha-Lagdùng Đáp ứng tần số", ta sẽ thấy sai số xác lập sẽ giảm theo hệ số a. Giá trị của T sẽ được chọn saocho hai tần số ở góc sẽ không bị đặt gần nhau (nếu như vậy khả năng đáo ứng tức thời sẽ xấu đi). Nhưthế cho a = 0,05 và T = 700 và xem điều gì xảy ra. Tạo m-file sau và chạy trong Matlab. Ta sẽ có biểuđồ sau.

m = 1000;b = 50;u = 10;Kp = 600;num = 1;den = [m b];cruise = tf(num,den);a = 0.05;T = 700;numlag = [a*T 1];denlag = a*[T 1];contr = Kp*tf(numlag,denlag);bode(contr*cruise)figuresys_cl=feedback(contr*cruise,1);step(u*sys_cl)

Vì hệ số tỉ lệ biên độ tần thấp đã được tăng trong khi dải băng tần vẫn giữ nguyên nên sai số xác lập sẽgiảm và thời gian quá độ vẫn giữ nguyên. Ta kiểm nghiệm lại đáp ứng của hệ kín như sau.

6

Page 168: Matlab Tutorial

Như trên có vẻ khó xem, nhưng ở trên biểu đồ có 1 đường nét đứt màu xanh phía dưới 10. Đường nàycho ta giá trị xác lập của hệ kín và ta thấy sai số xác lập đã đạt yêu cầu. Tuy nhiên, thời giân ổn địnhlại quá lâu. Để giải quyết, ta tăng hệ số tỉ lệ Kp=1500. Hệ số này được tìm ra sau 1 số phép thử sai màchúng tôi không tiện trình bày ở đây. Với thay đổi này, biểu đồ Bode và đáp ứng sẽ như sau.

7

Page 169: Matlab Tutorial

Như ta thấy, độ quá điều chỉnh thực tế bằng 0, sai số xác lập gần như bằng 0, thời gian quá độ khoảng2 giây, và thời gian đạt ổ định bé hơn 3,5 giây. Hệ thống đã thoả mãn các yêu cầu đặt ra.

Frequency Response ExamplesĐiều khiển xe | Điều khiển tốc độ động cơ | Motor Position | Bus Suspension | InvertedPendulum | Pitch Controller | Ball and Beam

Cruise Control ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

Cruise Control Examples Modeling | PID | Root Locus | Frequency Response | State Space | Digital Control

8

Page 170: Matlab Tutorial

Ví dụ: Điều khiển tốc độ động cơ dùng đáp ứng tầnsố

Vẽ biểu đồ Bode nguyên gốcThêm hệ số tỉ lệBiểu diễn đáp ứng của hệ kínThêm bộ điều khiển Lag

Từ phần đặt vấn đề, ta có phương trình động lực học và hàm truyền hở điều khiển tốc độ động cơ điện1 chiều như sau:

và sơ đồ khối hệ thống như sau:

Đê biết cách thiết lập mô hình, tham khảo phần Mô hình động cơ điện 1 chiều.

Với đầu vào tín hiệu bậc thang 1 rad/s, mục tiêu điều khiển đề ra là:

Thời gian ổn định nhỏ hơn 2 giâyĐộ quá điều chỉnh nhỏ hơn 5%Sai số xác lập nhỏ hơn 1%

Tạo 1 m-file có các lệnh sau (tham khảo phần mô hình).

J = 0.01;b = 0.1;K = 0.01;R = 1;L = 0.5;num = K;den = [(J*L) ((J*R)+(L*b)) ((b*R)+K^2)];

1

Page 171: Matlab Tutorial

motor = tf(num,den);

Vẽ biểu đồ Bode nguyên gốc

Ý tưởng chính của phương pháp thiết kế theo tần số là dùng biểu đồ Bode của hệ hở để ước đoán đápứng của hệ kín. Bằng cách thêm vào 1 bộ điều khiển để thay đổi biểu đồ Bode của hệ hở từ đó thayđổi đáp ứng của hệ kín. Trước hết hãy vẽ biểu đồ Bode của hàm truyền gốc. Thêm vào cuối m-filelệnh sau và chạy trong Matlab.

bode(motor)

Ta sẽ có biểu đồ Bode sau:

Thêm hệ số tỉ lệ

Từ biểu đồ Bode ở trên, ta thấy biên của pha có thể lớn hơn 60o nếu w nhỏ hơn 10 rad/sec. Thêm hệsố vào hệ thống sao cho dải băng tần bằng 10 rad/s, lúc đó ta sẽ có biên của pha khoảng 60o. Để tìmhệ số ứng với tần số là 10 rad/s, ta có thể tìm ngay trên biểu đồ Bode (nó hơn -40 dB 1 chút, hay biênbằng 0,01 ). Lệnh bode dẫn thêm các đối số bên tay trái được dùng để tìm chính xác biên độ:

[mag,phase,w] = bode(motor,10)

mag =

0.0139

Để có hệ số tỉ lệ biên độ là 1 ứng với tần số 10 rad/sec, ta cần thêm hệ số điều khiển bằng 1/0.0139tức là bằng 72 vào hệ thống.

contr=72;bode(contr*motor);

2

Page 172: Matlab Tutorial

và cho chạy m-file. Ta sẽ có biểu đồ Bode như sau:

Biểu diễn đáo ứng của hệ kín

Từ biểu đồ trên ta thấy biên của pha là khá lớn. Hãy xem đáp ứng của hệ kín ra sao. Thêm kí tự % vàotrước lệnh bode để tạm ngưng lệnh, và thêm các lệnh sau vào m-file:

sys_cl=feedback(contr*motor,1);t=0:0.01:10;step(sys_cl,t)

Ta sẽ có đáo ứng sau:

3

Page 173: Matlab Tutorial

Thời gian ổn định đã thoả mãn, nhưng độ quá điều chỉnh và sai số xác lập quá lớn. Độ quá điều chỉnhcó thể được giảm bằng cách giảm hệ số tỉ lệ đi 1 chút (sẽ làm cho biên của pha lớn hơn), nhưng nhưthế lại làm cho sai số xác lập tăng. Một bộ điều khiển Lag là điều cần có lúc này.

Thêm bộ điều khiển Lag

Ta có thể thêm bộ điều khiển Lag để giảm sai số xác lập. Cùng lúc đó ta sẽ giảm độ quá điều chỉnhbằng cách giảm hệ số tỉ lệ. Giảm hệ số xuống bằng 50, và thêm bộ điều khiển Lag sau

sẽ giảm sai số xác lập theo hệ số 1/0.01 = 100 (nhưng có thể làm tăng thời gian ổn định). Thay đổim-file giống như sau:

num = K;den = [(J*L) ((J*R)+(L*b)) ((b*R)+K^2)];motor = tf(num,den); Zo = 1;Po = 0.1;contr = 50*tf([1 Zo],[1 Po]);bode(contr*motor)

Chạy m-file và ta có biểu đồ sau

Biên của pha đã ổn. Sai số xác lập dự đoán khoảng 1/40dB (quy ra là 1%) đã thoả mãn yêu cầu. Hãyxem đáp ứng của hệ kín. Thêm vào m-file các lệnh sau và chạy trong Matlab.

sys_cl=feedback(contr*motor,1);t=0:0.01:10;step(sys_cl,t)

4

Page 174: Matlab Tutorial

Bây giờ ta đã có đáp ứng như mong muống. Sai số xác lập nhỏ hơn 1%, độ quá điều chỉnh khoảng 5%,và thời gian ổn định khoảng 2 giây.

Frequency Response ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Motor Speed ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

5

Page 175: Matlab Tutorial

Ví d: Thiết kế hệ điều khiển vị trí động cơ điện 1chiều bằng phương pháp tần số

Vẽ biểu đồ Bode nguyên gốcThêm khâu tích phânXác định biên hệ số, pha và thiết kế bộ điều khiển

Từ phần mô hình gốc, ta có phương trình động lực học và hàm truyền cả hệ như sau

:

và sơ đồ khối hệ thống như sau:

Để biết cách thiết lập mô hình, tham khảo phần Mô hình động cơ điện 1 chiều.

Với đầu vào tín hiệu bậc thang 1 rad, mục tiêu điều khiển đặt ra là:

Thời gian ổn định nhỏ hơn 40 mili giâyĐộ quá điều chỉnh nhỏ hơn 16%Không có sai sô xác lậpKhông có sai số xác lập do nhiễu

Vẽ biểu đồ Bode nguyên gốc

Tạo 1 m-file có các lệnh sau (tham khảo phần mô hình).

J = 3.2284E-6;b = 3.5077E-6;K = 0.0274;R = 4;L = 2.75E-6;

1

Page 176: Matlab Tutorial

num = K;den = [(J*L) ((J*R)+(L*b)) ((b*R)+K^2) 0];motor = tf(num,den);

Ý tưởng chính của phương pháp thiết kế theo tần số là dùng biểu đồ Bode của hệ hở để ước đoán đápứng của hệ kín. Bằng cách thêm vào 1 bộ điều khiển để thay đổi biểu đồ Bode của hệ hở từ đó thayđổi đáp ứng của hệ kín. Trước hết hãy vẽ biểu đồ Bode của hàm truyền gốc. Thêm vào cuối m-filelệnh sau và chạy trong Matlab.

w=logspace(0,4,101);bode(motor,w)

Ta sẽ có biểu đồ Bode sau:

Thêm khâu tích phân

Ta thêm khâu tích phân để có sai số xác lập do nhiễu bằng 0. Thêm các lệnh sau vào m-file:

numi = 1;deni = [1 0];contr = tf(numi,deni);bode(contr*motor,w)

Ta sẽ có biểu đồ sau:

2

Page 177: Matlab Tutorial

Xác định biên hệ số, pha và thiết kế bộ điều khiển

Chúng ta muốn độ quá điều chỉnh nhỏ hơn 16%, do vậy ta phải tính hệ số giảm chấn thích hợp. Tacũng phải tính cả biên của pha tương ứng bằng 100 lần hệ số giảm chấn. Từ yêu cầu về thời gian ổnđịnh, ta có thể tính ra dải tần số cần có. Thêm các lệnh sau vào m-file:

zeta = -log(.16)/sqrt(pi^2+(log(.16))^2);PM = 100*zeta; wbw = (4/(0.04*zeta))*sqrt((1-2*zeta^2)+sqrt(4*zeta^4-4*zeta^2+2));

Chúng ta cần có biên của pha ít nhất là 50o, cho nên hệ số tỉ lệ biên độ phải rơi vào khoảng -6 đến-7,5 dB tại một số tần số lớn hơn 250 rad/s. Từ biểu đồ Bode ta thấy rằng phải tăng thêm pha 80o vàhệ số tỉ lệ tăng thêm 60dB tại tần số 250 rad/s. Hệ số tỉ lệ lúc đó sẽ nằm giữa -6 đến -7,5 dB và hơn244 rad/s. Từ biểu đồ Bode pha ta có thể thấy có 1 cực gần tần số 60 rad/s. Chúng ta sẽ dùng 1 bộđiều khiển PI để đặt 1 điểm không tại s=60 để làm phẳng đường cong pha. Thêm các lệnh sau vàom-file:

numpi = [1 60];denpi = [1 0];contr = tf(numpi,denpi);bode(contr*motor,w)

Ta sẽ có biểu đồ sau:

3

Page 178: Matlab Tutorial

Từ biểu đồ trên ta thấy pha tại tần số 250rad/s cần tăng thêm 50o. Hãy thêm 1 khâu bù để thêm chínhxác 50o vào pha. Thêm các lệnh sau vào m-file:

a = (1 - sin(PM*pi/180))/(1 + sin(PM*pi/180));T = 1/(wbw*sqrt(a));contr2 = tf([T 1],[a*T 1]);w = logspace(2,3,101);bode(contr*contr2*motor,w)

Biểu đồ Bode mới cho ta thấy biên của pha ngay tại điểm 250 rad/s, nhưng tại đó hệ số tỉ lệ biên độ lạiquá nhỏ. Hệ số tỉ lệ biên độ phải tương ứng ở tần số 240 rad/s. Để tăng hệ số tỉ lệ biên độ lên thêm20dB, chúng ta nhân hệ số với 10. Thêm các lệnh sau vào m-file:

4

Page 179: Matlab Tutorial

Kp = 10;bode(Kp*contr*contr2*motor,w)

Ta có biểu đồ Bode như sau:

Ta kiểm tra đáp ứng của hệ hở bây giờ ra sao. Thêm các lệnh sau vào m-file:

sys_cl = feedback(Kp*contr*contr2*motor,1);t = 0:0.001:0.1;step(sys_cl,t)

Ta sẽ có đáp ứng sau:

Độ quá điều chỉnh là quá lớn, tuy nhiên thời gian ổn định tốt hơn mong đợi. Vì thế nên ta hãy thử thiết

5

Page 180: Matlab Tutorial

kế khác sao cho biên của pha lớn hơn, lấy khoảng 70o. Thêm các lệnh sau vào m-file:

PM = 70;a = (1 - sin(PM*pi/180))/(1 + sin(PM*pi/180));T = 1/(wbw*sqrt(a));contr2 = tf([T 1],[a*T 1]);w = logspace(2,3,101);bode(contr*contr2*motor,w)

Ta có đáp ứng sau:

Biểu đồ Bode này có biên của pha tại tần số gần như bằng 250 rad/s, nhưng hệ số tỉ lệ biên độ lại quánhỏ mất khoảng 14 dB. Hệ số tỉ lệ biên độ phải tương ứng ở tần số 240 rad/s. Để nâng giá trị hệ số ti lệbiên độ lên ta phải nhân hệ số với 5. Thêm các lệnh sau vào your m-file:

Kp=5;bode(Kp*contr*contr2*motor,w)

Ta có biểu đồ sau:

6

Page 181: Matlab Tutorial

Bây giờ ta lại kiểm tra xem đáp ứng của hệ kín ra sao. Thêm các lệnh sau vào m-file:

sys_cl = feedback(Kp*contr*contr2*motor,1);t = 0:0.001:0.1;step(sys_cl)

Ta sẽ có biểu đồ sau:

Với đáp ứng trên ta thấy độ quá điều chỉnh đã tốt, nhưng thời gian ổn định lại lớn. Ta hãy cho dải băngtần lớn hơn. Thêm các lệnh sau vào m-file:

wbw = 300;a = (1 - sin(PM*pi/180))/(1 + sin(PM*pi/180));T = 1/(wbw*sqrt(a));

7

Page 182: Matlab Tutorial

contr2 = tf([T 1],[a*T 1]);w = logspace(2,3,101);bode(contr*contr2*motor,w)

Ta có biểu đồ sau:

Biểu đồ Bode này cho ta thấy biên của pha sẽ ở tại tần số 250 rad/s, nhưng hệ số tỉ lệ biên độ lạ quánhỏ mất khoảng 18 dB. Hệ số tỉ lệ biên độ phải tương ứng ở tần số 240 rad/s. Để nâng giá trị hệ số ti lệbiên độ lên ta phải nhân hệ số với 8. Thêm các lệnh sau vào m-file:

Kp = 8;bode(Kp*contr*contr2*motor,w);

Ta có biểu đồ sau:

8

Page 183: Matlab Tutorial

Kiểm tra đáp ứng của hệ kín bây giờ ra sao. Thêm các lệnh sau vào m-file:

sys_cl = feedback(Kp*contr*contr2*motor,1);t = 0:0.001:0.1;step(sys_cl)

Ta có đáp ứng sau:

Mọi thứ đã đạt yêu cầu. Độ quá điều chỉnh nhỏ hơn 16% và thời gian ổn định khoảng 40 milligiây.

Chú ý: Bạn có thể thấy phương pháp dùng đáp ứng tần số cho ví dụ cụ thể này cần phải thực hiệnthao tác thử sai đáng kể. M-file dướic đây giản lược những thao tác vừa thực hiện. Sau khi chạy m-filenày, ta cũng vẫn sẽ có hai biểu đồ kết quả như trên.

J = 3.2284E-6;b = 3.5077E-6;K = 0.0274;R = 4;L = 2.75E-6; num = K;den = [(J*L) ((J*R)+(L*b)) ((b*R)+K^2) 0];motor = tf(num,den);

PM = 70;wbw = 300; a = (1-sin(PM*pi/180))/(1+sin(PM*pi/180));T = 1/(wbw*sqrt(a));

numpi = [1 60];denpi = [1 0];contr = tf(numpi,denpi); contr2 = tf([T 1],[a*T 1]); Kp = 8;w = logspace(2,3,101);

9

Page 184: Matlab Tutorial

bode(Kp*contr*contr2*motor,w) figuresys_cl = feedback(Kp*contr*contr2*motor,1);t = 0:0.001:0.1;step(sys_cl)

Frequency Response ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Motor Position ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

10

Page 185: Matlab Tutorial

Example: Frequency Design Method for the BusSuspension System

Plotting the frequency response using the bode commandAdding a two-lead controllerPlotting the closed-loop response

From the main problem, the dynamic equations in transfer function form are the following:

and the system schematic is:

For the original problem and the derivation of the above equations and schematic, please refer to the bus modelingpage.

We want to design a feedback controller so that when the road disturbance (W) is simulated by a unit step input,the output (X1-X2) has a settling time less than 5 seconds and an overshoot less than 5%. For example, when thebus runs onto a 10 cm high step, the bus body will oscillate within a range of +/- 5 mm and will stop oscillatingwithin 5 seconds.

The system model can be represented in MATLAB by creating a new m-file and entering the following commands(refer to the main problem for the details of getting those commands).

m1 = 2500;m2 = 320;k1 = 80000;k2 = 500000;b1 = 350;b2 = 15020;

nump=[(m1+m2) b2 k2];denp=[(m1*m2) (m1*(b1+b2))+(m2*b1) (m1*(k1+k2))+(m2*k1)+(b1*b2) (b1*k2)+(b2*k1) k1*k2];G1=tf(nump,denp);

num1=[-(m1*b2) -(m1*k2) 0 0];den1=[(m1*m2) (m1*(b1+b2))+(m2*b1) (m1*(k1+k2))+(m2*k1)+(b1*b2) (b1*k2)+(b2*k1) k1*k2];

1

Page 186: Matlab Tutorial

G2=tf(num1,den1);

numf=num1;denf=nump;F=tf(numf,denf);

Plotting the frequency response using the bode command

The main idea of frequency-based design is to use the Bode plot of the open-loop transfer function to estimate theclosed-loop response. Adding a controller to the system changes the open-loop Bode plot so that the closed-loopresponse will also change. Let's first draw the Bode plot for the original open-loop transfer function. Add thefollowing line of code to your m-file and rerun:

w = logspace(-1,2);bode(G1,w)

You should get the following bode plot:

For convenience in representing systems with different natural frequencies of the system, we normalize and scaleour findings before plotting the Bode plot, so that the low-frequency asymptote of each term is at 0 dB. Thisnormalization by adjusting the gain, K, makes it easier to add the components of the Bode plot. The effect of K isto move the magnitude curve up (increasing K) or down (decreasing K) by an amount 20*logK, but the gain, K,has no effect on the phase curve. Therefore from the previous plot, K must be equal to 100 dB or 100,000 tomove the magnitude curve up to 0 dB at 0.1 rad/s. Go back to your m-file and add the following line of code toyour m-file before the bode command and rerun:

K=100000;bode(K*G1,w)

You should get the following bode plot:

2

Page 187: Matlab Tutorial

Adding a two-lead controller

From the Bode plot above, we see that the phase curve is concave at about 5 rad/sec. First, we will try to addpositive phase around this region, so that the phase will remain above the -180 degree line. Since a large phasemargin leads to a small overshoot, we will want to add at least 140 degrees of positive phase at the area near 5rad/sec. Since one lead controller can add no more than +90 degrees, we will use a two-lead controller.

To obtain T and a, the following steps can be used:

1: Determine the positive phase needed :

Since we want 140 degrees total, we will need 70 degrees from each controller.

2: Determine the frequency where the phase should be added:

In our case this frequency should be 5.0 rad/sec.

3: Determine the constant a from the equation below, this determines the required space between the zero andthe pole for the desired maximum phase added.

4: Determine T and aT from the following equations, these determine the corner frequencies so that themaximum phase will be added at the desired frequency.

Now let's put our 2-Lead controller into the system and see what the Bode plot looks like. Add the following codeto your m-file, and add a % in front of the previous bode command (if there is one):

a = (1-sin(70/180*pi))/(1+sin(70/180*pi));w=5;T=1/(w*sqrt(a));aT=sqrt(a)/w;numc = conv([T 1], [T 1]);denc = conv([aT 1], [aT 1]);contr = tf(numc,denc);

3

Page 188: Matlab Tutorial

margin(K*contr*G1)

You should get the following Bode plot:

From this plot we see that the concave portion of the phase plot is above -180 degrees now, and the phase marginis large enough for the design criteria. Let's see how the output (the distance X1-X2) responds to a bump on theroad (W). Recall that the schematic of the system is:

and the closed-loop transfer function can be derived as follows:

sys_cl = F*feedback(G1,K*contr);

Plotting the closed-loop response

Let's see what the step response looks like now. Keep in mind that we are using a 0.1 m high step as thedisturbance. To simulate this, simply multiply the system by 0.1. Add the following code into the m-file andrerun it. Don't forget to put % mark in front of all bode and margin commands!

t=0:0.01:5;step(0.1*sys_cl,t)axis([0 5 -.01 .01])

and you should see the following plot:

4

Page 189: Matlab Tutorial

The amplitude of response is a lot smaller than the percent overshoot requirement and the settling time also is lessthan 5 seconds. Since we can see that an amplitude of the output's response less than 0.0001 m or 1% of inputmagnitude after 4 seconds. Therefore we can say that the settling time is 4 seconds from the above plot. From theBode plot above, we see that increasing the gain will increase the crossover frequency and thus make the responsefaster. We will increase the gain and see if we can get a better response. Go back to your m-file and change numcto numc=4*conv([T1 1],[T1 1]). Rerun the m-file and you should get the following plot:

From this plot we can see that the percent overshoot is about 0.15 mm less than the previous plot's and the settlingtime also less than 5 seconds. This response is now satisfactory and no more design iteration is needed.

Frequency Response ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | Pitch Controller | Balland Beam

5

Page 190: Matlab Tutorial

Bus Suspension ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

6

Page 191: Matlab Tutorial

Ví dụ: Giải pháp cho bài toán con lắc ngược dùngđáp ứng tần số

Biểu diễn hệ hởĐáp ứng của hệ kín khi chưa có khâu bùĐáp ứng của hệ kín khi có khâu bùĐiều gì xảy ra với vị trí xe?

Hàm truyền khâu chấp hành của ví dụ này như sau:

ở đây,

Chú ý: Hàm truyền này có sự ước lược 1 cặp điểm cực/không . Trong các ví dụ trước chúng được rútra khỏi hàm truyền. Tuy nhiên, trong ví dụ này chúng được chuyển vào với lý do ta sẽ bàn sau.

Mục tiêu thiết kế hệ điều khiển (với điều kiện ban đầu con lắc nhận được 1 xung lực 1N từ xe) là:

Thời gian ổn định nhỏ hơn 5 giây.Con lắc không được quay góc quá0,05 radian so với phương thẳng đứng.

Để biết cách thiết lập bài toán như thế nào, tham khảo phần mô hình con lắc ngược.

Chú ý: Trước khi đi vào giải quyết vấn đề, cần chú ý rằng giải quyết bài toán này bằng phương phápđáp ứng tần số là một vấn đề phức tạp. Bạn sẽ dễ nhận thấy bài ví dụ này có 1 điểm cực nằm ở nửabên trái mặt phẳng toạ độ làm cho hệ hở mất ổn định. Phương pháp đáp ứng tần số chỉ triển khai tốtkhi hệ hở ổn định. Với lý do như vậy nên ví dụ này không phải là ví dụ hay để bạn có thể học cáchdùng phương pháp đáp ứng tần số. Ví dụ này chỉ áp dụng cho những sinh viên muốn học cách giảiquyết vấn đề về đáp ứng tần số phức tạp mà thôi.

Biểu diễn hệ hở

1

Page 192: Matlab Tutorial

Hàm truyền thu được từ phép biến đổi Laplace với đầu ra phi (góc quay của con lắc) được thiết lậptrong Matlab bằng cách khai báo tử số và mẫu số dưới dạng các vecto. Tạo 1 m-file có các lệnh sau đểmô hình hoá hàm truyền:

M = .5;m = 0.2;b = 0.1;i = 0.006;g = 9.8;l = 0.3;

q = (M+m)*(i+m*l^2)-(m*l)^2; %simplifies input

num = [m*l/q 0 0];den = [1 b*(i+m*l^2)/q -(M+m)*m*g*l/q -b*m*g*l/q 0];pendulum = tf(num,den)

Đáp ứng của hệ kín khi chưa có khâu bù

Chúng ta sẽ thiết kế 1 bộ điều khiển với đầu vào là 1 xung dùng biểu đồ Nyquist (chúng ta không thểdùng biểu đồ Bode được vì hệ hở không ổn định). Ta bắt đầu bằng việc xem xét sơ đồ khối của hệthống:

Cách tốt nhất để có thể áp dụng Matlab là thay đổi sơ đồ khối sao cho ta có thể dễ dàng mô hình hoá.Sắp xếp lại so đồ ta có sơ đồ mới như sau:

Bây giờ ta có thể bắt đầu thiết kế. Trước hết, ta xem xét các điểm cực và điểm không của hàm truyền:

x = roots(num)y = roots(den)

x = 0 0

y = 0-5.6041 5.5651-0.1428

2

Page 193: Matlab Tutorial

Như đã biết trước, ta có sự ước lược cặp điểm cực-không tại gốc toạ độ, và cũng có 1 điểm cực thựcdương nằm ở nửa bên phải mặt phẳng toạ độ. Như thế có nghĩa là ta cần 1 lần bao quanh điểm -1 theochiều ngược kim đồng hồ của biểu đồ Nyquist để có hệ kín ổn định (Z = P + N; P = 1, N = -1). Vớim-file sau sẽ rất hữu dụng để thiết kế bộ điều khiển.

function[ ] = pend()

%define TFnum = [4.5455 0 0];den = [1.0000 0.1818 -31.1818 -4.4545 0];pendulum = tf(num,den);figure(1)

%ask user for controllernumc = input('numc?.........');denc = input('denc?.........');k = input('K?............');

%view compensated system bodecontr = k*tf(numc,denc);loop = contr*pendulum;bode(loop)

%view compensated system nyquistfigure(2)subplot (2,1,1)nyquist(loop)

%view compensated CL system impulse responsesubplot(2,1,2)sys_cl = feedback(pendulum,contr);impulse(sys_cl)

Với m-file này ta sẽ xem xét biểu đồ Nyquist của hệ khi chưa có khâu bù bằng cách chọn tử số vàmẫu số và hệ số tỉ lệ cho hàm truyền của bộ điều khiển bằng 1. Đánh lệnh pend trong cửa sổ lệnh vànhập giá trị 1 cho tử số, mẫu số và K. Ta sẽ có các biểu đồ sau:

numc?.........1denc?.........1K?............1

3

Page 194: Matlab Tutorial

Chú ý: Biểu đồ Bode trong version Matlab có thể khác so với biểu đồ Bode trong phầnnày 360o. Lệch pha 360o không làm thay đổi quan hệ giữa biểu đồ Bode và đáp ứng độnglực học của hệ thống.

Đáp ứng của hệ kín khi có khâu bù

Hệ kín không ổn định (vì không biểu đồ không bao điểm -1 lần nào). Bước đầu tiên cần làm là thêm 1khâu tích phân để khử điểm không phụ thêm ở gốc tọa đô (để ta sẽ có 2 cực và 2 điểm không tại gốctoạ độ). Ta lại dùng lệnh pend.

4

Page 195: Matlab Tutorial

numc?.........1denc?.........[1 0]K?............1

Ta để ý thấy biểu đồ Nyquist bao điểm -1 thuận chiều kim đồng hồ. Bây giờ ta có hai cực ở nửa bênphải mặt phẳng toạ độ (Z= P + N = 1 + 1). Ta cần tăng thêm pha để có được đường bao ngược chiềukim đồng hồ. Ta sẽ thực hiện điều này bằng cách thêm 1 điểm không vào bộ điều khiển của ta. Để bắtđầu, ta chọn điểm không tại điểm -1.

numc?.........[1 1]denc?.........[1 0]K?............1

5

Page 196: Matlab Tutorial

như ta thấy, độ lệch pha vẫn chưa đủ. Biểu đồ vẫn bao điểm -1 theo chiều kim đồng hồ. Chúng ta cầnthêm 1 điểm không nữa.

numc?.........conv([1 1],[1 1])denc?.........[1 0]K?............1

6

Page 197: Matlab Tutorial

Ta vẫn thấy biểu đồ bao điểm -1 thuận chiều kim đồng hồ. Tuy nhiên, nếu ta tăng hệ số lên 1 chút, tacó thể làm cho hệ thống ổn định ổn định bằng cách dịch biểu đồ Nyquist về phía trái để bao điểm -1ngược chiều kim đồng hồ, để cho N = -1.

numc?.........conv([1 1],[1 1])denc?.........[1 0]K?............10

7

Page 198: Matlab Tutorial

Như ta có thể thấy, hệ thống bây giờ đã ổn định. Bây giờ ta chỉ còn tập trung vào cải thiện chất lượngcủa đáp ứng. Ta sẽ điều chỉnh lại các cực của bộ điều khiển. Ta nên ghi nhớ rằng các cực giá trị nhỏ (ởgần gốc toạ độ) sẽ ảnh hưởng tới đáp ứng của hệ thống tại các tần số nhỏ, trong khi đó các cực có giátrị lớn (ở xa gốc toạ độ) sẽ ảnh hưởng tới đáp ứng của hệ thống tại các tần số cao. Khi thiết kế thôngqua đáo ứng tần số, chúng ta cố gắng cho ra được những biểu đồ đơn giản, vì như thế thì sẽ thực hiệndễ dàng hơn để có thể đạt được mục tiêu mong muốn. Do vậy, ta sẽ dùng ý tưởng 'làm phẳng' đáp ứngtần số (biểu đồ Bode). Cùng lúc, ta cũng chú ý rằng biểu đồ Nyquist sẽ có dạng oval.

Nếu ta thử dùng sự phối hợp giữa các cực và điểm không khác, ta có thể có những đáp ứng rất hợp lý.(Hãy gọi lệnh axis([0 5 -0.05 0.1]) sau khi thực hiện lệnh pend)

numc?.........conv([1 1.1],[1 5])denc?.........[1 0]

8

Page 199: Matlab Tutorial

K?............10

Đáp ứng đã đạt yêu cầu đề ra. Hãy tự mình chọn các tham số khác nhau và xem điều gì xảy ra.

Điều gì xảy ra với vị trí xe?

Ngay từ đầu của phần này, sơ đồ khối hệ thống đã được trình bày. Tuy nhiên sơ đồ khối đó khônghoàn toàn hoàn thiện. Khối biểu diễn cho vị trí của xe bị bỏ qua vì nó không phải là mục tiêu điềukhiển của ta. Sẽ rất hay nếu ta xem xét điều gì xảy ra với vị trí xe khi bộ điều khiển đang điều khiểngóc của con lắc. Để xem xét vấn đề, ta quan tâm tới sơ đồ khối hệ thống như sau:

9

Page 200: Matlab Tutorial

Sắp xếp lại 1 chút, ta sẽ có sơ đồ khối như sau:

Vòng phản hồi kín chính là bộ điều khiển mà ta đã thiết kế lúc trước cho điều khiển góc quay của conlắc. Hàm truyền cho vị trí xe với điều kiện đầu vào ban đầu là 1 xung lực và bộ điều khiển đã thiết kếtrước như sau:

Hàm truyền

Bây giờ ta đã có hàm truyền cho toàn bộ hệ thống, hãy xem đáp ứng của nó như thế nào. Trước hết tatính hàm truyền cho vị trí xe. Để có điều này ta thực hiện phép biến đổi Laplace cho hệ phương trìnhcủa hệ thống và tìm hàm truyền từ U(s) tới X(s). Dưới đây là hàm truyền đó:

ở đây,

Để biết thêm về phép biến đổi Laplace tham khảo phần mô hình con lắc ngược.

Bây giờ, tạo 1 m-file và chạy trong cửa sổ lệnh của Matlab:

10

Page 201: Matlab Tutorial

M = .5;m = 0.2;b = 0.1;i = 0.006;g = 9.8;l = 0.3;

q = (M+m)*(i+m*l^2)-(m*l)^2; %simplifies input

num1 = [m*l/q 0 0];den1 = [1 b*(i+m*l^2)/q -(M+m)*m*g*l/q -b*m*g*l/q 0];G1 = tf(num1,den1);

num2 = [(i+m*l^2)/q 0 -m*g*l/q];den2 = den1;G2 = tf(num2,den2);

k = 10;numc = conv([1 1.1],[1 5]);denc = [1 0];contr = tf(k*numc,denc);sys_cl = feedback(1,contr*G1)*G2;sys_cl = minreal(sys_cl);t=0:0.01:100;impulse(sys_cl,t)

Lệnh minreal chỉ ra cho Matlab ước lược đi tất cả các cực và điểm không của hàm truyền hệ kín; điềunày làm cho hàm impulse có tính chất số hoá tốt hơn. Như ta thấy, xe di chuyển theo chiều âm sau đóổn định tại vị trí khoảng -0,18m. Thiết kế của ta có thể hoạt động tốt khi áp dụng bộ điều khiển trongthực tế, giả sử rằng xe cần có khoảng không lớn để di chuyển thì đó là điều không may mắn. Chúng tađã cố gắng thiết kế sao cho vị trí của xe được ổn định và trên thực tế những gì chúng ta có là maymắn.

Frequency Response ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball & Beam

11

Page 202: Matlab Tutorial

Inverted Pendulum ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

12

Page 203: Matlab Tutorial

Example: Frequency Response Design method forthe Pitch Controller

Open-loop responseLead compensatorLag compensator

In the Pitch Controller Modeling page, the transfer function was derived as

The input (elevator deflection angle, delta e) will be 0.2 rad (11 degrees), and the output is the pitchangle (theta).

The design requirements are

Overshoot: Less than 10%Rise time: Less than 5 secondsSettling time: Less than 10 secondsSteady-state error: Less than 2%

To see the original problem setup, please refer to the Pitch Controller Modeling page.

Open-loop response

Recall from your control textbook that the frequency response design method is most effective forsystems with stable open-loop. To check the open-loop stability of our system, create a new m-file,and enter the following commands. Running this m-file in the MATLAB command window should giveyou the step response shown below:

de = 0.2;num = [1.151 0.1774];den = [1 0.739 0.921 0];pitch = tf(num,den);step(de*pitch)

1

Page 204: Matlab Tutorial

Unfortunately, our system is unstable in open-loop; however, we can still design the feedback systemvia frequency response method (even though this might not be the easiest way). First, let's generatethe open-loop Bode plot and see what it looks like. Change the m-file to the following and re-run it inthe MATLAB command window. You should see a Bode plot similar to the one shown below:

num = [1.151 0.1774];den = [1 0.739 0.921 0];pitch = tf(num,den);bode(pitch)

From our design requirements, we can determine that the natural frequency (Wn) must be greater than0.9 and the damping ratio (zeta) must be greater than 0.52 (please refer to the Pitch Controller:Root-Locus method for details). Using two equations shown below, we see that the bandwidthfrequency and the phase margin must be greater than 0.9 and 52 degrees, respectively.

2

Page 205: Matlab Tutorial

Tr = Rise timeWn = Natural frequencyBW = Bandwidth frequencyzeta = Damping ratioPM = Phase margin

Currently, we have a bandwidth frequency of 1 rad/sec and a phase margin of 80 degrees. Thesevalues are within our desired region. Let's plot the closed-loop step response and see what it lookslike. Delete the bode command from the above m-file and add the following commands. Running thisnew m-file should give you the following closed-loop step response:

sys_cl = feedback(pitch,1);de = 0.2;t = 0:0.01:10;step(de*sys_cl,t)

As you can see, the transient response is worse, there is a long settling time. We will implement a leadcompensator to improve the system response.

Lead Compensator

Referring to the "Lead or phase-lead compensator using frequency response" section of Lead and LagCompensator page, a lead compensator will add a positive phase to the system. An additional positivephase increases the phase margin; thus, increase damping. The settling time should decrease as a resultof this increased damping.

The transfer function of a typical first-order lead compensator is

3

Page 206: Matlab Tutorial

We need to find alead, Tlead and Klead. First, the phase margin requirement and the followingequation can be used to find alead

Since we are required to have the phase margin of greater than 52 degrees, the alead must be greaterthan 8.43. Using this alead, the bandwidth frequency requirement of greater than 0.9 and thefollowing equation leads us to have the Tlead of smaller than 0.382.

Let the Klead equal 0.1, alead equal 10, and Tlead equal 0.3 for now and enter the followingcommands to an new m-file.

num = [1 151 0.1774];den = [1 0.739 0.921 0];pitch = tf(num,den);

alead = 10;Tlead = 0.3;k = 0.1;lead = tf(k*[alead*Tlead 1],[Tlead 1]);

bode(lead*pitch)

sys_cl = feedback(lead*pitch,1);de = 0.2;t = 0:0.01:10;figurestep (de*sys_cl,t)

Running this m-file in the MATLAB command window gives you the following Bode and step responseplots.

4

Page 207: Matlab Tutorial

Although both the bandwidth frequency and phase margin have increased, the response still does notsatisfy the design requirements. Let's increase alead and decrease Tlead. After several trial and errorruns, an alead of 200, Tlead of 0.0025, and Klead of 0.05 , were found which gave the following leadcompensator,

providing the desired transient response. To see the step response and the corresponding Bode plot,enter the following commands to an m-file and run it in the command window. You should see boththe Bode plot and the step response shown below:

num = [1 151 0.1774];den = [1 0.739 0.921 0];pitch = tf(num,den);

alead = 200;Tlead = 0.0025;k = 0.1;lead = tf(k*[alead*Tlead 1],[Tlead 1]);

bode(lead*pitch)

sys_cl = feedback(lead*pitch,1);de = 0.2;t = 0:0.01:10;figurestep (de*sys_cl,t)

5

Page 208: Matlab Tutorial

If you compare the above Bode plot to the original Bode plot, you see both the phase margin and thebandwidth frequency have increased. Increasing both of them improves the rise time, the overshoot,and the settling time, as seen in the above step response plot. To improve the steady-state error, wewill add a lag compensator to the system.

Lag compensator

Referring to the "Lag or phase-lag Compensator using frequency response" section of Lead and LagCompensator page, a lag compensator reduces the steady-state error. The typical first-order transferfunction of a lead compensator is

The steady-state error will be reduced by a factor of alag. From the above step response, we see thatthe steady-state error is roughly 10%. Thus, alag needs to be approximately 0.1. The Tlag should begreater than alag*Tlag because this compensator must not greatly change the transient response.

6

Page 209: Matlab Tutorial

After several trial and error runs, an alag of 0.1, Tlag of 20, and Klag of 1.5, were found which gavethe following lag compensator,

provided the desired response. To see the step response and the corresponding Bode plot, enter thefollowing commands to an new m-file. Running this m-file in the command window should give youthe two plots shown below:

num = [1 151 0.1774];den = [1 0.739 0.921 0];pitch = tf(num,den);

alead = 200;Tlead = 0.0025;k = 0.05;lead = tf(k*[alead*Tlead 1],[Tlead 1]);

Tlag = 20;alag = 0.1;at = alag*Tlag;k2 = 1.5;numlag = k2/alag*[at 1];denlag = [Tlag 1];lag = tf(numlag,denlag);

bode(lag*lead*pitch)

sys_cl = feedback(lag*lead*pitch,1);figuret = 0:0.01:10;step(0.2*sys_cl,t)

7

Page 210: Matlab Tutorial

If you see the Bode plot, the low frequency gain has increased while keeping the bandwidth frequencythe same. This tells us that steady-state error has reduced while keeping the same rise time. The abovestep response shows that the steady-state error is acceptable. Now all design requirements aresatisfied.

Frequency Response ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchControl | Ball and Beam

Pitch Control ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

8

Page 211: Matlab Tutorial

Ví dụ: Giải pháp cho bài toán Bóng & Thanh đỡdùng đáp ứng tần số

Biểu đô Bode của hệ hởBộ điều khiển Phase-LeadTăng thêm pha

Hàm truyền hở khâu chấp hành cho bài toán bóng và thanh đỡ như sau:

Mục tiêu điều khiển là:

Thời gian ổn định nhỏ hơn 3 giâyĐộ quá điều chỉnh nhỏ hơn 5%

Để biết các phương trình của hệ xuất phát từ đâu, tham khảo phần mô hình bóng và thanh đỡ. Sơ đồhệ kín với bộ điều khiển như sau:

Biểu đồ Bode của hệ hở

Ý tưởng chính của phương pháp thiết kế theo tần số là dùng biểu đồ Bode của hệ hở để ước đoán đápứng của hệ kín. Bằng cách thêm vào 1 bộ điều khiển để thay đổi biểu đồ Bode của hệ hở từ đó thayđổi đáp ứng của hệ kín. Trước hết ta hãy vẽ biểu đồ Bode cho hệ hở ban đầu. Tạo 1 m-file với cáclệnh sau và chạy trong cửa sổ lệnh của Matlab:

m = 0.111;R = 0.015;g = -9.8;L = 1.0;d = 0.03;J = 9.99e-6;

K = (m*g*d)/(L*(J/R^2+m)); %simplifies input

num = [-K];den = [1 0 0];

1

Page 212: Matlab Tutorial

ball=tf(num,den);

bode(ball)

You should get the following Bode plot:

Từ biểu đồ Bode trên ta thấy biên của pha bằng 0. Vì biên của pha được định nghĩa là sự thay đổi phacần thiết trong hệ hở để hệ kín không ổn định, điều này nghĩa là với biên pha bằng 0 thì hệ là không ổnđịnh. Chúng ta cần tăng biên pha lên và ta có thể dùng 1 bộ điều khiển bù Lead để thực hiện. Để biếtrõ hơn về Biên hệ số và pha tham khảo phần Đáp ứng tần số.

Bộ điều khiển Pha-Lead

Khâu bù phase-lead loại 1 có dạng như sau:

Khâu bù Pha-Lead sẽ thêm 1 pha dương cho hệ thống trên dải tần số từ 1/aT đến 1/T, gọi là những tầnsố ở góc. Giá trị pha thêm vào nhiều nhất là 90o. Ta cần thiết kế để độ quá điều chỉnh nhỏ hơn 5 %,tương ứng với zeta (hệ số giảm chấn) bằng 0,7. Nhân zeta * 100 sẽ cho ta giá trị nhỏ nhất mà biên củapha cần có để đạt độ quá điều chỉnh mong muốn. Như vậy, ta cần biên của pha ít nhất là 70o.

Để có "T" và "a", cần thực hiện theo các bước sau.

1. Xác định pha dương cần thiết là bao nhiêu:

Với bộ điều khiển ta cần ít nhất là 70o.

2. Xác đinh tần số mà ta thực hiện thêm pha tại đó (tần số trung tâm):

Trong trường hợp này là khá khó xác định bởi biểu đồ tần số-pha hiẹn giừo là một đường thẳng.Tuy nhiên, ta lại có liên hệ giữa dải băng tần (wbw) và thời gian ổn định (tham khảo phần Dảibăng tần để biết phương trình liên hệ) và phương trình này giúp ta tìm được wbw xấp xỉ 1.92

2

Page 213: Matlab Tutorial

rad/s. Do vậy ta chọn tần số trung tâm ở trước wbw. Tạm thời chọn bằng 1.

3. Xác định hằng số "a" từ phương trình bên dưới, hằng số này cho biết khoảng cách cần thiết giữacực và điểm không của pha thêm lớn nhất.

ở đây phi là biên pha cần có. Với phi bằng 70 độ, a = 0.0311.

4. Xác định "T" và "aT" từ phương trình sau:

Với phi = 70 độ và tần số trung tâm w = 1, ta có aT = 0.176 và T = 5.67

Bây giờ, ta có thể thêm bộ điều khiển Lead cho hệ thống và xem xét biểu đồ Bode. Bỏ lệnh bodetrong m-file và thay bằng các lệnh sau:

phi=70*pi/180;a=(1-sin(phi))/(1+sin(phi));w=1;T=1/(w*sqrt(a));k = 1;numlead = k*[T 1];denlead = [a*T 1];contr = tf(numlead,denlead);

bode(contr*ball)

Ta có biểu đồ sau:

3

Page 214: Matlab Tutorial

Ta có thể thấy rằng biên của pha bây giờ là 70 độ. Hãy kiểm tra đáp ứng của hệ kín bây giừo ra saovới đầu vào tín hiệu bậc thang 0,25m. Thêm các lệnh sau vào m-file:

sys_cl = feedback(contr*ball,1);t = 0:0.01:5;step(0.25*sys_cl,t)

Ta có biểu đồ sau:

Mặc dù hệ thống đã ổn định và độ quá điều chỉnh khoảng 5%, nhưng thời gian ổn định không thoảmãn. Tăng hệ số sẽ tăng giá trị tần số cắt ngang và làm cho đáp ứng của hệ thống nhanh hơn. Với k =5, đáp ứng của ta sẽ như sau:

4

Page 215: Matlab Tutorial

Đáp ứng đã nhanh hơn, tuy nhiên, độ quá điều chỉnh lại quá cao. Tăng hệ số thêm nữa sẽ làm cho độquá điều chỉnh càng xấu.

Tăng thêm pha

Ta có thể tăng khâu bù pha-lead để giảm độ quá điều chỉnh. Để làm cho công việc đơn giản hơn tadùng chương trình sau. Tạo 1 m-file và copy hàm sau vào m-file.

function[ ] = phaseball()

%define TFm = 0.111;R = 0.015;g = -9.8;L = 1.0;d = 0.03;J = 9.99e-6;

5

Page 216: Matlab Tutorial

K = (m*g*d)/(L*(J/R^2+m)); %simplifies input

num = [-K];den = [1 0 0];ball = tf(num,den);

%ask user for controller informationpm = input('Phase Margin?.......');w = input('Center Frequency?...');k = input('Gain?...............');

%view compensated system bode plotpmr = pm*pi/180;a = (1 - sin(pmr))/(1+sin(pmr));T = sqrt(a)/w;aT = 1/(w*sqrt(a));

numlead = k*[aT 1];denlead = [T 1];contr = tf(numlead,denlead);

figurebode(contr*ball)

%view step responsesys_cl = feedback(contr*ball,1);t = 0:0.01:5;figurestep(0.25*sys_cl,t)

Với m-file này bạn có thể chọn biên của pha, tần số trung tâm và hệ số. Chạy your m-file với các thamsố sau và ta sẽ có biểu đồ sau.

Phase Margin?.......80Center Frequency?...1Gain?...............1

6

Page 217: Matlab Tutorial

Độ quá điều chỉnh đã đạt, nhưng thời gian ổn định lại lâu. Thử các giá trị khác và xem điều gì xảy ra.

Với các giá trị tham số sau mục tiêu đề ra sẽ đạt được.

Phase Margin?.......85Center Frequency?...1.9Gain?...............2

7

Page 218: Matlab Tutorial

Chú ý: Một vấn đề thiết kế không chỉ có 1 lời giải đáp duy nhất. Với phương pháp này (hoặc cácphương pháp khác) có thể cho ra các khâu bù khác nhau. Để tự thực hành, bạn có thể chọn lại pha, hệsố hoặc tần số trung tâm rồi xem xét các đáp ứng.

Frequency Response ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball & Beam

Ball & Beam ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

8

Page 219: Matlab Tutorial

Không gian trạng thái (State Space)Phương trình không gian trạng tháiThiết kế hệ điều khiển bằng cách gán điểm cựcIntroducing the reference inputObserver design

Các từ khoá lệnh Matlab trong phần này là: acker, lsim, place, plot, rscale

Phương trình không gian trạng thái

Có nhiều cách khác nhau để biểu diễn 1 hệ thống bằng các phương trình vi phân. Biểu diễn quakhông gian trạng thái có dạng như sau:

với x là vecto n x 1 biểu diễn trạng thái (thường là vị trí và vận tốc của hệ cơ khí), u là đại lượng vôhướng biểu diễn cho đầu vào (thường là lực hoặc momen xoắn trong hệ cơ khí), và y là đại lượng vôhướng biểu diễn cho đầu ra. Các ma trận A (n x n), B (n x 1), và C (1 x n) xác định mối liên hệ giữatrạng thái, đầu vào và đầu ra của hệ thống. Lưu ý là ở đây ta có n phương trình vi phâ cấp1. Khônggian trạng thái có thể biểu diễn được hệ thống với nhiều đầu vào ra (MIMO), nhưng ta chỉ xét các hệthống 1 đầu vào, 1 đầu ra (SISO) trong phần này.

Để giới thiệu phương pháp thiết kế theo không gian trạng thái,chúng tôi sử dụng mô hình treo quả bóng bằng từ trường làm ví dụ.Dòng điện trong cuộn dây sinh ra 1 lực từ cân bằng với trọng lựcvà làm cho quả bóng (làm bằng vật liệu từ) lơ lửng trong khôngkhí. Mô hình này có trong rất nhiều sách in về điều khiển (bao gồmcả cuốn Automatic Control Systems của B. C. Kuo, tái bản lần thứ7). Phương trình của hệ thống này được đưa ra như sau:

ở đây h là vị trí theo phương thẳng đứng của quả bóng, i là dòng điện chạy qua nam châm điện, V làđiện áp được đặt vào, M là khối lượng của bóng, g gia tốc trọng trường, L là độ tự cảm của cuộn dây,

1

Page 220: Matlab Tutorial

R điện trở, và K là hệ số xác định tác dụng của lực từ lên bóng. Để đơn giản, ta chọn M = 0,05 Kg, K= 0,0001, L = 0,01 H, R = 1 Ôm, g = 9,81 m/s2 . Hệ thống đạt vị trí cân bằng (bóng lơ lửng trongkhông khí) khi nào h = K i2/Mg (tại điểm này dh/dt = 0). Chúng ta tuyến tính hoá các phương trìnhxung quanh h = 0,01 m (ở đó dòng điện danh nghĩa khoảng 7 ampe) và có phương trình không giantrạng thái như sau:

với: là tập các biến trạng thái của hệ thống (vecto 3x1), u là điện áo đầu vào (denta V), và y

(đầu ra) là denta h. Nhập các ma trận hệ thống sau vào 1 m-file.

A = [ 0 1 0 980 0 -2.8 0 0 -100];B = [0 0 100];C = [1 0 0];

Một trong những điều đầu tiên ta muốn làm với các phương trình trạng thái là tìm các cực của hệthống; đó là những giá trị của s mà det(sI - A) = 0, hoặc chính là các giá trị riêng của ma trận A:

poles = eig(A)

Ta sẽ có 3 cực sau:

poles =

31.3050 -31.3050 -100.0000

Một trong số các cực nằm ở phía bên phải mặt phẳng toạ độ, có nghĩa là hệ hở không ổn định.

Để kiểm tra xem điều gì xảy ra với hệ thống không ộn định này khi điều kiện ban đầu khác không,thêm các lệnh sau vào m-file,

t = 0:0.01:2;u = 0*t;x0 = [0.005 0 0];sys = ss(A,B,C,0);[y,t,x] = lsim(sys,u,t,x0);plot(t,y)

và cho chạy lại.

2

Page 221: Matlab Tutorial

Có vẻ như khoảng cách giữa bóng và nam châm sẽ tiến ra vô cùng, nhưng có thể bóng sẽ chạm vàobàn hoăc mặt đất trước (và chắc chắn ra khỏi phạm vi tuyến tính hoá).

Thiết kế hệ điều khiển bằng cách gán điểm cực

Ta hãy xây dựng 1 bộ điều kiển cho hệ thống này. Sơ đồ có phản hồi đầy đủ các trạng thái của hệthống như sau:

Nhắc lại rằng đa thức đặc trưng của hệ kín là định thức của (sI-(A-BK)). Vì các ma trận A và B*K đềulà ma trận 3 x 3, nên hệ thống có 3 cực. Bằng cách phản hồi đầy đủ các trạng thái ta có thể gán cáccực ở mọi vị trí mà ta muốn. Ta có thể sử dụng lệnh place trong Matlab để tìm ma trận điều khiển K,ma trận sẽ cho ta các cực như mong muốn.

Trước khi thực hiện phương pháp này, chúng ta phải quyết định được vị trí nào để đặt cực của hệ kín.Giả sử mục tiêu điều khiển là thời gian ổn định <0,5 giây và độ quá điều chỉnh < 5%, chúng ta có thểcố gắng đặt hai cực chính tại -10 +/- 10i (zeta = 0.7 hay là 45o với sigma = 10 > 4.6*2). Cực thứ 3 lúcđầu ta có thể đặt tại điểm -50, và ta có thể thay đổi nó sau phụ thuộc vào hành vi của hệt thống ra sao.Bỏ lệnh lsim trong m-file và các lệnh sau đó nữa rồi thêm các lệnh sau vào m-file,

p1 = -10 + 10i;p2 = -10 - 10i;p3 = -50;

3

Page 222: Matlab Tutorial

K = place(A,B,[p1 p2 p3]);sys_cl=ss(A-B*K,B,C,0);lsim(sys_cl,u,t,x0);

Độ quá điều chỉnh quá lớn (như vậy là có 1 điểm không trong hàm truyền và có thể nó làm tăng độquá điều chỉnh, ta không thể thấy điểm không đó trong công thức không gian trạng thái). Thử đặt cáccực ra xa hơn về phía bên trái xem khả năng đáp ứng tức thời có được vải thiện hay không (điều nàycó nghĩa là làm cho đáp ứng nhanh hơn).

p1 = -20 + 20i;p2 = -20 - 20i;p3 = -100;K = place(A,B,[p1 p2 p3]);sys_cl = ss(A-B*K,B,C,0);lsim(sys_cl,u,t,x0);

Lần này độ quá điều chỉnh đã nhỏ hơn. Tham khảo sách in để có nhiều lời khuyên hơn nữa về cáchchọn các điểm cực mong muốn.

4

Page 223: Matlab Tutorial

Hãy so sánh khả năng điều khiển mong muốn của (K) trong cả hai trường hợp trên.. Nhìn chung, khita càng đặt điểm cực ra xa thì khả năng điều khiển của (K) càng tốt lên.

Chú ý: Nếu ta muốn đặt hai hoặc nhiều cực tại cùng 1 vị trí, lệnh place sẽ không thực hiện được. Khiđó ta có thể dùng lệnh acker tương tự như lệnh place để thực hiện:

K = acker(A,B,[p1 p2 p3])

Introducing the reference input

Bây giờ ta sẽ lấy hệ điều khiển như đã định nghĩa ở trên và áp dụng với đầu vào tín hiệu bậc thang (tachỉ chọn giá trị tín hiệu bậc thang nhỏ để thoả mãn điều kiện nằm trong vùng tuyến tính hóa). Thayt,u và lsim trong m-file lại như sau,

t = 0:0.01:2; u = 0.001*ones(size(t));sys_cl = ss(A-B*K,B,C,0);lsim(sys_cl,u,t)

Ta thất hệ thống không bám tín hiệu đầu vào một chút nào; không chỉ biên độ khác 1 mà còn có giá trịâm thay vì phải dương!

Xem lại sơ đồ khối bên trên ta thấy rằng ta không so sánh đầu ra với tín hiệu reference; thay vào đó tađã đo tất cả các trạng thái, nhân với vecto hệ số K, và lấy tín hiệu reference trừ đi kết quả đó. Khôngcó cơ sở nào để khẳng định rằng K*x sẽ bằng đầu ra mong muốn. Để giải quyết vấn đề này, ta có thểlấy tỉ lệ đầu vào reference sao cho nó bằng K*x_trạng thái tĩnh. Hệ số tỉ lệ này thường đựoc gọ làNbar; nó được đưa ra dưới dạng như sơ đồ sau:

5

Page 224: Matlab Tutorial

Ta có thể có được Nbar bằng cách dùng hàm rscale trong Matlab(đặt lệnh này sau lệnh K = ...).

Nbar=rscale(sys,K)

Chú ý hàm rscale không phải là 1 hàm chuẩn trong MATLAB. Để dùng được bạn phải copy nó trong 1m-file. Kích vào đây để biết chi tiết về cách dùng hàm này trong MATLAB. Bây giờ nếu ta muốn tìmđáp ứng của hệ thống với phản hồi trạng thái và tín hiệu đầu vào reference như đã nói ở trên, và tacũng chỉ quan niệm đơn giản là đầu vào được nhân với hệ số Nbar:

lsim(sys_cl,Nbar*u,t)

và ta có thể thấy đầu vào được hệ thống bám rất tốt.

Observer design

Khi chúng ta không thể đo được tất cả các trạng thái của x (đây là trường hợp hay gặp), ta có thể tạo1 khâu quan sát để ước lượng chúng trong lúc chỉ cần đo đầu ra y = C x. Với ví dụ bóng từ tính, ta sẽthêm mới ba trạng thái ước lượng vào hệ thống. Sơ đồ khối hệ thống sẽ như sau:

6

Page 225: Matlab Tutorial

Khâu quan sát cơ bản là 1 bản sao của khâu chấp hành; chúng có cùng đầu vào và các phương trình viphân hầu như giống nhau. Một thuật ngữ đặc biệt so sánh đầu ra đo thực tế y và đầu ra ước lượng ;điều này sẽ sinh ra 1 trạng thái ước luợng để tính xấp xỉ giá trị trạng thái thực tế x. Sai số động lựchọc của khâu quan sát được quy định bởi các cực của (A-L*C).

Trước hết ta cần chọn hệ số của khâu quan sát L. Vì chúng ta muốn động lực học của khâu quan sátnhanh hơn so với bản thân hệ thống nên ta cần đặt các cực ít nhất phải xa về phía bên trái gấp 5 lần sovới các cực chính. Muốn thế ta dùng lệnh place, và cần phải đặt các cực ở vị trí khác nhau.

op1 = -100;op2 = -101;op3 = -102;

Vì có sự đối ngẫu giữa tính điều khiển được và quan sát được, chúng ta có thể dùng cũng kỹ thuật đóđể tìm ma trận điều khiển, nhưng ta thay ma trận B bởi ma trận C và lấy chuyển vị của từng ma trận(tham khảo sách in để biết nguồn gốc vấn đề):

L = place(A',C',[op1 op2 op3])';

Các phương trình trong sơ đồ khối hệ thống trên được đưa ra cho . Thông thường hay viết cácphương trình liên hệ cho hệ thống và khâu chấp hành dùng trạng thái gốc x và thêm sai số trạng thái: e= x - . Chúng ta dùng 1 trạng thái phản hồi u = -K . Sau 1 số phép biến đổi đại số (tham khảosách in), chúng ta có phương trình liên kết trạng thái và sai số với tất cả các trạng thái phản hồi và mộtkhâu quan sát:

At = [A - B*K B*K zeros(size(A)) A - L*C];Bt = [ B*Nbar zeros(size(B))];Ct = [ C zeros(size(C))];

Để xem đáp ứng của hệ thống ra sao với điều kiện đầu khác không và không có tín hiệu reference,thêm các lệnh sau vào m-file. Chúng ta giả sử khâu quan sát có điều kiện đầu bằng 0, =0. Điều nàycho chúng ta điều kiện đầu của sai số bằng điều kiện đầu của trạng thái.

sys=ss(At,Bt,Ct,0);lsim(sys,zeros(size(t)),t,[x0 x0])

7

Page 226: Matlab Tutorial

Đáp ứng của các trạng thái được vẽ theo biểu đồ bên dưới. Nhớ lại rằng lệnh lsim cho chúng ta x và e;Để có ta phải lấy hiệu x-e.

Phóng to để nhìn chi tiết:

Đường nét liền màu xanh da trời là đáp ứng của vị trí bóng , đường nét đứt màu xanh da trời làtrạng thái ước lượng ;

8

Page 227: Matlab Tutorial

Đường nét liền màu xanh lá cây là đáp ứng của tốc độ bóng , đường nét đứt màu xanh là đườngtrạng thái ước lượng ;Đường nét liền màu đỏ là đáp ứng của dòng điện , đường nét đứt màu đỏ là đường trạng tháo ướclượng .

Chúng ta có thể thấy rằng khâu quan sát ước lượng các trạng thái nhanh và bám trạng thái xác lập khátốt.

Các biểu đồ trên vẽ bằng lệnh plot như sau:

[y,t,x] = lsim(sys,zeros(size(t)),t,[x0 x0]);plot(t,x)axis([0,.3,-.2,.2])

Các ví dụ về không gian trạng tháiĐiều khiển xe | Điều khiển tốc độ động cơ | Điều khiển vị trí động cơ | Bus Suspension | Điềukhiển con lắc ngược | Pitch Controller | Bài toán bóng và thanh đỡ

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

9

Page 228: Matlab Tutorial

Ví dụ: Giải pháp điều khiển xe sử dụng không giantrạng thái

Thiết kế điều khiển bằng cách gán điểm cựcĐầu vào Reference

Phương trình trạng thái của ví dụ này là:

ở đây

m=1000 kgb=50 N*sec/kgu=500 Nv=velocityy=output

Mục tiêu điều khiển là:

Thời gian quá độ < 5 secĐộ quá điều chỉnh < 10%

Sai số xác lập < 2%

Để biết cách thiết lập mô hình gốc, tham khảo phần Cruise Control Modeling.

Thiết kế điều khiển bằng cách gán điểm cực

Sơ đồ khối hệ thống phản hồi đầy đủ các trạng thái như sau.

ở đây

K=Ma trận điều khiểnU=-Kv=đầu vàoR=Reference

Nhắc lại phần Không gian trạng thái, chúng ta sẽ sử dụng kĩ thuật "gán điểm cực" để đạt được đầu ra

1

Page 229: Matlab Tutorial

mong muốn. Các cực của hệ kín có thể tìm được từ phương trình đặc tính: định thức của ma trận[sI-(A-B*K)] . Nếu các cực được đặt vào hệ thống bằng cách thiết kế cho chính ma trận điều khiển K,thì có thể đạt được đầu ra mong muốn. Trong phần này, các cực sẽ được chọn trước, sau đó ta dùngMatlab để tìm ma trận điều khiển K tương ứng.

Bây giờ ta cần xác định nơi đặt điểm cực. Vì ma trận [sI-(A-B*K)] là ma trận 1x1, nên ta chỉ gánđược 1 cực. Ta cho cực tại điểm -1.5 (tuỳ ý). Cũng giống như trong phần Không Gian Trạng Thái, hàmplace trong Matlab được dùng để tìm ma trận điều khiển K. Tạo 1 m-file có các lệnh sau.

m = 1000;b = 50;t = 0:0.1:10;u = 500*ones(size(t));

A = [-b/m];B = [1/m];C = [1];D = [0];cruise = ss(A,B,C,D);

x0 = [0];

p1 = -1.5;

K=place(A,B,[p1])

sys_cl=ss(A-B*K,B,C,D);lsim(sys_cl,u,t,x0);

Chạy m-file trong cửa sổ lệnh của Matlab ta sẽ có ma trận điều khiển và đáp ứng với đầu vào tín hiệubậc thang như sau.

Như ta thấy, thời gian quá độ đã thoả mãn nhưng sai số xác lập lại quá lớn.

Đầu vào Reference

Một lần nữa tham khảo từ phần Không gian trạng thái, hệ số tỉ lệ Nbar (như sơ đồ khối bên dưới)được dùng để khử sai số xác lập. Ta có thể dùng hàm rscale để tính hệ số tỉ lệ này. Đầu vào đã đượcnhân lên 500 lần, và ta muốn vận tốc ổn định ở giá trị 10 m/sec, nên ta cũng phải tính cả đến các hệ số

2

Page 230: Matlab Tutorial

đó.

Copy các lệnh sau vào m-file và chạy nó trong cửa sổ lệnh của Matlab. Ta sẽ có đáp ứng như sau. Tasẽ có đáp ứng như sau.

m=1000;b=50;t=0:0.1:10;u=500*ones(size(t));

A=[-b/m];B=[1/m];C=[1];D=[0];

x0=[0];

p1=-1.5

K=place(A,B,[p1]);

Nbar=rscale(cruise,k)*10/500;sys_cl=ss(A-B*K,B*Nbar,C,D);

lsim(sys_cl,u,t,x0);

Như ta thấy, sai số xác lập đã bị khử. Thời gian quá độ nhỏ hơn 5 giây và độ quá điều chỉnh trên thựctế là bằng 0. Tất cả các yêu cầu đặ ra đã hoàn thành.

State Space ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | Pitch

3

Page 231: Matlab Tutorial

Controller | Ball and Beam

Cruise Control ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

4

Page 232: Matlab Tutorial

Ví dụ: Bộ điều khiển không gian trạng thái cho tốcđộ động cơ 1 chiều

Thiết kế bộ điều khiển với phản hồi đầy đủ các trạng tháiThêm đầu vào reference

Từ bài toán gốc, phương trình động lực học của hệ biểu diễn trong không gian trạng thái có dạng nhưsau:

Để biết bài toán gốc thiết lập ra sao và các hệ quả của phương trình trên, tham khảo phần Mô hìnhđộng cơ 1 chiều.

Với tín hiệu reference 1 rad/sec đưa vào hệ thống, mục tiêu thiết kế đặt ra là:

Thời gian quá độ nhỏ hơn 2 giâyĐộ quá điều chỉnh nhỏ hơn 5%Sai số xác lập nhỏ hơn 1%

Tạo 1 m-file có các lệnh sau (tham khảo phần bài toán gốc để xem chi tiết).

J = 0.01;b = 0.1;K = 0.01;R = 1;L = 0.5;A = [-b/J K/J -K/L -R/L];B = [0 1/L];C = [1 0];D = 0;sys = ss(A,B,C,D);

Thiết kế bộ điều khiển với phản hồi đầy đủ các trạng thái

Vì cả hai biến trạng thái trong ví dụ này đều dễ dàng đo được (chỉ cần thêm một ampe kế đo dòng điệnvà tốc kế đo tốc độ), nên ta có thể thiết kế bộ điều khiển với phản hồi đầy đủ các trạng thái cho hệthống mà không cần phải lo đến việc thêm vào khâu quan sát. Sơ đồ khối cho hệ với phản hồi đầy đủcác trạng thái là:

1

Page 233: Matlab Tutorial

Nhớ lại rằng đa thức đặc tính của hệ kín là định thức của sI-(A-BK) với s là biến toán tử Laplace. Vìcác ma trận A và B*K đều là ma trận 2x2, nên hệ thống sẽ có 2 cực. Bằng cách thiết kế bộ điều khiểnvới phản hồi đầy đủ các trạng thái, chúng ta có thể đặt hai cực này vào bất cứ đâu ta muốn. Trước tiênta thử đặt chúng tại -5 + i và -5-i (chú ý rằng điều này tương ứng với zeta = 0.98 cho ta độ quá điềuchỉnh 0.1% và sigma = 5 sẽ cho ta thời gian ổn định là 1 giây). Chúng ta quay lại với các cực mà tamong muốn, MATLAB sẽ tìm cho ta ma trận điều khiển K cho chúng ta. Một cách đơn giản thêm cáclệnh sau vào m-file :

p1 = -5 + i;p2 = -5 - i;K = place(A,B,[p1 p2]);

Bây giờ hãy nhìn vào sơ đồ khối phía trên. Ta thấy rằng sau khi thêm ma trận điều khiển K vào hệthống, phương trình không gian trạng thái bây giờ là:

Ta có thể xem được đáp ứng của hệ kín bằng cách thêm các lệnh sau vào m-file:

t = 0:0.01:3;sys_cl = ss(A-B*K,B,C,D);step(sys_cl,t)

Chạy m-file trong cửa sổ lệnh, ta sẽ có biểu đồ sau:

2

Page 234: Matlab Tutorial

Thêm đầu vào reference

Từ biểu đồ trên ta thấy sai số xác lập quá lớn. Đối chiếu với các phương pháp thiết kế khác, ở đó taphản hồi lại đầu ra và so sánh nó với đầu vào reference để tính ra sai lệch, ở đây ta phản hồi cả haitrạng thái. Chúng ta cần tính toán xem sai số xác lập là bao nhiêu, sau đó nhân với hệ số đã chọn K,và dùng giá trị mới này làm reference cho việc tính toán đầu vào. Điều này có thể thực hiện bằng cáchthêm hệ số hằng Nbar after the reference:

We can find this Nbar factor by using the MATLAB command rscale:

Nbar=rscale(sys,K)

Note that the function rscale is not a standard function in MATLAB. You will have to copy it beforeyou use it. Click here for more information. Now we can plot the step response by adding thefollowing line of code to your m-file:

t = 0:0.01:10;step(sys*Nbar,t)title('Step Response with K Controller and Nbar')

3

Page 235: Matlab Tutorial

This time, the steady-state error is much less than 1%, and all the other design criteria have been metas well.

State Space ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Motor Speed ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

4

Page 236: Matlab Tutorial

Example: A State-Space Controller for DC MotorPosition Control

Designing the full-state feedback controllerDisturbance ResponseAdding Integral Action

From the main problem, the dynamic equations in state-space form are the following:

For the original problem setup and the derivation of the above equations, please refer to the ModelingDC Motor Position page.

With a 1 rad reference added to the system, the design criteria are:

Settling time less than 0.04 secondsOvershoot less than 16%Zero steady-state error to a step inputZero steady-state error to a step disturbance

Create a new m-file and type in the following commands (refer to the main problem for the details ofgetting those commands).

J = 3.2284E-6; b = 3.5077E-6; K = 0.0274;R = 4;L = 2.75E-6;

A = [0 1 0 0 -b/J K/J 0 -K/L -R/L];B = [0 ; 0 ; 1/L];C = [1 0 0];D = [0]; sys=ss(A,B,C,D);

Designing the full-state feedback controller

Since all of the state variab in our problem are very easy to measure (simply add an ammeter forcurrent, a tachometer for speed, and a potentiometer for position), we can design a full-state feedback

1

Page 237: Matlab Tutorial

controller for the system without worrying about having to add an observer. The schematic for afull-state feedback system is:

Recall that the characteristic polynomial for this closed-loop system is the determinant of(sI-(A-BKc)) where s is the Laplace variable. Since the matrices A and B*Kc are both 3x3 matrices,there should be 3 poles for the system. By designing a full-state feedback controller, we can movethese three poles anywhere we want them. We shall first try to place them at -100 + 100i and-100-100i (note that this corresponds to a zeta = 0.5 which gives 0.16% overshoot and a sigma = 100which leads to a .04 sec settling time). Once we come up with the poles we want, MATLAB will findthe controller matrix,Kc, for us. Simply add the following code to the end of your m-file :

p1 = -100+100i;p2 = -100-100i;p3 = -200;Kc = place(A,B,[p1,p2,p3]);

Now look at the schematic above again. We see that after adding the K matrix into the system, thestate-space equations become:

We can see the closed-loop response by simply adding the following line to the end of your m-file:

t = 0:0.001:.05;sys_cl=ss(A-B*Kc,B,C,D);step(sys_cl,t)

Run your m-file in the command window, You should see the following plot:

2

Page 238: Matlab Tutorial

Disturbance Response

In order to get the disturbance response, we must provide the proper input to the system. Physically, adisturbance is a torque which acts on the inertia of the motor. A torque acts as an additive term in thesecond state equation (which gets divided by J, as do all the other terms in this equation). We cansimulate this simply by modifying our closed loop input matrix, B, to have a 1/J in the second row.Add the following line to your m-file and re-run.

dist_cl=ss(A-B*Kc,[0;1/J;0],C,D);step(dist_cl,t)

3

Page 239: Matlab Tutorial

This is not a zero steady-state error to a disturbance, and we will have to compensate for this.

Adding Integral Action

We know that if we put an extra integrator in series with the plant it can remove steady-state error toan input. If the integrator comes before the injection of the disturbance, it will cancel the disturbancein steady state. This changes our control structure so it now resembles the following:

We can model the integrator by augmenting our state equations with an extra state which is theintegral of the output. This adds an extra equation which states that the derivative of the integral oftheta is theta. This equation will be placed at the top of our matrices. The input, r, now enters thesystem before the integrator, so it appears in the newly added top equation. The output of the systemremains the same.

These equations represent the dynamics of the system before the loop is closed. We will refer to thematrices in this equation as Aa, Ba, Ca, and Da. We will refer to the state vector of the augmentedsystem as xa. Note that the reference, r, does not affect the states (except the integrator state) or theoutput of the plant - this is expected, since there is no path from the reference to the plant input, u,without implementing the feedback matrix, Kc.

In order to find the closed loop equations, we have to look at how the input, u, affects the plant. Inthis case, it is exactly the same as in the unaugmented equations. Therefore, there is a vector, call itBau, which replaces Ba when we are treating u as the input. This is just our old B vector with an extrazero added as the first row. Since u=Kc*xa is the input to the plant for the closed loop, but r is theinput to the closed loop system, the closed loop equations will depend on both Bau and Ba. The closedloop equations will become:

4

Page 240: Matlab Tutorial

Now, the integral of the output will be fed back, and will be used by the controller to remove steadystate error to a disturbance. We can now redesign our controller. Since we need to place oneclosed-loop pole for each pole in the plant, we will place another pole at -300, which will be fasterthan the rest of the poles. Since the closed-loop system matrix depends on Bau, we will use Bau in theplace command rather that Ba. Add the following to your m-file:

Aa = [0 1 0 0 0 0 1 0 0 0 -b/J K/J 0 0 -K/L -R/L];Ba = [ -1 ; 0 ; 0 ; 0];Bau = [0 ; 0 ; 0 ; 1/L ];Ca = [0 1 0 0];Da = [0];

p4 = -300;Kc = place(Aa,Bau,[p1,p2,p3,p4]);

t = 0:0.001:.05;sys_cl = ss(Aa-Bau*Kc,Ba,Ca,Da);step(sys_cl,t)

Run your m-file (or just these new lines) and you will get the following output.

To look at the disturbance response, we apply a similar B matrix as we did previously when simulatingthe disturbance response.

dist_cl = ss(Aa-Bau*Kc,[0 ; 0 ; 1/J ; 0],Ca,Da);step(dist_cl,t)

5

Page 241: Matlab Tutorial

We can see that all of the design specifications have been met by this controller.

State Space ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Motor Position ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

6

Page 242: Matlab Tutorial

Example: A State-space Controller for a Bus SuspensionSystem

Designing the full-state feedback controllerPlotting the closed-loop response

From the main problem, the dynamic equations in state-space form are the following:

For the original problem setup and the derivation of the above equations, please refer to the Modeling page.

We want to design a feedback controller so that when the road disturbance (W) is simulated by a unit step input,the output (X1-X2) has a settling time less than 5 seconds and an overshoot less than 5%. For example, when thebus runs onto a 10 cm high step, the bus body will oscillate within a range of +/- 5 mm and will stop oscillatingwithin 5 seconds.

The system model can be represented in MATLAB by creating a new m-file and entering the following commands(refer to main problem for the details of getting those commands). We need to define the A, B, C, D matrices byentering the following into the m-file:

m1 = 2500;m2 = 320;k1 = 80000;k2 = 500000;b1 = 350;b2 = 15020;

A=[0 1 0 0 -(b1*b2)/(m1*m2) 0 ((b1/m1)*((b1/m1)+(b1/m2)+(b2/m2)))-(k1/m1) -(b1/m1) b2/m2 0 -((b1/m1)+(b1/m2)+(b2/m2)) 1 k2/m2 0 -((k1/m1)+(k1/m2)+(k2/m2)) 0];B=[0 0 1/m1 (b1*b2)/(m1*m2) 0 -(b2/m2) (1/m1)+(1/m2) -(k2/m2)];C=[0 0 1 0];D=[0 0];sys=ss(A,B,C,D);

Designing the full-state feedback controller

First, let's design a full-state feedback controller for the system. Assuming for now that all the states can be

1

Page 243: Matlab Tutorial

measured (this assumption is probably not true but is sufficient for this problem), the schematic of the systemshould be:

The characteristic polynomial for this closed-loop system is the determinant of (sI-(A-B[1,0]'K)). Note that it'snot sI-(A-BK) because the controller K can only control the force input u but not the road disturbance W.Recall that our B matrix is a 4 x 2 matrix, and we only need the first column of B to control u.

For this example, we have to use integral action to achieve zero steady-state error, so we add an extra statewhich is . In reality the bus will eventually reach an equilibrium that yields a zero steady-stateerror. The new states are X1, Y1, and Y2. Also the state-space matrices, A,B,and C, after adding extra statechange to be the following:

Aa=[0 1 0 0 0 -(b1*b2)/(m1*m2) 0 ((b1/m1)*((b1/m1)+(b1/m2)+(b2/m2)))-(k1/m1) -(b1/m1) 0 b2/m2 0 -((b1/m1)+(b1/m2)+(b2/m2)) 1 0 k2/m2 0 -((k1/m1)+(k1/m2)+(k2/m2)) 0 0 0 0 1 0 0];Ba=[0 0 1/m1 (b1*b2)/(m1*m2) 0 -(b2/m2) (1/m1)+(1/m2) -(k2/m2) 0 0];Ca=[0 0 1 0 0];Da=[0 0]; sys=ss(Aa,Ba,Ca,Da);

Actually, there is a shortcut for MATLAB to achieve the same result.

Aa = [[A,[0 0 0 0]'];[C, 0]];Ba = [B;[0 0]];Ca = [C,0];Da = D;sys=ss(Aa,Ba,Ca,Da);

Add the above MATLAB code into the m-file. In this case, we treat the problem like a PID controller design. Theintegral control is obtained from the new state. The proportional control is obtained from a gain on Y1 or X1-X2.The direct derivative control of the output isn't possible, since derivative of Y1 or X1-X2 isn't a state. Instead weuse the derivative of X1, which is available for feedback. (While X1 maybe hard to measure, could beobtained by integrating the output of an accelerometer mounted on the bus.) It is similar to adding more dampingto velocity of oscillation of the bus. Add the following MATLAB code for controller K in the m-file:

K = [0 2.3e6 5e8 0 8e6]

We arrived at this value of the K, matrix by trial and error, adjusting the gain for derivative of X1,Y1 and

2

Page 244: Matlab Tutorial

integral of Y1, as previously mentioned.

Plotting the closed-loop response

Looking at the schematic above again, we see that after adding the K matrix into the system, the state-spaceequations become:

We can now obtain the closed-loop response by simply adding the following code into the m-file. Note that weneed to multiply B matrix by 0.1 to simulate 0.1 m high step disturbance:

t = 0:0.01:2;sys_cl = ss(Aa-Ba(:,1)*K,-0.1*Ba,Ca,Da);step(sys_cl*[0;1],t)title('Closed-loop response to a 0.1 m step')

Running the m-file in the command window, you should see the following plot:

From the plot we see that the percent overshoot and settling time requirements are satisfied. Moreover thesteady-state error approaches zero as well. Therefore, we will determine that the response is satisfactory. Feelfree to play around with the gain for matrix K.

State Space ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | Pitch Controller |Ball and Beam

Bus Suspension ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space | Digital

3

Page 245: Matlab Tutorial

Control | Simulink Basics | Simulink Modeling | Examples

4

Page 246: Matlab Tutorial

Example: State-space design for the invertedpendulum

Open-loop polesLQR designAdding the reference InputObserver design

The state equations for this problem are:

The design criteria for this system with the cart receiving a 0.2 m step input are as follows:

Settling time for x and theta of less than 5 seconds.Rise time for x of less than 1 second.Overshoot of theta less than 20 degrees (0.35 radians).Steady-state error within 2%.

As you may have noticed if you went through some of the other inverted pendulum examples, thedesign criteria for this example are different. In the other examples we were dealing with an impulseand not a step input. Also, we were only concerned with the pendulums angle and disregarded thecart's position in the design of the controller. However, for an inverted pendulum it is unrealistic toconsider just the single output system. Using state-space methods it is relatively simple to work with amulti-output system, so in this example we will design a controller with both the pendulum angle andthe cart position in mind.

To see how this problem was originally set up, consult the inverted pendulum modeling page.

This problem can be solved using full state feedback. The schematic of this type of control system isshown below:

1

Page 247: Matlab Tutorial

If you are interested in running an animation of this example based on the control techniques used inthe state-space tutorial please go to the Inverted Pendulum Animation Page after completing thistutorial.

Open-loop poles

In this problem R represents the commanded step input to the cart. The 4 states represent the positionand velocity of the cart and the angle and angular velocity of the pendulum. The output y containsboth the position of the cart and the angle of the pendulum. We want to design a controller so thatwhen an step input is given to the system, the pendulum should be displaced, but eventually return tozero (i.e. the vertical) and the cart should move to its new commanded position. To view the system'sopen-loop response please refer to the inverted pendulum modeling page.

The first step in designing this type of controller is to determine the open-loop poles of the system.Enter the following lines of code into a m-file (or a '.m' file located in the same directory as MATLAB):

M = 0.5; m = 0.2; b = 0.1; i = 0.006; g = 9.8; l = 0.3;

p = i*(M+m)+M*m*l^2; %denominator A = [0 1 0 0;

0 -(i+m*l^2)*b/p (m^2*g*l^2)/p 0; 0 0 0 1; 0 -(m*l*b)/p m*g*l*(M+m)/p 0];

B = [0; (i+m*l^2)/p; 0; m*l/p]; C = [1 0 0 0; 0 0 1 0]; D = [0;0]; pend = ss(A,B,C,D); p = eig(A)

The MATLAB command window should output the following text as a result:

p = 0 -0.1428 5.5651 -5.6041

As you can see, there is one right-half-plane pole at 5.5651. This should confirm your intuition that the

2

Page 248: Matlab Tutorial

system is unstable in open loop.

LQR design

The next step in the design process is to assume that we have full-state feedback (i.e. that we canmeasure all four states), and find the vector K which determines the feedback control law. This can bedone in a number of ways. If you know the desired closed-loop poles, you can use the place or ackercommand. Another option is to use the lqr function; this will give you the optimal controller (undercertain assumptions; consult your textbook for more details). The lqr function allows you to choosetwo parameters, R and Q, which will balance the relative importance of the input and state in the costfunction that you are trying to optimize. The simplest case is to assume R=1, and Q=C'*C. You maynotice that we are using both outputs (the pendulum's angle and the cart's position). Essentially, the lqrmethod allows for the control of both outputs. In this case, it is pretty easy to do. The controller canbe tuned by changing the nonzero elements in the Q matrix to get a desirable response. To find thestructure of Q, enter the following into the MATLAB command window:

C'*C

You should see the following in the command window:

ans =

1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0

The element in the 1,1 position will be used to weight the cart's position and the element in the 3,3position will be used to weight the pendulum's angle. The input weighting R will remain at 1. Now thatwe know what the Q matrix should look like we can experiment to find the K matrix that will give us agood controller. We will go ahead and find the K matrix and plot the response all in one step so thatchanges can be made in the control and be seen automatically in the response. Enter the following textinto your m-file:

x = 1;y = 1;Q = [x 0 0 0; 0 0 0 0; 0 0 y 0; 0 0 0 0];R = 1;K = lqr(A,B,Q,R)Ac = [(A-B*K)];Bc = [B];Cc = [C];Dc = [D];sys_cl=ss(Ac,Bc,Cc,Dc);

T=0:0.01:5;U=0.2*ones(size(T));[Y,T,X]=lsim(sys_cl,U,T);plot(T,Y)legend('Cart','Pendulum')

You should get the following value for K and a response plot:

3

Page 249: Matlab Tutorial

K =

-1.0000 -1.6567 18.6854 3.4594

The curve in green represents the pendulum's angle in radians, and the curve in blue represents thecart's position in meters. As you can see, this plot is not satisfactory. The pendulum and cart'sovershoot appear fine, but their settling times need improvement and the cart's rise time needs to godown. As I'm sure you have noticed the cart is not near the desired location but has in fact moved inthe other direction. This error will be dealt with in the next section and right now we will focus on thesettling and rise times. Go back to your m-file and change the x and y variab to see if you can get abetter response. You will find that increasing x makes the settling and rise times go down, and lowersthe angle the pendulum moves. Using x=5000 and y=100, the following value of K and step responsewere found:

K =

-70.7107 -37.8345 105.5298 20.9238

4

Page 250: Matlab Tutorial

You may have noted that if you increased x and y even higher, you could improve the response evenmore. The reason this plot was chosen was because it satisfied the design requirements while keepingx and y as small as possible. In this problem, x and y have been used to describe the relative weight ofthe tracking error in the cart's position and pendulum's angle versus the control effort. The higher xand y are, the more control effort is used, but the smaller the tracking error. The system response has asettling time under 2 seconds.

Adding the reference input

Now we want to get rid of the steady-state error. In contrast to the other design methods, where wefeedback the output and compare it to the reference input to compute an error, with a full-statefeedback controller we are feeding back all the states. We need to compute what the steady-statevalue of the states should be, multiply that by the chosen gain K, and use a new value as our referencefor computing the input. This can be done by adding a constant gain Nbar after the reference. Theschematic below shows this relationship:

Nbar can be found using the user-defined function rscale (copy it to the directory that your m-file isin). Delete the lsim line and copy the following to your m-file and run it to view the step responsewith Nbar added.

Cn = [1 0 0 0]; sys = ss(A,B,Cn,0);

5

Page 251: Matlab Tutorial

Nbar = rscale(sys,K)sys_cl = ss(Ac,Bc*Nbar,Cc,Dc);[Y,T,X] = lsim(sys_cl,U,T);plot(T,Y)legend('Cart','Pendulum')

A different C had to be used because the rscale function will not work for multiple outputs.However, the Nbar found is correct, as you can see from the output below:

Nbar =

-70.7107

Now, the steady-state error is within our limits, the rise and settling times are met and the pendulum'sovershoot is within range of the design criteria.

Observer design

This response is good, but was found assuming full-state feedback, which most likely will not be avalid assumption. To compensate for this, we will next design a full-order estimator to estimate thosestates that are not measured. A schematic of this kind of system is shown below, without Nbar:

6

Page 252: Matlab Tutorial

To begin, we must first find the controller poles. To do this copy the following code to the end of yourm-file:

p = eig(Ac)

If you changed the weighting factors x and y above to x=5000 and y=100, you should see thefollowing poles in the MATLAB command window:

p =

-8.4910 + 7.9283i -8.4910 - 7.9283i -4.7592 + 0.8309i -4.7592 - 0.8309i

We want to design estimator poles that are about 4-10 times as fast as slowest pole, say at -40. We willuse the place command in MATLAB to find the L vector (note that acker would also work).Remember that the place command cannot have all the desired poles at the same location. Deletefrom the lsim command on and enter the following text to the end of your m-file to find the L matrix:

P = [-40 -41 -42 -43];L = place(A',C',P)'

We are using both outputs (the angle of the pendulum and the position of the cart) to design theobserver. The system is not observable using only the angle of the pendulum as output; you can checkthis in MATLAB by computing rank(obsv(A,C(2,:))). This should make sense to you: if you canonly measure the angle of the pendulum, you cannot determine what the position of the cart will be.

You should see the following in the MATLAB window:

L =

1.0e+03 *

0.0826 -0.0010 1.6992 -0.0402 -0.0014 0.0832 -0.0762 1.7604

Now we will combine the control-law design with the estimator design to get the compensator. Theresponse should be similar to the one from the control-law design. To set up the compensator copy thefollowing code to the end of your m-file:

Ace = [A-B*K B*K; zeros(size(A)) (A-L*C)];Bce = [ B*Nbar; zeros(size(B))];Cce = [Cc zeros(size(Cc))];Dce = [0;0];est_cl = ss(Ace,Bce,Cce,Dce);T = 0:0.01:5;U = 0.2*ones(size(T));[Y,T,X] = lsim(est_cl,U,T);plot(T,Y)legend('Cart','Pendulum')

After running this m-file, you should output the following step response simulation plot:

7

Page 253: Matlab Tutorial

This response is about the same as before. All of the design requirements have been met with theminimum amount of control effort, so no more iteration is needed.

As you can see, it is much easier to control multi-input or multi-output systems with the state spacemethod than with any other of the methods.

If you are interested in running an animation of the inverted pendulum example based on the controltechniques used in this tutorial please go to the Inverted Pendulum Animation Page.

State Space ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball & Beam

Inverted Pendulum ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink |Animation

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

8

Page 254: Matlab Tutorial

Example: State-space method for the PitchController

Controllability and ObservabilityControl design via pole placementReference input

In the Pitch Controller Modeling page, the state-space model was derived as

The input (elevator deflection angle, delta e) will be 0.2 rad (11 degrees), and the output is the pitchangle (theta).

The design requirements are

Overshoot: Less than 10%Rise time: Less than 5 secondsSettling time: Less than 10 secondsSteady-state error: Less than 2%

To see the original problem setup, please refer to the Pitch Controller Modeling page.

If you are interested in running an animation of this example based on the control techniques used inthe state-space tutorial please go to the Pitch Controller Animation page after completing this tutorial.

Controllability and Observability

The first thing to do in designing a system via state-space method is to check the controllability andobservability of the system. For the system to be completely state controllable, the controllabilitymatrix

1

Page 255: Matlab Tutorial

must have the rank of n. The rank of the matrix is the number of independent rows (or columns). Inthe same token, for the system to be completely state observable, the observability matrix

must also have the rank of n. Since our controllability matrix and observability matrix are 3x3, therank for both matrices must be 3. The MATLAB command rank can give you the ranks of bothmatrices. Create a new m-file and enter the following commands:

A = [-0.313 56.7 0; -0.0139 -0.426 0; 0 56.7 0]; B = [0.232; 0.0203; 0]; C = [0 0 1];

D = [0];

pitch = ss(A,B,C,D);

co = ctrb(pitch);ob = obsv(pitch);

Controllability = rank(co)Observability = rank(ob)

If you run this m-file in the MATLAB command window, you should see

Controllability =

3

Observability =

3

This proves that our system is both completely state controllable and completely state observable.

Control design via pole placement

The schematic of a full-state feedback system is shown below:

2

Page 256: Matlab Tutorial

where

K=Control matrixx=State matrix (alpha, q, theta)de=-Kx=inputR=Reference

Recall from the State-Space Tutorial page, the "pole placement" technique can be used to find thecontrol matrix (K). Since the determinant of [sI-(A-BK)] matrix is a third-order polynomial, there arethree poles we can place.

In the State-Space Tutorial, the dominant second-order pole placement method was introduced.However for this example, we will use another method called Linear Quadratic Regulator (LQR)method. This method allows you to find the optimal control matrix that results in some balancebetween system errors and control effort. Please consult your control textbook for details. To use thisLQR method, we need to find three parameters: performance index matrix (R), state-cost matrix (Q),and weighting factor (p). For simplicity, we will choose the performance index matrix equals 1 (R=1),and the state-cost matrix (Q) equals to C' x C. The weighting factor (p) will be varied as we see thestep response. To see the structure of the Q matrix, type in the following commands to an m-file andrun it in the MATLAB command window (or you can simply type them directly into the commandwindow).

C = [0 0 1];Q = C'*C

You should see the following Q matrix in the command window:

Q =

0 0 00 0 00 0 1

Now we are ready to find the control matrix (K) and see the response of the system. First, let theweighting factor (p) equal 50. Enter the following commands to a new m-file and run it in the MATLABcommand window.

t = 0:0.1:10;de = 0.2*ones(size(t));yo = [0 0 0];

A = [-0.313 56.7 0; -0.0139 -0.426 0; 0 56.7 0]; B = [0.232;

3

Page 257: Matlab Tutorial

0.0203; 0]; C = [0 0 1];

D = [0];

p = 50;Q = [0 0 0; 0 0 0; 0 0 p]; [K] = lqr(A,B,Q,1)

sys_cl=ss(A-B*K,B,C,D);lsim(sys_cl,de,t,yo)

After you run this m-file, you should see the step response similar to the one shown below:

The rise time, overshoot, and settling time look satisfactory. However, there is a large steady-stateerror. This can be easily corrected by introducing the feedforwarding scaling factor (Nbar).

Reference input

Unlike other design methods, the full-state feedback system does not compare the output to thereference; instead, it compares all states multiplied by the control matrix (K*x) to the reference (seethe schematic shown above). Thus, we should not expect to see the output equal to the input. Toobtain the desired output, we need to scale the reference input so that the output equals the reference.This can be easily done by introducing a feed-forwarding scaling factor called Nbar. The basicschematic with the scaling factor (Nbar) is shown below:

4

Page 258: Matlab Tutorial

We can easily find Nbar from the MATLAB function rscale. Since this rscale is a user-definedfunction, you need to copy and save the rscale m-file to your directory. For further assistance in usinguser-defined functions, refer to the function page. After you have saved the rscale m-file to yourdirectory, enter the following commands to a new m-file and run it in the MATLAB command window.You should see the response shown below:

t = 0:0.1:10;de = 0.2*ones(size(t));yo = [0 0 0];

A = [-0.313 56.7 0; -0.0139 -0.426 0; 0 56.7 0]; B = [0.232; 0.0203; 0]; C = [0 0 1];

D = [0];

pitch = ss(A,B,C,D);

x = 50;Q = [0 0 0; 0 0 0; 0 0 x]; [K] = lqr(A,B,Q,1) Nbar = rscale(pitch,K)

sys_cl = ss(A-B*K,B*Nbar,C,D); lsim (sys_cl,de,t,yo)

Now the steady-state error has been eliminated and all design requirements are satisfied.

If you are interested in running an animation of the pitch controller example based on the controltechniques used in this tutorial please go to the Pitch Controller Animation page.

State-Space Examples

5

Page 259: Matlab Tutorial

Cruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchControl | Ball and Beam

Pitch Control Examples Modeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink |Animation

Tutorials MATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

6

Page 260: Matlab Tutorial

Example: Solution to the Ball & Beam ProblemUsing the State-space Design Method

Full-State Feedback ControllerReference Input

The state-space representation of the ball and beam example is given below:

Unlike the previous examples where we controlled the gear's angle to control the beam and ball, herewe are controlling alpha-doubledot. By doing this we are essentially controlling a torque applied at thecenter of the beam by a motor. Therefore, we do not need a gear and lever system.

The design criteria for this problem are:

Settling time less than 3 secondsOvershoot less than 5%

To see the derivation of the state-space equations for this problem refer to the ball and beam modelingpage.

If you are interested in running an animation of this example based on the control techniques used inthe state-space tutorial please go to the Ball & Beam Animation Page after completing this tutorial.

Full-State Feedback Controller

We will design a controller for this physical system that utilizes full-state feedback control. Aschematic of this type of system is shown below:

1

Page 261: Matlab Tutorial

Recall, that the characteristic polynomial for this closed-loop system is the determinant of(sI-(A-BK)), where s is the Laplace variable. For our system the A and B*K matrices are both 4x4.Hence, there should be four poles for our system. In designing our full-state feedback controller wecan move these poles anywhere we want.

For our design we desire an overshoot of less than 5% which corresponds to a zeta of 0.7 (please referto your textbook for the relationship between overshoot and damping ratio). On a root locus thiscriterion is represented as a 45 degree line emanating from the origin and extending out into theleft-half plane. We want to place our desired poles on or beneath this line. Our next criterion is asettling time less than 3 seconds, which corresponds to a sigma = 4.6/Ts = 4.6/3 = 1.53, represented bya vertical line at -1.53 on the root locus. Anything beyond this line in the left-half plane is a suitableplace for our poles. Therefore we will place our poles at -2+2i and -2-2i. We will place the other polesfar to the left for now, so that they will not affect the response too much. To start with place them at-20 and -80. Now that we have our poles we can use MATLAB to find the controller (K matrix) byusing the place command. Copy the following code to an m-file to model the system and find the Kmatrix:

m = 0.111;R = 0.015;g = -9.8;J = 9.99e-6;

H = -m*g/(J/(R^2)+m); A = [0 1 0 0 0 0 H 0 0 0 0 1 0 0 0 0];B = [0;0;0;1];C = [1 0 0 0];D = [0];

ball = ss(A,B,C,D);

p1 = -2+2i;p2 = -2-2i;p3 = -20;p4 = -80;

K = place(A,B,[p1,p2,p3,p4])

Run your m-file and you should get the following output for the K matrix:

place: ndigits= 15

2

Page 262: Matlab Tutorial

K = 1.0e+03 * 1.8286 1.0286 2.0080 0.1040

After adding the K matrix, the state space equations now become:

We can now simulate the closed-loop response to a 0.25m step input by using the lsim command.Add the following to your m-file:

T = 0:0.01:5; U = 0.25*ones(size(T)); sys_cl = ss(A-B*K,B,C,D); [Y,T,X] = lsim(sys_cl,U,T); plot(T,Y)

Run your m-file and you should get the following plot:

From this plot we see that there is a large steady state error, to compensate for this, we will need toadd a reference input compensation (explained in next section). However, the overshoot and settlingtime criteria are met. If we wanted to reduce the overshoot further, we could make the imaginary partof the pole smaller than the real part. Also, if we wanted a faster settling time we would move thepoles further in the left-half plane. Feel free to experiment with the pole positions to see these trends.

Reference Input

Now we want to get rid of the steady-state error. In contrast to the other design methods, where wefeedback the output and compare it to the reference input to compute an error, with a full-statefeedback controller we are feeding back both states. We need to compute what the steady-state value

3

Page 263: Matlab Tutorial

of the states should be, multiply that by the chosen gain K, and use a new value as our reference forcomputing the input. This can be done by adding a constant gain Nbar after the reference. Theschematic below shows this relationship:

Nbar can be found using the user-defined function rscale (copy it to the directory that your m-file isin). Copy the following to your m-file and run it to view the step response with Nbar added.

Nbar=rscale(ball,K)

T = 0:0.01:5; U = 0.25*ones(size(T)); [Y,T,X]=lsim(Nbar*sys_cl,U,T); plot(T,Y)

Your output should be:

place: ndigits= 15 Nbar = 1.8286e+03

Now the steady-state error has been eliminated and all the design criteria are satisfied.

4

Page 264: Matlab Tutorial

Note: A design problem does not necessarily have a unique answer. Using this method (or any other)may result in many different compensators. For practice you may want to go back and try to changethe pole positions to see how the system responds.

If you are interested in running an animation of the ball & beam example based on the controltechniques used in this tutorial please go to the Ball & Beam Animation Page.

State-space ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball & Beam

Ball & Beam ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink |Animation

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

5

Page 265: Matlab Tutorial

Điều khiển số (Digital Control)IntroductionZero-order hold equivalenceConversion using c2dmStability and transient responseDiscrete Root-Locus

Key MATLAB Commands used in this tutorial are: c2d pzmap zgrid step rlocus

Introduction

The figure below shows the typical continuous feedback system that we have been considering so far inthis tutorial. Almost all of the continuous controllers can be built using analog electronics.

The continuous controller, enclosed in the dashed square, can be replaced by a digital controller, shownbelow, that performs same control task as the continuous controller. The basic difference between thesecontrollers is that the digital system operates on discrete signals (or samples of the sensed signal) ratherthan on continuous signals.

1

Page 266: Matlab Tutorial

Different types of signals in the above digital schematic can be represented by the following plots.

The purpose of this Digital Control Tutorial is to show you how to use MATLAB to work with discretefunctions either in transfer function or state-space form to design digital control systems.

Zero-order hold equivalence

In the above schematic of the digital control system, we see that the digital control system contains bothdiscrete and the continuous portions. When designing a digital control system, we need to find the discreteequivalent of the continuous portion so that we only need to deal with discrete functions.

For this technique, we will consider the following portion of the digital control system and rearrange asfollows.

2

Page 267: Matlab Tutorial

The clock connected to the D/A and A/D converters supplies a pulse every T seconds and each D/A andA/D sends a signal only when the pulse arrives. The purpose of having this pulse is to require that Hzoh(z)have only samples u(k) to work on and produce only samples of output y(k); thus, Hzoh(z) can be realizedas a discrete function.

The philosophy of the design is the following. We want to find a discrete function Hzoh(z) so that for apiecewise constant input to the continuous system H(s), the sampled output of the continuous systemequals the discrete output. Suppose the signal u(k) represents a sample of the input signal. There aretechniques for taking this sample u(k) and holding it to produce a continuous signal uhat(t). The sketchbelow shows that the uhat(t) is held constant at u(k) over the interval kT to (k+1)T. This operation ofholding uhat(t) constant over the sampling time is called zero-order hold.

3

Page 268: Matlab Tutorial

The zero-order held signal uhat(t) goes through H2(s) and A/D to produce the output y(k) that will be thepiecewise same signal as if the discrete signal u(k) goes through Hzoh(z) to produce the discrete outputy(k).

Now we will redraw the schematic, placing Hzoh(z) in place of the continuous portion.

By placing Hzoh(z), we can design digital control systems dealing with only discrete functions.

Note: There are certain cases where the discrete response does not match the continuous response due to ahold circuit implemented in digital control systems. For information, see Lagging effect associated with thehold.

Conversion using c2d

There is a MATLAB function called c2d that converts a given continuous system (either in transfer functionor state-space form) to a discrete system using the zero-order hold operation explained above. The basiccommand for this c2d is one of the following.

sys_d = c2d(sys,Ts,'zoh')

Note: sys can be generated from either tf or ss. Also discrete system can be generated with system data asfollowing. For more information on MATLAB representation, please refer to MATLAB representation.

The sampling time (Ts in sec/sample) should be smaller than 1/(30*BW), where BW is the closed-loopbandwidth frequency.

1. Transfer function

Suppose you have the following continuous transfer function

4

Page 269: Matlab Tutorial

M = 1 kgb = 10 N.s/mk = 20 N/mF(s) = 1

Assuming the closed-loop bandwidth frequency is greater than 1 rad/sec, we will choose the sampling time(Ts) equal to 1/100 sec. Now, create an new m-file and enter the following commands.

M = 1;b = 10;k = 20;

num = 1;den = [M b k];sys = tf(num,den);

Ts = 1/100;sys_d = c2d(sys,Ts,'zoh')

Running this m-file in the command window should give you the following result.

Transfer function:4.837e-05 z + 4.678e-05-----------------------z^2 - 1.903 z + 0.9048

Sampling time: 0.01

Note: The numerator and denominator matrices are represented in descending powers of z. For moreinformation on MATLAB representation, please refer to MATLAB representation.

Now you have the transfer function in discrete form.

2. State-Space

Suppose you have the following continuous state-space model

All constants are same as before

The following m-file converts the above continuous state-space to discrete state-space.

M = 1;b = 10;k = 20;

5

Page 270: Matlab Tutorial

A = [0 1; -k/M -b/M]; B = [ 0; 1/M]; C = [1 0];

D = [0]; Ts = 1/100;

sys = ss(A,B,C,D);sys_d = c2d(sys,Ts,'zoh')

Create an new m-file and copy the above commands. Running this m-file in the MATLAB commandwindow should give you the following results.

a = x1 x2

x1 0.99903 0.0095131 x2 -0.19026 0.9039

b = u1

x1 4.8366e-05 x2 0.0095131

c = x1 x2

y1 1 0

d = u1 y1 0

Sampling time: 0.01Discrete-time system.

From these matrices, the discrete state-space can be written as

Now you have the discrete time state-space model.

Note: For more information on the discrete state-space, please refer to Discrete State-Space.

Stability and transient response

For continuous systems, we know that certain behaviors results from different pole locations in the

6

Page 271: Matlab Tutorial

s-plane. For instance, a system is unstable when any pole is located to the right of the imaginary axis. Fordiscrete systems, we can analyze the system behaviors from different pole locations in the z-plane. Thecharacteristics in the z-plane can be related to those in the s-plane by the expression

T = Sampling time (sec/sample)s = Location in the s-planez = Location in the z-plane

The figure below shows the mapping of lines of constant damping ratio (zeta) and natural frequency (Wn)from the s-plane to the z-plane using the expression shown above.

If you noticed in the z-plane, the stability boundary is no longer imaginary axis, but is the unit circle |z|=1.The system is stable when all poles are located inside the unit circle and unstable when any pole is locatedoutside.

For analyzing the transient response from pole locations in the z-plane, the following three equations usedin continuous system designs are still applicable.

where

7

Page 272: Matlab Tutorial

zeta = Damping ratioWn = Natural frequency (rad/sec)Ts = Settling timeTr = Rise timeMp = Maximum overshoot

Important: The natural frequency (Wn) in z-plane has the unit of rad/sample, but when you use theequations shown above, the Wn must be in the unit of rad/sec.

Suppose we have the following discrete transfer function

Create an new m-file and enter the following commands. Running this m-file in the command windowgives you the following plot with the lines of constant damping ratio and natural frequency.

numDz = 1;denDz = [1 -0.3 0.5];sys = tf(numDz,denDz,-1); % the -1 indicates that the sample time is undetermined

pzmap(sys)axis([-1 1 -1 1])zgrid

From this plot, we see poles are located approximately at the natural frequency of 9pi/20T (rad/sample)and the damping ratio of 0.25. Assuming that we have a sampling time of 1/20 sec (which leads to Wn =28.2 rad/sec) and using three equations shown above, we can determine that this system should have therise time of 0.06 sec, a settling time of 0.65 sec and a maximum overshoot of 45% (0.45 more than thesteady-state value). Let's obtain the step response and see if these are correct. Add the followingcommands to the above m-file and rerun it in the command window. You should get the following stepresponse.

sys = tf(numDz,denDz,1/20);step(sys,2.5);

8

Page 273: Matlab Tutorial

As you can see from the plot, the rise time, settling time and overshoot came out to be what we expected.This shows how you can use the locations of poles and the above three equations to analyze the transientresponse of the system.

For more analysis on the pole locations and transient response, see Transient Response.

Discrete Root-Locus

The root-locus is the locus of points where roots of characteristic equation can be found as a single gain isvaried from zero to infinity. The characteristic equation of an unity feedback system is

where G(z) is the compensator implemented in the digital controller and Hzoh(z) is the plant transferfunction in z.

The mechanics of drawing the root-loci are exactly the same in the z-plane as in the s-plane. Recall fromthe continuous Root-Locus Tutorial, we used the MATLAB function called sgrid to find the root-locusregion that gives an acceptable gain (K). For the discrete root-locus analysis, we will use the functionzgrid that has the same characteristics as sgrid. The command zgrid(zeta, Wn) draws lines ofconstant damping ratio (zeta) and natural frequency (Wn).

Suppose we have the following discrete transfer function

and the requirements are a damping ratio greater than 0.6 and a natural frequency greater than 0.4rad/sample (these can be found from design requirements, sampling time (sec/sample) and three equationsshown in the previous section). The following commands draw the root-locus with the lines of constantdamping ratio and natural frequency. Create an new m-file and enter the following commands. Runningthis m-file should give you the following root-locus plot.

numDz = [1 -0.3];denDz = [1 -1.6 0.7];sys = tf(numDz,denDz,-1);

rlocus(sys)

9

Page 274: Matlab Tutorial

axis([-1 1 -1 1])

zeta = 0.4;Wn = 0.3;zgrid(zeta,Wn)

From this plot, you should realize that the system is stable because all poles are located inside the unitcircle. Also, you see two dotted lines of constant damping ratio and natural frequency. The naturalfrequency is greater than 0.3 outside the constant-Wn line, and the damping ratio is greater than 0.4 insidethe constant-zeta line. In this example, we do have the root-locus drawn in the desired region. Therefore, again (K) chosen from one of the loci in the desired region should give you the response that satisfies designrequirements.

Digital Control ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space | DigitalControl | Simulink Basics | Simulink Modeling | Examples

10

Page 275: Matlab Tutorial

Digital Control Example: Designing Cruise Controlusing Root-Locus method

Discrete transfer functionRoot-Locus in z-planeCompensation using a digital controller

In this digital control version of the cruise control problem, we are going to use the root-locus designmethod to design the digital controller. If you refer to the Cruise Control: Modeling page, theopen-loop transfer function was derived as

where

m = 1000b = 50U(s) = 10Y(s) = velocity output

The design requirements are

Rise time: Less than 5 secondsOvershoot: Less than 10%Steady-state error: Less than 2%

Discrete transfer function

The first step in performing a discrete analysis of a system is to find the discrete equivalent transferfunction of the continuous portion. We will convert the above transfer function (Y(s)/U(s)) to thediscrete transfer function using the MATLAB function called c2d. To use this c2d, you need to specifythree arguments: system, sampling time (Ts), and the 'method'. You should already be familiar withhow to enter num and den matrices. The sampling time (Ts), in the unit of sec/sample, should besmaller than 1/(30*BW), where BW is the closed-loop bandwidth frequency. For the method, we willuse the zero-order hold ('zoh').

Let the sampling time equal 1/50 sec; this is sufficiently fast assuming that the bandwidth frequency is1 rad/sec. Now enter the following commands into an m-file and run it in the command window.

num = [1];den = [1000 50];cruise = tf(num,den);

Ts = 1/50;

cruise_d = c2d(cruise,Ts,'zoh')

1

Page 276: Matlab Tutorial

The following matrices should be returned to the command window.

Transfer function:1.999e-05---------z - 0.999

Sampling time: 0.02

Root-Locus in z-plane

Recall from the Digital Control Tutorial, the MATLAB function called zgrid can be used to find anacceptable region of the discrete root-locus that gives the desired gain (K). The zgrid commandrequires two arguments: Natural frequency (Wn) and damping ratio (zeta). These two arguments canbe found from the rise time and the overshoot requirements and the following two equations.

where

Wn=Natural frequency (rad/sec)zeta=Damping ratioTr=Rise timeMp=Maximum overshoot

Since our rise time and overshoot requirements are 5 seconds and 10%, respectively, we candetermine that the natural frequency (Wn) must be greater than 0.36 rad/sec and the damping ratio(zeta) must be greater than 0.6.

Let's generate the root-locus and use the zgrid to find the acceptable region of the root-locus. Butbefore doing that, if you refer to the Digital Control Tutorial, the natural frequency argument for zgridneeds to be in the unit of rad/sample, so let Wn = 0.36*Ts = 0.0072 rad/sample. Now add thefollowing commands to the above m-file and rerun it. You should get the following plot.

Wn = 0.0072;zeta = 0.6;

rlocus(cruise_d)zgrid(zeta, Wn)axis ([-1 1 -1 1])

2

Page 277: Matlab Tutorial

The region of the complex plane which interests us is that which is near the point (1,0), so you shouldzoom in on this point. Rerun using the axis command below you should now see

axis ([0.95 1 -.1 .1])

The dotted line on the right, indicates the locations of constant natural frequency (Wn), and thenatural frequency is greater than 0.0072 outside the line. The other dotted line indicates the locationsof constant damping ratio (zeta), and the damping ratio is greater than 0.6 inside the line. The jaggedvertical line is a portion of the unit circle which is calculated at low resolution (hence the jaggedness).

In the above plot, you see that part of the root-locus is inside the desired region. Let's find a gain (K)using the MATLAB function rlocfind and obtain the corresponding step response. Add the followingcommands to the above m-file and rerun it in the MATLAB command window.

[K,poles] = rlocfind(cruise_d)

3

Page 278: Matlab Tutorial

In the command window, you should see the prompt asking you to select a point on the root-locus.Remember that if you choose a pole which is too far inside the unit circle, then the step response willbe too fast indicating a physically unreasonable acceleration. Therefore you should choose the polewhich is near the intersection of the constant natural frequency and the real axis. The gain (K) and thepole location should be returned to the command window. Selecting the point at 0.99 gives thefollowing root locus graph.

To see the step response, add the following to your m-file.

sys_cl = feedback(K*cruise_d,1);U = 10;figurestep(U*sys_cl,10);

This response satisfies the rise time and overshoot requirements. But the steady state error is about11%. To obtain the desired steady state error, we will modify the discrete controller.

4

Page 279: Matlab Tutorial

Compensation using a digital controller

Recall from the continuous Cruise Control: Root-Locus page, the lag controller was added to thesystem to obtain the desired response. In this digital control version of the cruise control problem, wewill modify the existing digital controller by adding a function of the form

There is a guideline to design digital lead and lag compensators and a guideline for design continuoustime lead and lag compensators. The discrete design method described says that the zero of the lagcompensator should be chosen to (approximately) cancel one of the plant poles, as long as it is stable.Thus, we choose the zero to be at Zo = 0.999.

To reduce the steady state error, we note that the low frequency gain of the discrete time controlsystem with a lag compensator is increased by a factor of of (1 - Zo)/(1 - Po). To reduce the steadystate error by a factor of 5, we choose Po = 0.9998. To have a a gain of 1 at zero frequency, thenumerator is multiplied by Kd = (1 - Zp)/(1 - Zo) = 0.2 before using the root locus. Note that thewhole compensator is multiplied by the gain determined from the root locus.

Now we have the discrete compensator transfer function. Let's generate the root-locus and obtain thestep response. Create a new m-file and enter the following commands.

num = [1];den = [1000 50];cruise = tf(num,den)

Ts = 1/50;cruise_d = c2d (cruise,Ts,'zoh');contr = tf(0.2*[1 -0.999],[1 -0.9998],Ts);

Wn = 0.0072;zeta = 0.6;

rlocus(contr*cruise_d)zgrid(zeta, Wn)axis([0.98 1 -0.01 0.01])

[K,poles] = rlocfind(contr*cruise_d)

sys_cl = feedback(K*contr*cruise_d,1);U = 10;figurestep(U*sys_cl,10);

Running this m-file in the command window give you the following root-locus.

5

Page 280: Matlab Tutorial

In the command window, you should be asked to pick a point on the root-locus. Click on the locusnear +0.99. You should now have the step response similar to the one shown below.

This response rises about as fast as before, but the steady state error has been reduced to 2%. Thissystem satisfies all design requirements with the reasonable control effort.

Note: A design problem does not necessarily have a unique answer. For practice, you may try othercompensators to obtain a better response than the one shown above.

Digital Control ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

6

Page 281: Matlab Tutorial

Cruise Control ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

7

Page 282: Matlab Tutorial

Example: Digital DC Motor Speed Control withPID Control

Continuous to Discrete ConversionPID Controller

In this page, we will consider the digital control version of DC motor speed problem. A digital DCmotor model can be obtained from conversion of the analog model, as we will describe. The controllerfor this example will be designed by a PID method.

From the Modeling a DC Motor Page, the open-loop transfer function for DC motor's speed wasderived as:

Where:

*electrical resistance (R) = 1 ohm*electrical inductance (L) = 0.5 H*electromotive force constant (Ke=Kt) = 0.01 Nm/Amp*moment of inertia of the rotor (J) = 0.01 kg*m^2/s^2*damping ratio of the mechanical system (b) = 0.1 Nms*input (V): Source Voltage*output (theta dot): Rotating speed*The rotor and shaft are assumed to be rigid

The design requirements for 1 rad/sec step input are

Settling time: Less than 2 secondsOvershoot: Less than 5%Steady-state error: Less than 1%

Continuous to Discrete Conversion

The first step in designing the discrete control system is to convert the continuous transfer function toa discrete transfer function. The MATLAB command c2d will do this for you. The c2d commandrequires the following three arguments: system, the sampling time (Ts) and method for conversion. Inthis example, we will use the zero-order hold ('zoh') method.

From the design requirement, let the sampling time, Ts equal 0.12 seconds, which is 1/10 the timeconstant of a system with a settling time of 2 seconds. Let's create a new m-file and enter thefollowing commands:

R = 1;L = 0.5;

1

Page 283: Matlab Tutorial

Kt = 0.01;J = 0.01;b = 0.1;

num = Kt;den = [(J*L) (J*R)+(L*b) (R*b)+(Kt^2)];

motor = tf(num,den)

Ts = 0.12;motor_d= c2d(motor,Ts,'zoh')

Running this m-file should return the following:

Transfer function:0.009201 z + 0.005709----------------------z^2 - 1.088 z + 0.2369 Sampling time: 0.12

After you have done this, let's see what the closed-loop step response looks like with a proportionalgain of 1. The step command will do this for you. Click here for more information. Add the followingMATLAB code to the end of previous m-file and rerun it.

sys_cl = feedback(motor_d,1)[Y,T] = step(sys_cl,12);stairs(T,Y);xlabel('Time (s)')ylabel('Velocity (rad/s)')title('Stairstep Response:Original')

You should see the following plot:

PID Controller

2

Page 284: Matlab Tutorial

Recall that the continuous-time transfer function for a PID controller is:

There are several ways for mapping from the s-plane to z-plane. The most accurate one is . Wecannot obtain PID transfer function in this way because the discrete-time transfer function wouldhave more zeroes than poles, which is not realizable. Instead we are going to use the bilineartransformation shown below.

Thus we can derive the discrete PID controller with bilinear transformation mapping. For more detailon the derivation of the discrete PID controller, see the Discrete PID Controller Page. Equivalently,the c2d command in MATLAB will help you to convert the continuous-time PID compensator todiscrete-time PID compensator by using the "tustin" method. The "tustin" method use the bilinearapproximation to convert to discrete time. According to the PID Design Method for the DC Motorpage, Kp = 100, Ki = 200 and Kd = 10 satisfy the design requirement. We will use all of these gains inthis example. Now add the following MATLAB commands to your previous m-file and rerun it inMATLAB window.

% Discrete PID controller with bilinear approximationKp = 100;Ki = 200;Kd = 10;

PID = tf([Kd Kp Ki],[1 0]);contr = c2d(PID,Ts,'tustin');

Let's see if the performance of the closed-loop response with the PID compensator satisfies the designrequirements. Now add the following code to the end of your m-file and rerun it. You should get thefollowing closed-loop stairstep response.

sys_cl = feedback(contr*motor_d,1);

[x2,T] = step(sys_cl,12);stairs(T,x2)xlabel('Time (seconds)')ylabel('Velocity (rad/s)')title('Stairstep Response:with PID controller')

3

Page 285: Matlab Tutorial

As you can see from the above plot, the closed-loop response of the system is unstable. Thereforethere must be something wrong with compensated system. So we should take a look at root locus ofthe compensated system. Let's add the following MATLAB command into the end of your m-file andrerun it.

rlocus(contr*motor_d)title('Root Locus of Compensated System')

From this root-locus plot, we see that the denominator of the PID controller has a pole at -1 in thez-plane. We know that if a pole of a system is outside the unit circle, the system will be unstable. Thiscompensated system will always be unstable for any positive gain because there are an even numberof poles and zeroes to the right of the pole at -1. Therefore that pole will always move to the left andoutside the unit circle. The pole at -1 comes from the compensator, and we can change its location bychanging the compensator design. We choose it to cancel the zero at -0.62. This will make the system

4

Page 286: Matlab Tutorial

stable for at least some gains. Furthermore we can choose an appropriate gain from the root locus plotto satisfy the design requirements using rlocfind. Enter the following MATLAB code to your m-file.

contr.den = conv([1 -1],[1/.62 1]);

rlocus(contr*motor_d)title('Root Locus of Compensated System');[K,poles] = rlocfind(contr*motor_d)sys_cl = feedback(K*contr*motor_d,1);

[x3,T] = step(sys_cl,12);stairs(T,x3)xlabel('Time (seconds)')ylabel('Velocity (rad/s)')title('Stairstep Response:with PID controller')

Note how the first line of code above allows you to change the denominator of the system transferfunction directly, without having to redefine the system. The new closed loop poles will have a pole at-0.625 instead of -1, which almost cancels the zero of uncompensated system. In the MATLABwindow, you should see the command asking you to select the point on the root-locus plot. You shouldclick on the plot as the following:

Then MATLAB will return the appropriate gain and the corresponding compensated poles, and it willplot the closed-loop compensated response as follows.

5

Page 287: Matlab Tutorial

The plot shows that the settling time is less than 2 seconds and the percent overshoot is around 3%. Inaddition, the steady state error is zero. Also, the gain, K, from root locus is 0.2425 which isreasonable. Therefore this response satisfies all of the design requirements.

Digital Control ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Motor Speed ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

6

Page 288: Matlab Tutorial

Example: Root Locus Design for Digital DC MotorPosition Control

Continuous to Discrete ConversionRoot Locus Design

In this example, the controller will be designed by a Root Locus method. A digital DC motor modelcan obtain from conversion of analog DC motor model, as we will describe. According to theModeling a DC Motor Page, the open-loop transfer function for DC motor's position is as shown.

where:

*electric resistance (R) = 4 ohm*electric inductance (L) = 2.75E-6 H*electromotive force constant (K=Ke=Kt) = 0.0274 Nm/Amp*moment of inertia of the rotor (J) = 3.2284E-6 kg*m^2/s^2*damping ratio of the mechanical system (b) = 3.5077E-6 Nms*input (V): Source Voltage*output (sigma dot): Rotating speed*The rotor and shaft are assumed to be rigid

The design requirements are:

Settling time: Less than 0.04 secondsOvershoot: Less than 16%Steady-state error: 0 with a step disturbance input

Continuous to Discrete Conversion

The first step in the design of a discrete-time system is to convert a continuous transfer function to adiscrete transfer function. MATLAB can be used to convert the above transfer function todiscrete transfer function by using the c2d command. The c2d command requires three arguments:system, a sampling time (T) and a type of hold circuit. In this example we will use the zero-order hold(zoh). Refer to the Digital Control Tutorials page for more information.

From the design requirement, let the sampling time, T equal to 0.001 seconds, which is 1/100 of therequired time constant or 1/40 of the required settling time. Let's create a new m-file and add thefollowing MATLAB code:

R = 4;L = 2.75E-6;K = 0.0274;J = 3.2284E-6;

1

Page 289: Matlab Tutorial

b = 3.5077E-6;

num = K;den = [(J*L) (J*R)+(L*b) (R*b)+(K^2) 0];motor = tf(num,den)

Ts = 0.001;motor_d = c2d(motor, Ts, 'zoh')[numd,dend] = tfdata(motor_d,'v')

MATLAB should return the following:

Transfer function:0.001039 z^2 + 0.001021 z + 9.454e-10-------------------------------------z^3 - 1.942 z^2 + 0.9425 z

Sampling time: 0.001

numd =

0 0.0010 0.0010 0.0000

dend =

1.0000 -1.9425 0.9425 0

As noticed above, both the numerator and the denominator of the discrete transfer function have oneextra root at z = 0. Also, we can get rid of the leading zero coefficient in the numerator. To do this addthe following code to cancel out extra pole and zero to avoid numerical problems in MATLAB.Otherwise it will consider both the numerator and denominator to be fourth-order polynomials.

numd = numd(2:3);dend = dend(1:3);motor_d = tf(numd,dend,Ts)

Therefore, the discrete-time transfer function from the motor position output to the voltage input is:

We would like to see what the closed-loop response of the system looks like when no controller isadded. First, we have to close the loop of the transfer function by using the feedback command. Afterclosing the loop, let's see how the closed-loop stairstep response performs by using the stepand stairscommands. The step command will provide the vector of discrete step signals and stairs command willconnect these discrete signals (click here for more information). Add the following MATLAB code atthe end of previous m-file and rerun it.

sys_cl = feedback(motor_d,1);[x1,t] = step(sys_cl,.5);stairs(t,x1)xlabel('Time (seconds)')ylabel('Position (rad)')title('Stairstep Response:Original')

You should see the following plot:

2

Page 290: Matlab Tutorial

Root Locus Design

The main idea of root locus design is to obtain the closed-loop response from the open-loop root locusplot. By adding zeroes and poles to the original system, the root locus can be modified, to a newclosed-loop response. First let's see the root-locus for the system itself. In your m-file, add thefollowing commands and rerun it. You should get the root-locus plot as shown below.

rlocus(motor_d)title('Root Locus of Original System')zgrid(0,0)axis([-2,2,-2,2])

To get the zero steady-state error from the closed-loop response, we have to add an integral control.

3

Page 291: Matlab Tutorial

Recall that the integral control in the continuous- time is 1/s. If we use the backward differenceapproximation for mapping from the s-plane to the z-plane as described by s = 1/(z-1), one pole willbe added at 1 on the root locus plot. After adding the extra pole at 1, the root locus will have threepoles near 1. Therefore the root locus will move out to the right, and the closed-loop response will bemore unstable. Thus, we must add one zero near 1, inside the unit circle, to cancel with one pole andpull the root locus in. We will add a zero at z = 0.95. In general, we must at least add as many poles aszeroes for the controller to be causal. Now add the following MATLAB commands in to your m-file.

numi = [1 -0.95];deni = [1 -1];icontr = tf(numi,deni,Ts);

Recall from the Digital Control Tutorial page, the zgrid command can be used to find the desiredregion (satisfying the design requirements) on the discrete root locus plot. The zgrid command requirestwo arguments: the natural frequency (Wn) and the damping ratio (zeta). From the designrequirement, the settling time is less than 0.04 seconds and the percent overshoot is less than 16%. Weknow the formulas for finding the damping ratio and natural frequency as shown:

where:

OS: the percent overshoot Ts: the settling time

The required damping ratio is 0.5 and the natural frequency is 200 rad/sec, but the zgrid commandrequires a non-dimensional natural frequency. Therefore Wn = 200*Ts = 0.2 rad/sample. Add thefollowing MATLAB code into the end of your m-file and rerun it.

rlocus(icontr*motor_d);zgrid(0.5,0.2)title('Root Locus of system with integral control')axis([-2,2,-2,2])

You should get the following plot:

4

Page 292: Matlab Tutorial

From the above root locus plot, we can see that system is unstable at all gains because the root locus isoutside the unit circle. Moreover, the root locus should be in the region where the damping ratio lineand natural frequency cross each other to satisfy the design requirements. Thus we have to pull theroot locus in further by first canceling the zero at approximately -0.98, since this zero will addovershoot to the step response. Then we have to add one more pole and two zeroes near the desiredpoles. After going through some trial and error, one more pole is added at 0.61 and two zeroes areadded at 0.76. Add the following commands to your m-file and rerun it in the MATLAB window.

numc = conv([1 -0.76],[1 -0.76]);denc = conv([1 0.9831],[1 -0.61]);contr = tf(numc,denc,Ts);

rlocus(icontr*contr*motor_d);zgrid(0.5,0.2)title('Root Locus of Compensated System')axis([-2,2,-2,2])

The system will have a pole at 0.61 instead of -0.98. You should get the following root locus plot:

5

Page 293: Matlab Tutorial

From the above root locus plot, we see that the root locus is in the desired region. Let's find a gain, K,on the root locus plot by using the rlocfind command and obtain the stairstep response with theselected gain. Enter the following commands at the end of your m-file and rerun it.

K = rlocfind(icontr*contr*motor_d)sys_cl = feedback(K*icontr*contr*motor_d,1);

[x2,t] = step(sys_cl,.05);stairs(t,x2)xlabel('Time (seconds)')ylabel('Position (rad)')title('Stairstep Response of Compensated System')

In the MATLAB window, you should see the command asking you to select a point on the root-locusplot. You should click on the plot as the following:

6

Page 294: Matlab Tutorial

The selected gain should be around 330, and it will plot the closed-loop compensated response asfollows.

From the above closed-loop response, the settling time is about 0.05 seconds which is satisfy therequirement, but the percent overshoot is 22% which is too large due to the zeroes. If we select thegain to be larger, the requirements will be satisfied. On the other hand, the problem will be unrealisticand a huge actuator is needed, you can try this yourself by picking a larger gain on the previous rootlocus plot which will yield an unrealistically sudden step response. So we have to move both one poleand two zeroes a little further to the right to pull root locus in a little bit more. The new pole will beput at 0.7 and two zeroes will be at 0.85. Go back to your m-file and change only numc and denc asshown below and rerun it in MATLAB window.

numc = conv([1 -0.85],[1 -0.85]);denc = conv([1 0.9831],[1 -0.7]);

7

Page 295: Matlab Tutorial

Then you should see the following root locus plot.

On the new root locus, you should click on the plot to select a new gain as the following:

The selected gain should be around 450, and then it will plot the closed-loop compensated response asfollows:

8

Page 296: Matlab Tutorial

Now we see that the settling time and percent overshoot meet the design require ments of the system.The settling time is 0.04 seconds and the percent overshoot is about 10%.

Now let's take a look at a disturbance response of the closed-loop system. We need to cancel theselected gain, the integral transfer function and controller's transfer function from the closed-looptransfer function. So add the following code into your m-file and rerun it.

dist_cl=feedback(motor_d,K*icontr*contr);

[x4,t] = step(dist_cl,.25);stairs(t,x4)xlabel('Time (seconds)')ylabel('Position (rad)')title('Stairstep Response of Compensated System')

MATLAB should return the following plot:

9

Page 297: Matlab Tutorial

We can see that a response to the disturbance is small (3.3% of the disturbance ) and settles within 2%of the disturbance after 0.04 seconds and eventually reaches zero.

Digital Control ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Motor Position ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

10

Page 298: Matlab Tutorial

Example: State Space Design for Digital BusSuspension Control

Sampling Time SelectionContinuous to Discrete ConversionDesigning the ControllerSimulating the Closed-Loop Response

In this example, we will design a digital state space controller for the bus suspension control example. First wewill convert the continuous time model to a discrete time model, and then use the pole placement method todesign the controller. From the bus suspension state space modeling page, the state space model of the systemis:

Where:

* body mass (m1) = 2500 kg,* suspension mass (m2) = 320 kg,* spring constant of suspension system (k1) = 80,000 N/m,* spring constant of wheel and tire (k2) = 500,000 N/m,* damping constant of suspension system (b1) = 350 Ns/m.* damping constant of wheel and tire (b2) = 15,020 Ns/m.* control force (u) = force from the controller we are going to design.

The design requirements are:

Overshoot: Output (X1-X2) less than 5% of disturbance (W)Settling time: Less than 5 seconds

Sampling Time Selection

The first step in the design of a discrete-time controller is to convert the continuous plant to its discrete timeequivalent. First, we need to pick an appropriate sampling time, T. In this example, selection of sampling timeis very important since a step in the road surface very quickly affects the output. Physically, what happens isthe road surface suddenly lifts the wheel, compressing the spring, K2, and the damper, b2. Since thesuspension mass is relatively low, and the spring fairly stiff, the suspension mass rises quickly, increasing X2

1

Page 299: Matlab Tutorial

almost immediately. Since the controller can only see the effect of the disturbance after a complete samplingperiod, we have to pick a sampling time, T, short enough so that the output (X1-X2) does not exceed the 5%requirement in one sampling period. To pick the sampling period, we need to closely examine the beginning ofthe step response. If you remember from the modeling page, the output quickly goes negative in response to astep disturbance, and then begins to oscillate. We will simulate just the beginning of this response by settingthe time vector input to the step function to range from 0 to .005. The response to a .1m step input is simulatedby multiplying the B matrix by .1. Create a new m-file and enter the following code:

m1 = 2500;m2 = 320;k1 = 80000;k2 = 500000;b1 = 350;b2 = 15020;

A = [0 1 0 0 -(b1*b2)/(m1*m2) 0 ((b1/m1)*((b1/m1)+(b1/m2)+(b2/m2)))-(k1/m1) -(b1/m1) b2/m2 0 -((b1/m1)+(b1/m2)+(b2/m2)) 1 k2/m2 0 -((k1/m1)+(k1/m2)+(k2/m2)) 0]; B = [0 0 1/m1 (b1*b2)/(m1*m2) 0 -(b2/m2) (1/m1)+(1/m2) -(k2/m2)];C = [0 0 1 0];D = [0 0];

sus = ss(A,B,C,D);step(sus*[0;1]*.1,0:0.0001:.005);

This plot shows that the spring, K1 compresses very quickly, and exceeds our requirement of 5mm in responseto a .1m step after only a little more than 0.001s. Therefore, we will set T=.0005s in order to give thecontroller a chance to respond.

Continuous to Discrete Conversion

Now that we have selected a sampling time, we can convert the plant to discrete time. MATLAB can be used toconvert the above state space model, sus, to a discrete state space model, sus_d, by using the c2d command.The c2d command takes three arguments: the continuous time system, the sampling time, T, and the type of

2

Page 300: Matlab Tutorial

hold circuit. In this example we will use zero-order hold ('zoh'). Refer to the Digital Control Tutorials page formore information.

Add the following code to your m-file:

T = .0005;sus_d = c2d(sus,T,'zoh')

MATLAB should return the following:

a = x1 x2 x3 x4 x1 1 0.0005 -3.1263e-06 -1.8022e-08 x2 -0.0034605 1 -0.012444 -7.3126e-05 x3 0.02338 5.8525e-06 0.97598 0.00049399 x4 0.77045 0.00019351 -0.91116 0.99977 b = u1 u2 x1 4.9989e-11 8.5058e-07 x2 1.9994e-07 0.0034605 x3 4.3748e-10 -0.02338 x4 1.7624e-06 -0.77045 c = x1 x2 x3 x4 y1 0 0 1 0 d = u1 u2 y1 0 0

Sampling time: 0.0005Discrete-time system.

which represent the new discrete-time state space model.

Adding an Integrator

In this example, we will need to add an integrator to the system in order to drive the steady-state response tozero. We will add this integrator in series with the plant. This will have the effect of adding another state to theplant. An integrator in discrete time state space can be represented as a trapezoidal approximation ofintegration over each sample period as follows:

To add this, add the following commands in your m-file:

Ai = 1;Bi = T;Ci = 1;Di = T/2;[As,Bs,Cs,Ds]=ssdata(sus_d);Aa = [As, zeros(4,1); Bi*Cs, Ai];Ba = [Bs; 0,0];

3

Page 301: Matlab Tutorial

Ca = [Cs, 0];Da = Ds;

sus_di = ss(Aa,Ba,Ca,Da,T);[Ad,Bd,Cd,Dd] = ssdata(sus_di);

Designing the Controller

The structure of the controller is similar to the structure of the continuous-time state space controller. We willnow use the place command to compute the gain matrix, K, which will, in feedback, give us the desiredclosed-loop poles.

We first need to decide where to place the closed-loop poles. Since we get to place all five of the closed-looppoles, we can be very selective about where they go. In particular, we can place them to cancel all of the plantzeros, as well as give us the desired response. First, we will find the plant zeros by converting the plant's digitalstate equations to a transfer function, and then finding the roots of the numerator. We will use the tfdatacommand which takes a system (sus_d) as its argument and outputs a transfer function numerator anddenominator. Since the suspension system (sus_d) has two inputs, only one input must be selected. Notice howthe first input is selected in the following code.

Add the following code to your m-file:

sus1 = sus_di*[1;0]; %select the first input[num,den] = tfdata(sus1,'v');z = roots(num)

MATLAB will return the following:

zeros = -0.9929 1.0000 0.9986 + 0.0065i 0.9986 - 0.0065i

We will select these three zeros as three of our desired closed-loop poles. One of the other two will be selectedat .9992 since a pole there settles in approximately 10000 samples (or 5 seconds). The last pole will beselected at z=.5 since this is sufficiently fast to be insignificant. Add the following code to your m-file:

p1 = z(1);p2 = z(3);p3 = z(4);p4 = .9992;p5 = .5;

K=place(Ad,Bd*[1;0],[p1 p2 p3 p4 p5])

MATLAB will return the following:

place: ndigits= 15

K =

1.0e+09 *

0.0534 0.0000 1.0898 0.0011 1.8286

Simulating the Closed-Loop Response

We can use the step command to simulate the closed-loop response. Since multiplying the state vector by K in

4

Page 302: Matlab Tutorial

our controller only returns a single signal, u, we need to add a row of zeros to K by multiplying it by [1 0]T.This is identical to what was done in the continuous design to compensate for the fact that there are two inputsto the plant, but only one is a control input. We will simulate with a negative .1m step disturbance in the roadto give us a positive deflection of the bus for aesthetic reasons. Enter the following code into your m-file:

sys_cl = ss(Ad-Bd*[1;0]*K,Bd,Cd,Dd,T);step(-.1*sys_cl*[0;1],5);

You should see the following plot.

We can see in this plot, that the overshoot is less than 5mm, and the response settles well within 5 seconds.

Digital Control ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | Pitch Controller |Ball and Beam

Bus Suspension ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space | DigitalControl | Simulink Basics | Simulink Modeling | Examples

5

Page 303: Matlab Tutorial

Digital Control Example: Inverted Pendulum usingState-Space method

Discrete state-spaceControllability and ObservabilityControl design via pole placementReference inputObserver design

In this digital control version of the inverted pendulum problem, we will use the state-space method todesign the digital controller. If you refer to the Inverted Pendulum Modeling page, the state-spaceequations were derived as

where

M mass of the cart 0.5 kgm mass of the pendulum 0.5 kgb friction of the cart 0.1 N/m/secl length to pendulum center of mass 0.3 mI inertia of the pendulum 0.006 kg*m^2u step force applied to the cartx cart position coordinatephi pendulum angle from vertical

Outputs are the cart displacement (x in meters) and the pendulum deflection angle (phi in radians).

The design requirements are

Settling time for x and phi less than 5 secondsRise time for x of less than 1 secondOvershoot of phi less than 0.35 rad (20 deg)Steady-state error of x and phi less than 2%

1

Page 304: Matlab Tutorial

Discrete state-space

The first thing to do here is to convert the above continuous state-space equations to discrete state-space. To do this, we are going to use the MATLAB function called c2d. To use this c2d, we need tospecify three arguments: state-space system, sampling time (Ts in sec/sample), and the 'method'. Youshould already be familiar with how to construct a state-space system from A, B, C, and D matrices.The sampling time should be smaller than 1/(30*BW) sec, where BW is the closed-loop bandwidthfrequency. The method we will use is the zero-order hold ('zoh').

Assuming that the closed-loop bandwidth frequencies are around 1 rad/sec for both the cart and thependulum, let the sampling time be 1/100 sec/sample. Now we are ready to use c2d. Enter thefollowing commands to an m-file.

M = .5;m = 0.2;b = 0.1;i = 0.006;g = 9.8;l = 0.3;

p = i*(M+m)+M*m*l^2; %denominator for the A and B matrices

A = [0 1 0 0; 0 -(i+m*l^2)*b/p (m^2*g*l^2)/p 0; 0 0 0 1; 0 -(m*l*b)/p m*g*l*(M+m)/p 0];

B = [ 0; (i+m*l^2)/p; 0; m*l/p]; C = [1 0 0 0; 0 0 1 0]; D = [0; 0]; Ts = 1/100;pend = ss(A,B,C,D);

pend_d = c2d(pend,Ts,'zoh')

Running this m-file in the MATLAB command window gives you the following four matrices.

a = x1 x2 x3 x4 x1 1 0.0099909 0.00013359 4.4532e-07 x2 0 0.99818 0.026717 0.00013359 x3 0 -2.2719e-05 1.0016 0.010005 x4 0 -0.0045437 0.31192 1.0016 b = u1 x1 9.0859e-05 x2 0.018167 x3 0.00022719 x4 0.045437

2

Page 305: Matlab Tutorial

c = x1 x2 x3 x4 y1 1 0 0 0 y2 0 0 1 0 d = u1 y1 0 y2 0 Sampling time: 0.01Discrete-time system.

Now we have obtained the discrete state-space model of the form

Controllability and Observability

The next step is to check the controllability and the observability of the system. For the system to becompletely state controllable, the controllability matrix

must have the rank of n. The rank of the matrix is the number of independent rows (or columns). Inthe same token, for the system to be completely state observable, the observability matrix

must also have the rank of n.

3

Page 306: Matlab Tutorial

Since our controllability matrix and observability matrix are '4x4', the rank of both matrices must be 4.The function rank can give you the rank of each matrix. In an new m-file, enter the followingcommands and run it in the command window.

F = [1.0000 0.0100 0.0001 0.0000; 0 0.9982 0.0267 0.0001; 0 0.0000 1.0016 0.0100; 0 -0.0045 0.3119 1.0016]; G = [0.0001 0.0182; 0.0002; 0.0454]; H = [1 0 0 0; 0 0 1 0]; J = [0; 0];

Ts = 1/100;pend_d = ss(F,G,H,J,Ts); co = ctrb(pend_d);ob = obsv(pend_d);

Controllability = rank(co)Observability = rank(ob)

In the command window, you should see

Controllability =

4 Observability = 4

This proves that our discrete system is both completely state controllable and completely stateobservable.

Control design via pole placement

The schematic of a full-state feedback system is shown below.

The next step is to assume that all four states are measurable, and find the control matrix (K). If yourefer to the continuous Inverted Pendulum: State-Space page, the Linear Quadratic Regulator(LQR) method was used to find the control matrix (K). In this digital version, we will use the same

4

Page 307: Matlab Tutorial

LQR method. This method allows you to find the optimal control matrix that results in some balancebetween system errors and control effort. Please consult your control textbook for details. To use thisLQR method, we need to find three parameters: Performance index matrix (R), state-cost matrix (Q),and weighting factors. For simplicity, we will choose the performance index matrix equal 1 (R=1), andthe state-cost matrix (Q) equals H' x H. The weighting factors will be chosen by trial and error. Thestate-cost matrix (Q) has the following structure

Q =1 0 0 0

0 0 0 0 0 0 1 0 0 0 0 0

The element in the 1,1 position will be used to weight the cart's position and the element in the 3,3position will be used to weight the pendulum's angle. The weighting factors for the cart's position andthe pendulum's angle will be chosen individually.

Now we are ready to find the control matrix (K) and see the response of the system. Enter thefollowing commands to an new m-file and run it in the MATLAB command window.

T = 0:0.01:5;U = 0.2*ones(size(T));

F = [1.0000 0.0100 0.0001 0.0000; 0 0.9982 0.0267 0.0001; 0 0.0000 1.0016 0.0100; 0 -0.0045 0.3119 1.0016]; G = [0.0001; 0.0182; 0.0002; 0.0454]; H = [1 0 0 0; 0 0 1 0]; J = [0; 0];

x = 1; %weighting factor for the cart positiony = 1; %weighting factor for the pendulum angle

Q = [x 0 0 0; 0 0 0 0; 0 0 y 0; 0 0 0 0];

R = 1;

K = dlqr(F,G,Q,R)Ts = 1/100;sys_cl = ss(F-G*K,G,H,J,Ts);

[Y,T,X] = lsim(sys_cl,U);stairs(T,Y)legend('Cart (x)','Pendulum (phi)')

You should see the following step response.

5

Page 308: Matlab Tutorial

The curve in green represents the pendulum's angle, in radians, and the curve in blue represents thecart's position in meters. The pendulum's and cart's overshoot appear fine, but their settling times needimprovement, and the cart's rise time needs to be decreased. Also the cart has, in fact, moved in theopposite direction. For now, we will concentrate on improving the settling times and the rise times,and fix the steady-state error later.

Let's increase the weighting factors (x and y) and see if both the settling and rise times decrease. Goback to your m-file and change the x and y to x=5000 and y=100. Running this m-file in the commandwindow gives you the following new step response.

From this plot, we see that all design requirements are satisfied except the steady-state error of thecart position (x). We can easily correct this by introducing a feedforward scaling factor (Nbar).

Reference input

6

Page 309: Matlab Tutorial

Unlike other design methods, the full-state feedback system does not compare the output to thereference; instead, it compares all states multiplied by the control matrix (K*x) to the reference (seethe schematic shown above). Thus, we should not expect to see the output equal to the input. Toobtain the desired output, we need to scale the reference input so that the output equals the reference.This can be easily done by introducing a feedforward scaling factor called Nbar. The basic schematicwith Nbar is shown below.

Unfortunately, we can not use our user-defined function rscale to find Nbar because it was defined forcontinuous-time single-output systems. But certainly we can find it by trial and error. After severaltrials, Nbar equals -61.55 provided a satisfactory response. Try the following m-file and obtain thestep response shown below.

T = 0:0.01:5;U = 0.2*ones(size(T));

F = [1.0000 0.0100 0.0001 0.0000; 0 0.9982 0.0267 0.0001; 0 0.0000 1.0016 0.0100; 0 -0.0045 0.3119 1.0016]; G = [0.0001; 0.0182; 0.0002; 0.0454]; H = [1 0 0 0; 0 0 1 0]; J = [0; 0];

x = 5000; %weighting factor for the cart positiony = 100; %weighting factor for the pendulum angle

Q = [x 0 0 0; 0 0 0 0; 0 0 y 0; 0 0 0 0];

R = 1;

K = dlqr(F,G,Q,R) Nbar = -61.55;Ts = 1/100;sys_cl = ss(F-G*K,G*Nbar,H,J,Ts);[Y,T,X] = lsim(sys_cl,U);stairs(T,Y)legend('Cart (x)','Pendulum (phi)')

7

Page 310: Matlab Tutorial

Notice that the steady-state error of the cart's position have been eliminated. Now we have designed asystem that satisfies all design requirements.

Observer design

The above response satisfies all design requirements; however, it was found assuming all states aremeasurable. This assumption may not be valid for all systems. In this section, we develop a techniquefor estimating the states of a plant from the information that is available concerning the plant. Thesystem that estimates the states of another system is called an observer. Thus, in this section we willdesign a full-order state observer to estimate those states that are not measurable. For furtherexplanation on how an observer works, please consult your control textbook.

A basic schematic of the plant-observer system is shown below.

8

Page 311: Matlab Tutorial

To design the observer, first, we need to find the L matrix. To find the L matrix, we need to find thepoles of the system without the observer (the poles of F-G*K). Copy the following commands to anew m-file and run it in the MATLAB command window.

F = [1.0000 0.0100 0.0001 0.0000; 0 0.9982 0.0267 0.0001;

0 0.0000 1.0016 0.0100; 0 -0.0045 0.3119 1.0016];

G = [0.0001; 0.0182; 0.0002; 0.0454]; H = [1 0 0 0; 0 0 1 0]; J = [0; 0];

x = 5000; %weighting factor for the cart positiony = 100; %weighting factor for the pendulum angle

Q = [x 0 0 0; 0 0 0 0; 0 0 y 0; 0 0 0 0];

R = 1;

K = dlqr(F,G,Q,R);

poles = eig (F-G*K)

9

Page 312: Matlab Tutorial

In the command window, you should see

poles =

0.9156 + 0.0729i 0.9156 - 0.0729i 0.9535 + 0.0079i 0.9535 - 0.0079i

We want to place observer poles so that the observer dynamics are a lot faster than the system withoutthe observer. Let's place the observer poles far left of above poles, say, at [-0.3 -0.31 -0.32 -0.33].These poles can be changed later, if necessary. We will use the MATLAB function place to find the Lmatrix. Enter the following commands to an new m-file and run it.

F = [1.0000 0.0100 0.0001 0.0000; 0 0.9982 0.0267 0.0001;

0 0.0000 1.0016 0.0100; 0 -0.0045 0.3119 1.0016];

H = [1 0 0 0; 0 0 1 0];

P = [-0.3 -0.31 -0.32 -0.33];

L = place (F',H',P)'

You should see the following L matrix in the command window.

L =

2.6310 -0.0105 172.8146 -1.3468 -0.0129 2.6304 -2.2954 173.2787

Now we will obtain the overall system response including the observer. Once again, create a newm-file and copy the following code.

T = 0:0.01:5;U = 0.2*ones(size(T));

F = [1.0000 0.0100 0.0001 0.0000; 0 0.9982 0.0267 0.0001; 0 0.0000 1.0016 0.0100; 0 -0.0045 0.3119 1.0016]; G = [0.0001; 0.0182; 0.0002; 0.0454]; H = [1 0 0 0; 0 0 1 0]; J = [0; 0]; x = 5000; %weighting factor for the cart positiony = 100; %weighting factor for the pendulum angle

Q = [x 0 0 0;

10

Page 313: Matlab Tutorial

0 0 0 0; 0 0 y 0; 0 0 0 0];

R = 1;

K = dlqr(F,G,Q,R)

Nbar = -61.55;

L = [2.6310 -0.0105; 172.8146 -1.3468; -0.0129 2.6304; -2.2954 173.2787];

Fce = [F-G*K G*K; zeros(size(F)) (F-L*H)]; Gce = [G*Nbar; zeros(size(G))]; Hce = [H zeros(size(H))];

Jce = [0;0];

Ts = 1/100;sys_cl = ss(Fce,Gce,Hce,Jce,Ts);

[Y,T,X] = lsim(sys_cl,U);

stairs(T,Y)legend('cart (x)','pendulum (phi)')

After running this m-file, you should get the following step response.

As you noticed, this response is identical to the as previous one since observer knows the plant exactlyand has the same initial condition.

Digital Control Examples

11

Page 314: Matlab Tutorial

Cruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball & Beam

Inverted Pendulum ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

12

Page 315: Matlab Tutorial

Digital Control Example: Designing PitchController using State-Space method

Discrete state-spaceControllability and observabilityControl design via pole placementReference input

In this digital control version of the pitch controller problem, we will use the state-space method todesign the digital controller. If you refer to the Pitch Controller: Modeling page, the state-space modelwas derived as

The input (elevator deflection angle, delta e) will be 0.2 rad (11 degrees), and the output is the pitchangle (theta).

The design requirements are

Overshoot: Less than 10%Rise time: Less than 2 secondsSettling time: Less than 10 secondsSteady-state error: Less than 2%

Discrete state-space

The first thing to do here is to convert the continuous state-space model to discrete state-space. To dothis, we will use the MATLAB function c2d. To use c2d, we need to specify three arguments:state-space system, sampling time (Ts), and the 'method'. You should already be familiar with how toconstruct a system from A, B, C, and D matrices. The sampling time should be smaller than1/(30*BW), where BW is the closed-loop bandwidth frequency. The method we will use is thezero-order hold.

From the closed-loop Bode plot, the bandwidth frequency was determined to be approximately 2

1

Page 316: Matlab Tutorial

rad/sec (see this yourself) . Thus, to be sure we have a small enough sampling time, we will use thesampling time of 1/100 sec/sample. Now we are ready to use the function c2d. Enter the followingcommands in an m-file.

A = [-0.313 56.7 0; -0.0139 -0.426 0; 0 56.7 0];B = [0.232; 0.0203; 0]; C = [0 0 1];D = [0];

pitch = ss(A,B,C,D);

Ts=1/100;pitch_d = c2d(pitch,Ts,'zoh')

Running this m-file in the MATLAB command window gives you the following four matrices.

a = x1 x2 x3 x1 0.99684 0.5649 0 x2 -0.00013849 0.99571 0 x3 -3.9309e-05 0.56579 1 b = u1 x1 0.0023738 x2 0.0002024 x3 5.7438e-05 c = x1 x2 x3 y1 0 0 1 d = u1 y1 0 Sampling time: 0.01Discrete-time system.

Now we have obtained the discrete state-space model of the form

2

Page 317: Matlab Tutorial

Controllability and observability

The next step is to check the controllability and the observability of the system. For the system to becompletely state controllable, the controllability matrix

must have the rank of n. The rank of the matrix is the number of independent rows (or columns). Inthe same token, for the system to be completely state observable, the observability matrix

must also have the rank of n. Since our controllability matrix and observability matrix are 3x3, therank of both matrices must be 3. The MATLAB function rank can give you the rank of each matrices.In an new m-file, enter the following commands and run it.

F = [0.9968 0.05649 0 -0.0001 0.9957 0 0 0.5658 1];G = [0.0024; 0.0002; 0.0001];H = [0 0 1];J = [0];

Ts = 1/100;pitch_d = ss(F,G,H,J,Ts);

co = ctrb(pitch_d);ob = obsv(pitch_d);

Controllability = rank(co)Observability = rank(ob)

In the command window, you should see

3

Page 318: Matlab Tutorial

Controllability =

3

Observability =

3

This proves that our discrete system is both completely state controllable and completely stateobservable.

Control design via pole placement

The schematic of a full-state feedback system is shown below.

where

K=Control matrixx=State matrix (alpha, q, theta)de=-Kx=inputR=Reference

In the continuous Pitch Controller: State-Space page, the Linear Quadratic Regulator (LQR)method was used to find the control matrix (K). In this digital version, we will use the same LQRmethod. This method allows you to find the optimal control matrix that results in some balancebetween system errors and control effort. Please consult your control textbook for details. To use thisLQR method, we need to find three parameters: Performance index matrix (R), state-cost matrix (Q),and weighting factor (p). For simplicity, we will choose the performance index matrix equals 1 (R=1),and the state-cost matrix (Q) equals to H' x H. The weighting factor (p) will be chosen by trial anderrors. The state-cost matrix (Q) has the following structure

Q =

0 0 00 0 00 0 1

Now we are ready to find the control matrix (K) and see the response of the system. First, let theweighting factor (p) equal 50. Enter the following commands into a new m-file and run it in theMATLAB command window.

t = 0:0.01:10;de = 0.2*ones(size(t));

F = [0.9968 0.05649 0 -0.0001 0.9957 0 0 0.5658 1];

4

Page 319: Matlab Tutorial

G = [0.0024; 0.0002; 0.0001];H = [0 0 1];J = [0];

p = 50;Q = [0 0 0 0 0 0 0 0 p]; [K] = dlqr(F,G,Q,1)

Ts = 1/100;sys_cl = ss(F-G*K,G,H,J,Ts);

[Y,T] = lsim(sys_cl,de);stairs(T,Y)

After you run this m-file, you should see the control matrix (K) in the command window and the stepresponse similar to the one shown below.

The rise time, the overshoot, and the settling time look satisfactory. However, there is a largesteady-state error. This can be easily corrected by introducing the feedforwarding scaling factor(Nbar).

Reference input

Unlike other design methods, the full-state feedback system does not compare the output to thereference; instead, it compares all states multiplied by the control matrix (K*x) to the reference (seethe schematic shown above). Thus, we should not expect to see the output equals to the input. Toobtain the desired output, we need to scale the reference input so that the output equals to thereference. This can be easily done by introducing a feedforwarding scaling factor called Nbar. Thebasic schematic with the Nbar is shown below.

5

Page 320: Matlab Tutorial

Unfortunately, we can not use our user-defined function rscale to find Nbar because it is defined forcontinuous systems. But we can find it by trial and error. After several trials, Nbar equals 6.95provided a satisfactory response. Try the following m-file and obtain the stairstep response shownbelow.

t = 0:0.01:10;de = 0.2*ones(size(t));

F = [0.9968 0.05649 0 -0.0001 0.9957 0 0 0.5658 1];G = [0.0024; 0.0002; 0.0001];H = [0 0 1];J = [0];

p=50;Q = [0 0 0 0 0 0 0 0 p]; [K,S,E] = dlqr(F,G,Q,1)

Nbar = 6.95;Ts = 1/100;sys_cl = ss(F-G*K,G*Nbar,H,J,Ts);

[x] = lsim(sys_cl,de);stairs(t,x)

From this plot, we see that the Nbar factor eliminates the steady-state error. Now all designrequirements are satisfied.

6

Page 321: Matlab Tutorial

Note: Assuming all states are measurable, an observer design will not be explainedhere.

Digital Control ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Pitch Control ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

7

Page 322: Matlab Tutorial

Digital Control Example: Ball and Beam problemusing PID Control

Digital PID controllerDiscrete transfer functionOpen-loop responseProportional controlProportional-Derivative control

In this digital control version of the ball and beam experiment, we are going to use the PID controlmethod to design the digital controller. If you refer to the Ball and Beam Modeling page, theopen-loop transfer function was derived as

m mass of the ball 0.11 kgg gravitational acceleration 9.8 m/s^2d lever arm offset 0.03 mL length of the beam 1.0 mR radius of the ball 0.015 mJ ball's moment of inertia 9.99e-6 kgm^2R(s) ball position coordinate (m)theta(s) servo gear angle 0.25 rad

The design criteria for this problem are:

Settling time less than 3 secondsOvershoot less than 5%

Digital PID controller

If you refer to any of the PID control problem for continuous systems, the PID transfer function wasexpressed as

As you noticed the above transfer function was written in terms of s. For the digital PID control, weuse the following transfer function in terms of z.

1

Page 323: Matlab Tutorial

Discrete transfer function

The first thing to do here is to convert the above continuous system transfer function to an equivalentdiscrete transfer function. To do this, we will use the MATLAB function c2d. To use c2d, we need tospecify three arguments: system, sampling time (Ts), and the 'method'. You should already be familiarwith how to create a system from numerator and denominator matrices. The sampling time should besmaller than 1/(30*BW) sec, where BW is the closed-loop bandwidth frequency. The method we willuse is the zero-order hold ('zoh'). Assuming that the closed-loop bandwidth frequency is around 1rad/sec, let the sampling time be 1/50 sec/sample. Now we are ready to use c2d. Enter the followingcommands to an m-file.

m = 0.111;R = 0.015;g = -9.8;L = 1.0;d = 0.03;J = 9.99e-6;

K = (m*g*d)/(L*(J/R^2+m)); %simplifies input

num = [-K];den = [1 0 0];ball = tf(num,den);

Ts = 1/50;ball_d = c2d(ball,Ts,'zoh')

Running this m-file in the MATLAB command window gives you the following matrices.

Transfer function:4.2e-05 z + 4.2e-05------------------- z^2 - 2 z + 1 Sampling time: 0.02

Open-loop response

Now we will observe the ball's response to a step input of 0.25 m. To do this, enter the followingcommands into a new m-file and run it in the command window. You should see the followingresponse.

numDz = 0.0001*[0.42 0.42];denDz = [1 -2 1];Ts = 1/50;ball_d = tf(numDz,denDz,Ts);

[x,t] = step(0.25*ball_d,5);stairs(t,x)

2

Page 324: Matlab Tutorial

From this plot, it is clear that the open-loop system is unstable causing the ball to roll off the end ofthe beam.

Proportional Control

Now we will add proportional control (Kp) to the system and obtain the closed-loop system response.For now let Kp equal 100 and see what happens to the response. Enter the following commands into anew m-file and run it in the command window.

numDz = 0.0001*[0.42 0.42];denDz = [1 -2 1];Ts = 1/50;ball_d = tf(numDz,denDz,Ts);

Kp=100;sys_cl = feedback(Kp*ball_d,1);

[x,t] = step(0.25*sys_cl,5);stairs(t,x)

As you can see, the addition of proportional control does not make the system stable. You may try toincrease the proportional gain (Kp) and confirm that the system remains unstable.

Proportional-Derivative control

Now we will add a derivative term to the controller. Keep the proportional gain (Kp) equal to 100, andlet the derivative gain (Kd) equal to 10. Copy the following code to an new m-file and run it to viewthe system response.

numDz = 0.0001*[0.42 0.42];denDz = [1 -2 1];Ts = 1/50;ball_d = tf(numDz,denDz,Ts);

Kp=100;Kd=10;

numpd = [Kp+Kd -(Kp+2*Kd) Kd];

3

Page 325: Matlab Tutorial

denpd = [1 1 0];contr = tf(numpd,denpd,Ts);

sys_cl = feedback(contr*ball_d,1);

[x,t] = step(0.25*sys_cl,5);stairs(t,x)

Now the system is stable, but the rise time is too long. From the PID Tutorial page, we see that theincreasing the proportional gain (Kp) will decrease the rise time. Let's increase the proportional gain(Kp) to 1000 and see what happens. Change Kp in the above m-file from 100 to 1000 and rerun it inthe command window. You should see the following step response.

As you can see, all of the design requirements are satisfied. For this particular problem, noimplementation of an integral control was needed. But remember there is more than one solution for acontrol problem. For practice, you may try different P, I and D combinations to obtain a satisfactoryresponse.

Digital Control ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Ball & Beam ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency Response | StateSpace | Digital Control | Simulink Basics | Simulink Modeling | Examples

4

Page 326: Matlab Tutorial

Simulink Cơ sởBắt đầu với SimulinkCác File mô hìnhCác phần tử cơ bảnChạy mô phỏngXây dựng hệ thống

Simulink là phần mở rộng của MATLAB dùng để mô hình hoá và mô phỏng hệ thống. Trong Simulink,hệ thống được vẽ dưới dạng sơ đồ các block. Có rất nhiều phần tử cơ bản trong sơ đồ block đượcdùng như các hàm truyền, summing junctions, v.v., cùng với các thiết bị vào-ra ảo như các bộ tạo hàmvà osilo. Simulink được tích hợp trong MATLAB và dữ liệu được truyền qua lại dễ dàng giữa cácchương trình. Trong phần tutor này, chúng ta áp dụng Simulink cho các ví dụ trong phần mô hình cáchệ thống, xây dựng các bộ điều khiển và mô phỏng hệ thống đó. Simulink được hỗ trợ trên môi trườngUnix, Macintosh, và Windows; và gồm cả phiên bản cho sinh viên chạy trên máy tính cá nhân. Để biếtthêm thông tin về Simulink, xin liên hệ với MathWorks.

Ý tưởng đằng sau phần tutorial này là bạn có thể xem xét mọi thứ trong 1 cửa sổ riêngtrong khi chương trình Simulink đang được chạy trong 1 cửa sổ khác. Các file mô hìnhcủa hệ thống ta có thể download dễ dàng từ phần tutorial và mở chúng trong phần mềmSimulink. Bạn có thể chỉnh sửa hoặc mở rộng hệ thống đó trong quá trình học sử dụngSimulink để mô hình hóa hệ thống, điều khiển, và mô phỏng. Bạn không được làm lộnxộn các cửa sổ, biểu tượng và các menu trong cửa sổ thực hiện Simulink. Các hình ảnhtrong phần tutorial là ảnh cắt chèn - chúng chỉ đơn giản cho bạn thấy những gì sẽ có đượctrong cửa sổ làm việc của Simulink. Tất cả các thao tác về Simulink sẽ được thực hiệntrong cửa sổ Simulink.

Bắt đầu với Simulink

Simulink được khởi động trong MATLAB bằng cách đánh lệnh sau trong cửa sổ lệnh:

simulink

Với lựa chọn khác, bạn có thể nhấn và nút New Simulink Model trong cửa sổ lệnh của MATLAB nhưsau:

1

Page 327: Matlab Tutorial

Khi bắt đầu, Simulink đem đến hai cửa sổ. Đầu tiên là cửa sổ main Simulink, như sau:

Cửa sổ thứ hai là phần trống, không có đề mục và là cửa sổ mô hình. Đây là cửa sổ ta dùng để vẽ môhình hệ thống.

Các File mô hình

Trong Simulink, một mô hình là 1 sự tổ hợp các block biểu diễn cho 1 hệ thống. Hơn nữa, để vẽ cácmô hình trong cửa sổ trống ta có thể mở các file mô hình lưu trước đó từ menu File trong cửa sổ lệnhcủa MATLAB. Ví dụ, ta download file mô hình sau bằng cách nhấn vào liên kết sau và lưu file đó trongthư mục chạy chương trình MATLAB.

simple.mdl

Mở file này trong Simulink bằng các lệnh sau trong cửa sổ lệnh của MATLAB. (Theo cách khác, ta cóthể mở file này bằng cách dùng chức năng Open trong menu File, hoặc ấn Ctrl+O trong Simulink.)

simple

Cửa sổ mô hình sau sẽ xuất hiện.

2

Page 328: Matlab Tutorial

Mô hình mới có thể được tạo ra bằng cách chọn New từ menu File trong bất cứ cửa sổ Simulink nào(hoặc ấn Ctrl+N).

Các phần tử cơ bản

Có 2 lớp item chính trong Simulink: khối và đường nối. Các khối được dùng để phát, điều chế, tổhợp, xuất ra và hiển thị các tín hiệu. Các đường nối được dùng để truyền tín hiệu giữa các khối vớinhau.

Các khối

Có một số lớp các khối tổng quát như sau:

Các khối nguồn tín hiệu: Dùng để phát các tín hiệu khác nhauCác khối Sink: Dùng để xuất tín hiệu hoặc hiển thịCác khối rời rạc: Các phần tử tuyến tính, rời rạc về thời gian trong hệ thống (các hàm truyền,mô hình không gian trạng thái, v.v..)Các khối tuyến tính: Các khối và các liên kết tuyến tính, liên tục về thời gian (summingjunctions, các hệ số, v.v..)Các khối phi tuyến: Các toán tử phi tuyến (các hàm ngẫu nhiên, tập trung, trễ, v.v..)Các khối liên kết: Multiplex, Demultiplex, các Macro hệ thống, v.v..

Các block có các điểm giữa đối với các điểm đầu vào và điểm đầu ra. Các điểm đầu vào để ngỏ đượcbiểu diễn bằng hình tam giác nhỏ hở. Đầu ra để ngỏ được biểu diễn bởi hình tam giác nhỏ. Hình khốisau có 1 đầu vào để ngỏ bên trái và 1 đầu ra để ngỏ bên phải.

Các đường nối

Các đường nối truyền tín hiệu theo hướng mũi tên. Các đường nối luôn luôn truyền tín hiệu từ đầu racủa khối này đến đầu vào của khối khác. Trong 1 số trường hợp 1 đường có thể được chia nhánh từđường khác, và tín hiệu được truyền tới cả hai khối đích, như sau (kích vào hình minh hoạ đểdownload file mô hình split.mdl).

Các đường thì không bao giờ truyền tín hiệu vào đường khác; các đường nối phải được kết hợp thôngqua cách dùng các khối ví dụ như summing junction.

Một tín hiệu có thể là vô hướng hoặc dạng vecto. Với các hệ thống Single-Input, Single-Output(SISO),

3

Page 329: Matlab Tutorial

tín hiệu vô hướng thường xuyên được sử dụng. Với các hệ thống Multi-Input, Multi-Output(MIMO),tín hiệu dạng vecto lại hay dùng, và chính là bao gồm 2 hoặc hơn 2 tín hiệu vô hướng. Các đường nốidùng để truyền tín hiệu vô hướng và tín hiệu dạng vecto là đồng nhất. Dạng tín hiệu trên 1 đường nốiđược xác định bởi các khối ở hai điểm đầu và cuối của đường nối đó.

Ví dụ đơn giản

Mô hình đơn giản trên (lấy từ phần file mô hình ) bao gồm ba khối: Step, Hàm truyền, và Scope. Steplà khối nguồn mà từ đó 1 xung đầu vào step được tạo ra. Tín hiệu này được truyền qua đường nốitheo hướng mũi tên đến hàm truyền là 1 khối tuyến tính. Hàm truyền này nhận tín hiệu đầu vào vàcho ra tín hiệu đầu ra mới đến Scope. Scope là 1 sink block dùng đển biểu diễn 1 tín hiệu nào đógiống như osilo.

Có rất nhiều kiểu khối trong Simulink, chúgng sẽ được bàn đến sau. Ngay bây giờ, chúng ta chỉ khảosát 3 khối mà ta dùng trong mô hình trên.

Điều chỉnh các khối

Một khối có thể được điều chỉnh bằng cách kích đúp lên nó. Ví dụ, nếu kích đúp lên khối "hàmtruyền" trong mô hình đơn giản trên, bạn sẽ thấy hộp thoại như sau.

Hộp thoại bao gồm các trường cho tử số và mẫu số của khối hàm truyền. Bằng cách nhập vào các hệsố mong muốn của đa thức tử số và mẫu số, ta sẽ có hàm truyền như mong muốn. Ví dụ, để thay đổimẫu số thành s^2+2s+1, ta nhập giá trị cho các trường của mẫu số như sau:

[1 2 1]

và kích vào nút close, cửa sổ mô hình sẽ thay đổi như dưới đây ,

4

Page 330: Matlab Tutorial

và điều này ảnh hưởng đến mẫu số của hàm truyền.

Khối "step" cũng có thể được kích đúp cho phép ta thay đổi thông qua hộp thoại sau.

Các giá trị tham số mặc định trong hộp thoại này cho ra 1 hàm step tại thời điểm 1 giây, có giá trị thayđổi từ mức 0 đến mức 1. (nói cách khác là một step đơn vị tại thời điểm t=1). Mỗi tham số có thể thayđổi được. Nhớ đóng hộp thoại trước khi tiếp tục.

Khối phức tạp nhất trong ba khối chính là khối "Scope". Kích đúp chuột để có màn hình osilo trống.

Khi một lần mô phỏng được thực hiện, tín hiệu nào cung cấp cho scope sẽ được biểu diễn trong cửa sổnày. Các thao tác chi tiết của scope sẽ không được bàn nhiều trong phần này. Ta chỉ dùng 1 hàm duynhất đó là nút autoscale, biểu tượng của nó giống như 1 cặp ống nhòm trong phần phía trên của cửasổ.

Chạy mô phỏng

5

Page 331: Matlab Tutorial

Để chạy mô phỏng, ta sẽ làm việc với file mô hình sau:

simple2.mdl

Download và mở file này trong Simulink theo hướng dẫn đã nêu. Ta sẽ có cửa sổ mô hình như sau.

Trước khi chạy mô phỏng cho 1 mô hình, trước tiên ta mở cửa sổ scope bằng cách kích đúp vào khốiscope. Sau đó để khởi động mô phỏng có thể nhấn nút Start trong menu Simulation (như bên dưới)hoặc ấn Ctrl-T trong cửa sổ mô hình.

Mô phỏng sẽ chạy rất nhanh và cho ra cửa sổ scope như dưới đây.

Chú ý là đầu ra của mô phỏng (có màu vàng) ở mức rất thấp so với các trục toạ độ của scope. Đểchỉnh lại, ấn nút autoscale (hình cặp ống nhòm), nó sẽ chỉnh lại tỉ lệ các trục toạ độ như sau.

6

Page 332: Matlab Tutorial

Chú ý rằng đáp ứng đơn vị chưa được bắt đầu cho đến khi t=1. Ta có thể điều chỉnh được bằng cáchkích đúp vào khối "step". Bây giờ ta sẽ thay đổi các tham số cho hệ thống và mô phỏng lại lần nữa.Kích đúp lên khối "Hàm truyền" trong cửa sổ mô hình và thay mẫu số thành

[1 20 400]

Chạy mô phỏng lại (ấn Ctrl-T) và bạn sẽ thấy những gì xuất hiện chỉ là 1 đường bằng phẳng trên cửasổ scope. Ấn nút autoscale, và bạn sẽ thấy cửa sổ scope như sau.

Nhớ rằng nút autoscale chỉ thay đổi trục tung. Vì hàm truyền này có đáp ứng rất nhanh, nó được dồnvào 1 khoảng rất hẹp trong cửa sổ scope. Điều này không có vấn đề gì đối với scope, nhưng với chínhbản thân mô phỏng thì có. Simulink đã mô phỏng hệ thống trong 10 giây mặc dù hệ thống đã đạt trạngthái ổn định chỉ sau khoảng 1 giây.

Để sửa lại, bạn phải thay đổi lại các tham số của chính bản thân mô phỏng. Trong cửa sổ mô hình,chọn Parameters từ menu Simulation. Bạn sẽ thấy hộp thoại sau.

7

Page 333: Matlab Tutorial

Có rất nhiều mục lựa chọn cho tham số; chúng ta chỉ quan tâm tới thời gian bắt đầu và kết thúc, điềunày sẽ cho Simulink thực thi mô phỏng trong khoảng thời gian nào. Thay đổi Start time từ 0.0 thành0.8 (vì xung step chưa xuất hiện đến khi t=1.0). Thay đổi Stop time từ 10.0 thành 2.0, gần ngay saukhi hệ thống ổn định. Đóng cửa sổ này lại và chạy mô phỏng lại. Sau khi ấn nút autoscale, cửa sổscope sẽ cho ta biểu diễn đáp ứng đơn vị tốt hơn như sau.

Xây dựng hệ thống

Trong phần này, bạn sẽ học cách xây dựng hệ thống trong Simulink bằng cách dùng các khối trong Thư viện khối của Simulink. Ta sẽ xây dựng hệ thống sau.

8

Page 334: Matlab Tutorial

Nếu bạn muốn download mô hình hoàn chỉnh, nhấn vào đây.

Trước tiên bạn phải tập hợp được tất cả các khối cần thiết từ thư viện các khối. Sau đó phải chỉnh lạicác khối cho tương ứng với các khối trong mô hình như mong muốn. Cuối cùng, bạn sẽ kết nối cáckhối bằng các đường nối để tạo nên 1 hệ thống hoàn chỉnh. Sau bước này, bạn sẽ mô phỏng hệ thốngđể kiểm nghiệm lại xem nó hoạt động ra sao.

Tập hợp các khối

Thực hiện các bước như sau để chọn các khối cần thiết:

Tạo một mô hình mới (New từ menu File hoặc Ctrl-N). Bạn sẽ có cửa sổ mô hình trống.

Kích đúp vào biểu tượng Sources trong cửa sổ chính của Simulink.

9

Page 335: Matlab Tutorial

Thao tác này sẽ cho ta cửa sổ Sources chứa các thư viện Source. Các khối Source được dùng đểphát tín hiệu. Để biết thêm về thư viện các khối Kích vào đây.

Kéo khối Step trong cửa sổ sources đặt vào phía bên trái của cửa sổ mô hình.

Kích đúp vào biểu tượng Linear trong cửa sổ chính của Simulink để mở cửa sổ thư viện LinearBlock Library.Kéo các khối Sum, Gain, và 2 khối Hàm Truyền (kéo 2 lần) vào cửa sổ mô hình và sắp xếp gầnđược như sau. Sự sắp xếp chính xác không cần thiết lắm vì sau này ta sẽ chỉnh lại. Chỉ cần xácđinh đúng vị trí tương đối của các khối. Chú ý là hàm truyền thứ hai có số 1 ở sau tên của nó. Vìhai khối không thể có cùng 1 tên, nên Simulink tự động thêm các chữ số vào sau tên của cáckhối để phân biệt chúng với nhau.

10

Page 336: Matlab Tutorial

Kích đúp vào biểu tượng Sinks trong cửa sổ chính của Simulink để mở cửa sổ các Sink.Kéo khối Scope vào phía bên phải của cửa sổ mô hình.

Chỉnh lại các khối

Tiến hành các bước sau để chỉnh lại các khối trong mô hình.

Kích đúp vào khối Sum. Vì ta muốn đầu vào thứ 2 là phép trừ, nhập +- vào danh sách cáctrường dấu. Đóng hộp thoại lại.Kích đúp vào khối Gain block. Thay hệ số tỉ lệ thành 2.5 và đóng hộp thoại lại.Kích đúp vào Hàm truyền gần bên trái nhất. Thay đổi tử thành [1 2] và mẫu thành [1 0]. Đónghộp thoại lại.Kích đúp vào Hàm truyền gần bên phải nhất. Giữ nguyên tử là [1], Nhưng thay mẫu thành [1 24]. Đóng hộp thoại lại. Mô hình của ta sẽ có dạng sau:

11

Page 337: Matlab Tutorial

Thay tên của hàm truyền thứ nhất bằng cách kích vào chữ "Transfer Fcn". Một hộp và dấu nhắcsẽ xuất hiện trên tên của khối như sau. Dùng bàn phím (dùng chuột vẫn hữu ích) để xoá tên hiệntại và nhập tên mới cho vào là "PI Controller". Kích vào bất cứ đâu bên ngoài hộp tên để hoàntất.

Tương tự, ta thay tên của hàm truyền thứ hai từ "Transfer Fcn1" thành "Plant". Bây giờ, tất cáckhối đều được có tên thích hợp. Mô hình của ta sẽ như sau:

Kết nối các khối bằng các đường

Bây giờ các khối đã được bố trí thích hợp, ta sẽ liên kết chúng với nhau. Tiến hành theo các bước sau.

Kéo chuột từ đầu ra của khối Step đến đầu vào phía trên (dương) của khối Sum. Thả chuột khinào đã nhấp đúng vào điểm đầu vào. Không nên quan tâm đến dạng của đường nối khi đang vẽ,

12

Page 338: Matlab Tutorial

đường nối sẽ tự động chạy. Bạn sẽ thấy như sau.

Kết quả làđường nối sẽ có 1 mũi tên tô đậm ở đầu. Nếu mũi tên là hở, như dưới đây, thì có nghĩa là nókhông nối tới đâu cả.

Bạn có thểtiếp tục với đường nối không hoàn thiện đó bằng cách coi như mũi tên hở là một điểm đầu ra vàlại vẽ lại như ban nãy. Tiếp nữa, nếu bạn muốn vẽ lại đường nối hoặc đường nối liên kết sai, bạnnên xoá nó đi và vẽ lại nó. Để xoá 1 đường (hay bất cứ đối tượng nào), kích chuột chọn chúngsau đó nhấn phím delete.Kéo một đường nối từ đầu ra khối Sum đến đầu vào khối Gain. Cũng vẽ tiếp 1 đường từ khốiGain đến bộ điều khiển PI, 1 đường từ bộ điều khiển PI đến khối Plant, và 1 đường từ khối chấphành tới Scope. Bạn sẽ có như sau.

Đường nối còn lại cần vẽ là tín hiệu phản hồi từ đầu ra của khối Plant về đầu vào âm của khốiSum. Đường nối này sẽ khác bởi hai lý lẽ. Thứ nhất, vì đường này đi vòng và không đi theođường ngắn nhất (góc vuông) nên nó được vẽ qua 1 số giai đoạn. Thứ hai, vì không có điểm

13

Page 339: Matlab Tutorial

output để bắt đầu nên đường này phải bám vào 1 đường nào có sẵn.

Để bám vào 1 đường output, giữ Ctrl trong khi kéo chuột từ điểm mong muốn trên đường cósẵn. Trong trường hợp này, ta bắt đầu từ bên phải của khối Plant. Kéo đến góc trái phía dướccủa đường tín hiệu phản hồi như hình sau.

Bây giờ mũitên hở của đường nối được coi như là 1 điểm output. Vẽ 1 đường từ nó tới điểm âm của khốiSum như thông thường.

Bây giờ bạn có thể căn chỉnh lại các khối cho gọn gàng hơn. Khi sắp xếp lại, vị trí của các khốikhông là vấn đề lắm, nhưng rõ ràng là sẽ dễ đọc hơn khi chúng được sắp hàng lại. Để di chuyểnmỗi khối, kéo nó bằng chuột. Các đường sẽ vẫn giữ liên kết và tự nối lại. Các đoạn giữa và góccủa các đường có thể được kéo đến vị trí khác. Bắt đầu từ bên trái, kéo từng khối 1 sao chođường nối nằm thẳng ngang. Cũng lúc đó cũng điều chỉnh luôn khoảng cách giữa các khối 1cách hợp lý để có chỗ cho các nhãn tín hiệu. Bạn sẽ có như sau:

14

Page 340: Matlab Tutorial

Cuối cùng, bạn sẽ đặt các nhãn để xác định các tín hiệu tương ứng. Để đặt 1 nhãn ở bất cứ đâutrong mô hình, kich đúp vào điểm bạn muốn đặt nhãn. Ta bắt đầu bằng cách kích đúp vàođường dẫn từ khối Step. Bạn sẽ có một hộp văn bản trống với dâu nhắc như dưới đây.

Đánh r vàođó là ta đã đặt nhán cho tín hiệu reference sau đó kích ra ngoài để kết thúc.Đặt nhãn cho tín hiệu sai số (e), tín hiệu điều khiển (u), và tín hiệu đầu ra (y) như thông thường.Mô hình cuối cùng của ta sẽ có dạng như sau:

Để lưu lại mô hình, chọn Save As trong menu File và đánh tên theo ý bạn. Mô hình hoàn chỉnhsẽ có khi kích vào đây.

Mô phỏng

Bây giờ mô hình đã hoàn thiện, bạn có thể cho chạy mô phỏng nó. Chọn Start từ menu Simulation đểchạy. Kích đúp vào khối Scope để xem tín hiệu output. Nhấn vào nút autoscale (hình ống nhòm) và

15

Page 341: Matlab Tutorial

bạn sẽ thấy như sau.

Lấy biến từ Matlab

Trong một số trường hợp, các tham số như hệ số chẳng hạn, có thể được tính toán trong MATLAB sauđó sử dụng trong 1 mô hình Simulink. Nếu có trường hợp này thì ta không cần thiết phải nhập trực tiếpkết quả tính toán từ MATLAB vào Simulink. Ví dụ, giả sử ta tính toán hệ số thông qua biến K trongMatlab. Đưa biến ra bằng cách thực hiện lệnh sau trong cửa sổ lệnh của MATLAB.

K=2.5

Biến này có thể được dùng trong khối Gain của Simulink. Trong mô hình Simulink của bạn, kích đúpchuột vào khối Gain và nhập K vào trường Gain.

K

Đóng hộp thoại lại. Chú ý rằng khối Gain trong mô hình Simulink sẽ biểu diễn K chứ không phải là 1con số.

16

Page 342: Matlab Tutorial

Bây giờ bạn chạy mô phỏng lại và xem tín hiệu output trên Scope. Kết quả sẽ như sau.

Bây giờ nếu bất cứ 1 phép tính nào được thực hiện trong MATLAB làm thay đổi giá trị của biến trongmô hình Simulink thì bộ mô phỏng sẽ dùng các giá trị mới này để chạy. Để thử điều này, trongMATLAB, thay giá trị của K bằng cách đánh lệnh sau.

K=5

Khởi động mô phỏng lại lần nữa, đưa cửa sổ Scope ra va ấn nút autoscale. Bạn sẽ thấy đầu ra khácphản ánh giá trị mới lớn hơn của hệ số.

17

Page 343: Matlab Tutorial

Bên cạnh các biến thì tín hiệu, và ngay cả toàn bộ hệ thống có thể được trao đổi qua lại giữa MATLABvà Simulink. Để biết thêm, kích vào đây.

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

18

Page 344: Matlab Tutorial

Tạo mô hình trong SimulinkHệ thống xe lửaBiểu đồ giải phóng liên kết và định luật NewtonCấu trúc mô hìnhChạy thực thi mô hìnhObtaining MATLAB Model

Trong Simulink, rất dễ dàng biểu diễn 1 cách thẳng thừng một hệ vật lý hoặc một mô hình. Tựu chunglại, một hệ động lực học có thể được xây dựng từ các định luật vật lý cơ bản. Chúng ta sẽ minh hoạđiều này thông qua một ví dụ.

Hệ thống xe lửa

Trong ví dụ này, chúng ta xem xét 1 chiếc xe lửa đồ chơi bao gồm 1 động cơ và 1 xe kéo. Giả sử rằngxe lửa chỉ di chuyển theo 1 hướng, chúng ta cần điều khiển sao cho xe lửa khởi động và dừng lại thậtêm, theo đó là chuyển động thẳng với vận tốc không đổi.

Trọng lượng của động cơ và xe kéo biểu diễn là M1 và M2 tương ứng. Hai vật được nối với nhau bởi1 lò xo có độ cứng tương ứng là k. F là lực kéo của động cơ, và chữ cái Hy lạp muy (biểu diễn là u) làhệ số ma sát lăn.

Biểu đồ giải phóng liên kết và định luật Newton

Hệ thống có thể được biểu diễn thông qua Biểu đồ giả phóng liên kết sau.

Từ định luật Newton, ta biết rằng tổng các lực tác dụng lên 1 khối lượng bằng tích của khối lượng đóvà gia tốc của nó. Trong trường hợp này, các lực tác dụng lên M1 là lực đàn hồi lò xo, lực ma sát vàlực kéo của động cơ. Các lực tác dụng vào M2 là lực đàn hồi lò xo và lực ma sát. Theo phương thẳngđứng, trọng lực cân bằng với phản lực của mặt đất, do vậy không có gia tốc theo phương thẳng đứng.

1

Page 345: Matlab Tutorial

Chúng ta sẽ bắt dầu xây dựng mô hình bằng mô tả đơn giản:

Sum(forces_on_M1)=M1*x1'' Sum(forces_on_M1)=M1*x1''

Xây dựng mô hình

Tập các phương trình này có thể được mô tả bằng đồ hoạ, không cần thêm thao tác nào khác. Trướctiên, ta xây dựng hai bản copy (cho mỗi khối lượng) cho biểu thức tổng_F=Ma hay là a=1/M*tổng_F.Mở một cửa sổ mô hình mới, kéo hai khối Sum (từ thư viện Linear), để một khối ở phía trên khối kia.Đánh nhãn cho các khối Sum là "Sum_F1" and "Sum_F2".

Các đầu ra output của mỗi khối Sum biểu diễn cho tổng các lực tác dụng lên mỗi khối lượng. Khi nhânvới 1/M sẽ cho ta giá trị gia tốc. Kéo hai khối Gain vào mô hình và nối chúng với đầu ra của các khốiSum.

Các khối Gain này sẽ là 1/M tương ứng với từng khối lượng. Chúng ta sẽ lấy các biến M1 và M2 từMATLAB, như vậy ta chỉ cần nhập biến cho mỗi khối Gain. Kích đúp lên khối Gain phía trên và nhậpvào trường Gain thành.

1/M1

2

Page 346: Matlab Tutorial

Tương tự cho khối Gain thứ hai thành.

1/M2

Bây giờ bạn có thể thấy rằng hệ số không thấy hiện lên trên khối Gain, và chỉ có hình "-K-" hiện lên.Điều này bởi vì hình khối của chúng quá nhỏ để hiển thị được 1/M2 lên trên. Các khối có thể chỉnhđược kích thước sao cho hệ số có thể nhìn thấy được. Để chỉnh lại kích thước cho 1 khối, kích chuộtchọn nó. Các hình vuông nhỏ sẽ hiện lên ở 4 góc. Kéo các hình vuông nhỏ để mở rộng khối.

Khi kích thước khối Gain đủ để hiển thị hệ số, hãy sắp xếp lại chúng thẳng theo đường tín hiệu. Cũngthế, đánh nhãn cho hai khối Gain "a1" và "a2".

Đầu ra của các khối Gain là gia tốc của mỗi khối lượng. Chúng ta quan tâm tới cả vận tốc và vị trí củacủa các khối lượng. Vì vận tốc là tích phân của gia tốc, nên chúng ta có thể tạo ra các tín hiệu bằngcách sử dụng các khối tích phân. Kéo hai khối tích phân vào mô hình đối với hai tín hiệu gia tốc. Kếtnối chúng bằng các đường thành hai chuỗi giống như sau. Đánh nhãn cho các khối tích phân là "v1","x1", "v2", và "x2" vì chúng là các tín hiệu mà các khối này tạo ra.

3

Page 347: Matlab Tutorial

Bây giờ, kéo hai khối Scope từ thư viện Sinks vào mô hình và liên kết chúng với các đầu ra của cáckhối tích phân này. Đánh nhãn chúng là "View_x1" và "View_x2".

Bây giờ chúng ta sẵn sàng thêm các lực tác dụng vào mỗi khối lượng. Trước tiên, bạn cần tính toáncác đầu vào cho mỗi khối Sum một cách chính xác (các kí hiệu sẽ bàn sau). Có 3 tác động lên M1,nên ta thay đổi ở hộp thoại của khối Sum_F1 thành:

+++

Chỉ có 2 lực tác dụng lên M2, nên ta vẫn giữ nguyên khối Sum_F1.

4

Page 348: Matlab Tutorial

Lực đầu tiên tác dụng lên M1 là lực đầu vào F. Kéo khối Signal Generator từ thư viện Sources và liênkết nó với đầu vào phía trên cùng của khối Sum_F1. Đánh nhãn cho Signal Generator là "F".

Lực tiếp theo tác dụng lên M1 là lực ma sát. Lực này tính bằng:

F_friction_1=mu*g*M1*v1

Để tạo ra tín hiệu này, chúng ta phải trích tín hiệu vận tốc và nhân với mu*g*M1. Kéo thêm 1 khốiGain vào mô hình. Trích tín hiệu từ khối tích phân v1 và nối nó vào đầu vào của khối Gain (có thểphải qua 1 số thao tác vẽ nếu cần). Liên kết đầu ra của khối Gain này với đầu vào thứ hai của khốiSum_F1. Thay đổi hệ số của khối Gain thành.

mu*g*M1

Chỉnh lại kích thước của khối Gain để có thể hiển thị được hệ số và nhãn là Friction_1.

5

Page 349: Matlab Tutorial

Lực này là lực tác động ngược chiều đối với x1. Do vậy đầu vào khối Sum_F1 của nó phải có dấu -.Thay đổi các dấu của khối Sum_F1 thành

+-+

Lực cuối cùng tác dụng vào M1 là lực đàn hồi của lò xo lắp giữa hai khối lượng. Lực này bằng:

k*(x1-x2)

Trước hết, ta phải tạo ra tín hiệu (x1-x2) sau đó nhân với k đê tạo ra lực đàn hồi. Kéo thêm 1 khốiSum vào phần còn lại của mô hình. Đánh nhã nó là "(x1-x2)" và thay đổi dấu tín hiệu đầu vào thành

-+

Vì tổng này thực hiện từ phải sang trái nên ta phải xoay khối này lại. Chọn khối bằng cách kích chuộtvào nó và chọn Flip từ menu Format (hoặc nhấn Ctrl-F). Bạn sẽ thấy như sau.

6

Page 350: Matlab Tutorial

Bây giờ trích tín hiệu x2 và nối nó với đầu vào - của khối (x1-x2). Trích tín hiệu x1 và nối nó với đầuvào + tiếp theo. Động tác này sẽ làm cho các đường nối cắt nhau. Các đường có thể cắt nhau, nhưngchúng thực sự liên kết với nhau ở chỗ có các khối nhỏ (ví dụ như ở điểm trích).

Bây giờ chúng ta có thể nhân giá trị sai lệch vị trí này với hằng số của lò xo để được lực đàn hồi. Kéomột khối Gain vào phía trái của khối Sum. Thay hệ số của nó thành k và đánh nhãn là "spring". Liênkết đầu ra của khối (x1-x2) với đầu vào của khối spring, và đầu ra của khối spring với đầu vào thứ 3của khối Sum_F1. Đổi dấu đầu vào khối Sum_F1 thành +--.

7

Page 351: Matlab Tutorial

Bây giờ chúng ta có thể đặt các lực vào M2. Lực thứ nhất chính là lực lò xo mà chúng ta vừa tạo ra,chỉ khác là chiều tác động là âm. Đơn giản chỉ cần trích tín hiệu đầu ra của khối spring và nối nó vớiđầu vào thứ nhất của khối Sum_F2.

Lực cuối cùng ta cần thêm vào là lực ma sát tác động lên M2. Điều này ta thực hiện giống như đã làmđối với M1, trích tín hiệu v2, nhân với mu*g*M2 và liên kết vào Sum_F2 với dấu là âm. Sau khi thựchiện xong, bạn sẽ có mô hình như sau.

8

Page 352: Matlab Tutorial

Bây giờ mô hình đã hoàn tất. Bây giờ chúng ta chỉ cần cho đúng tín hiệu vào và quan sát đầu ra. Đầuvào của hệ thống là lực phát động F của động cơ. Chúng ta đã có hàm tạo tín hiệu đầu vào. Đầu ra củahệ thống là vận tốc của đầu máy. Kéo 1 khối Scope từ thư viện Sinks vào mô hình của bạn. Trích tínhiệu ra "v1" từ khối tích phân cho vào khối đó để xem được đầu ra vận tốc. Đánh nhãn khối scopemới là "View_v1".

Bây giờ mô hình đã xong, ghi lại dưới tên file nào tuỳ ý bạn. Bạn cũng có thể download mô hình hoànchỉnh ở đây.

Chạy thực thi mô hình

Trước khi cho chạy mô hình, chúng ta cần xác định các giá trị tham biến dùng trong mô hình. Với môhình xe lửa, cho

M1 = 1 kgM2 = 0.5 kgk = 1 N/sec

9

Page 353: Matlab Tutorial

F= 1 Nu = 0.002 sec/mg = 9.8 m/s^2

Tạo 1 m-file mới có các lệnh sau.

M1=1;M2=0.5;k=1;F=1;mu=0.002;g=9.8;

Chạy m-file này để xác định các giá trị này. Simulink sẽ nhận ra các biến của MATLAB và sử dụngchúng trong mô hình.

Bây giờ chúng ta cần tạo ra đầu vào gần đúng cho đầu máy. Kích đúp vào khối tạo hàm (khối F).Chọn dạng sóng vuông với tần số 0 .001Hz và biên độ là -1 (vì biên độ dương sẽ tạo ra mức âm trướcmức dương).

Bước cuối cùng trước khi chạy mô phỏng là chọn thời gian mô phỏng. Để quan sát 1 chu kì của tần số0.001Hz , chúng ta phải mô phỏng trong 1000 giây. Chọn Parameters từ menu Simulation và thayđổi trường Stop Time thành 1000. Sau đó đóng hộp thoại lại.

Bây giờ hãy chạy mô phỏng và mở View_v1 để xem đầu ra vận tốc (ấn autoscale). Đầu vào là sóngvuông với hai bước, 1 âm và 1 dương. Nhìn từ khía cạnh vật lý, ta thấy đầu máy ban đầu di chuyểntiến lên, sau đó lùi lại. Đầu ra vận tốc phản ánh rõ điều này.

10

Page 354: Matlab Tutorial

Obtaining MATLAB Model

Chúng ta cũng có thể tạo ra 1 mô hình trong MATLAB (ví dụ như mô hình không gian trạng thái hoặchàm truyền) từ mô hình simulink. Để làm điều này, xoá khối scope View_v1 thay vào đó là 1 khối Out(Trong thư viện Connections). Cũng thế, xóa khối tạo hàm F và thay vào đó là 1 khối In (Trong thưviện Connections). Các khối vào và ra này xác đinh đầu vào và đầu ra của hệ thống mà ta cần tạo. Đểbiết chi tiết về cách xử lý và các cách tích hợp MATLAB và Simulink với nhau kích vào đây.

Lưu mô hình dưới dạng file train2.mdl hoặc download mô hình ở đây. Bây giờ chúng ta có thể tạo ramô hình trong MATLAB. Đánh lệnh sau trong cửa sổ lệnh của MATLAB để xuất ra mô hình không giantrạng thái.

[A,B,C,D]=linmod('train2')

Bạn sẽ thấy nó cho ra các ma trận xác định 1 mô hình không gian trạng thái tương ứng với mô hìnhtrong Simulink như sau.

A =

-0.0196 0 1.0000 -1.0000 0 -0.0196 -2.0000 2.0000

11

Page 355: Matlab Tutorial

0 1.0000 0 0 1.0000 0 0 0

B =

1 0 0 0

C =

1 0 0 0

D =

0

Để có mô hình hàm truyền, đánh các lệnh sau trong MATLAB.

[num,den]=ss2tf(A,B,C,D)

Bạn sẽ thấy nó cho ra tử và mẫu của hàm truyền tương ứng.

num =

0 1.0000 0.0196 2.0000 0.0000

den =

1.0000 0.0392 3.0004 0.0588 0.0000

Các mô hình này đều tương đương (mặc dù cách phát biểu khác nhau) với mô hình xây dựng bằng taytrong phần MATLAB.

Simulink ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

12

Page 356: Matlab Tutorial

Ví dụ: Mô hình xe trong Simulink

Cài đặt các thông số vật lý và các phương trình hệ thốngXây dựng mô hìnhĐáp ứng của hê hởTruy xuất mô hìnhThực thi bộ điều khiển PIĐáp ứng của hệ kín

Cài đặt các thông số vật lý và các phương trình hệ thống

Mô hình của hệ thống điều khiển xe theo 1 cách nào đó là tương đối đơn giản. Nếu momen quán tínhcủa bánh được bỏ qua, và giả sử ma sát (tỉ lệ với vận tốc của xe) là lực duy nhất cản trở chuyển độngcủa xe, thì bài toán được rút gọn thành hệ khối lượng và giảm chấn đơn giản như sau.

Dùng định luật Newton, các phương trình của hệ như sau:

(1)

ở đây u là lực phát động của động cơ. Với ví dụ này, giả sử rằng

m = 1000kgb = 50Nsec/m

u = 500N

Xây dựng mô hình

Hệ thống này có thể được mô hình bằng cách tính tổng các lực tác dụng vào khối lượng và tích phângia tốc để tính ra vận tốc. Mở Simulink và mở 1 cửa sổ mô hình mới. Trước tiên, chúng ta sẽ mô hìnhhoá tích phân gia tốc

1

Page 357: Matlab Tutorial

Thêm 1 Khối tích phân (từ thư viện Linear) và vẽ các đường vào và ra cho khối.Đánh nhãn đường vào là "vdot" và đường ra là "v" như bên dưới. Để thêm 1 nhãn, kích đúp vàovùng trống phía trên đường tương ứng.

Vì gia tốc (dv/dt) bằng tổng các lực chia cho khối lượng, chúng ta sẽ chia tín hiệu đầu vào cho khốilượng.

Thêm 1 khối Gain (từ thư viện Linear) và nối nó với đường vào của khối tích phân và vẽ 1đường vào cho đầu vào khối gain đó.Thay đổi lại khối gain bằng cách kích đúp lên nó và thay giá trị thành "1/m".Thay nhãn của khối Gain thành "inertia" bằng cách kích vào từ "Gain" phía dưới khối đó.

Bây giờ, chúng ta sẽ thêm các lực như trong phương trình (1). Trước tiên, chúng ta thêm lực cản.

Gắn thêm 1 khối Sum (từ thư viện Linear) vào đường dẫn tới khối quá tính.Thay dấu của khối Sum này thành "+-".Thêm 1 khối gain vào phía dưới khối quán tính, chọn nó bằng cách kích đơn, và chọn Flip từmenu Format (hoặc ấn Ctrl-F) để lật nó từ bên trái qua bên phải.Đặt giá trị hệ số là "b" và đổi tên khối thành "damping".Trích 1 đường (Giữ Ctrl khi vẽ) từ đầu ra của khối tích phân và nối với đầu vào của khốidamping.Vẽ 1 đường từ đầu ra khối damping tới đầu vào - của khối Sum.

2

Page 358: Matlab Tutorial

Lực thứ hai tác dụng lên khối lưọng là lực đầu vào điều khiển, u. Chúng ta sẽ cho nó là đầu vào step.

Thêm 1 khối Step (từ thư viện Sources) và nối nó với đầu vào + của khối Sum.Để xem vận tốc đầu ra, thêm 1 khối Scope (từ thư viện Sinks) và nối nó với đầu ra của khối tíchphân.

Để có đầu vào step gần đúng bằng 500 tại t=0, kích đúp vào khối Step và đặt Step Time bằng"0" và Final Value là "u".

Đáp ứng của hệ hở

Để mo phỏng hệ thống trên. Trước hết, ta phải chọn thời gian mô phỏng hợp lý.

Chọn Parameters từ menu Simulation và nhập "120" vào trường Stop Time. 120 giây là đủ dài

3

Page 359: Matlab Tutorial

để xem đáp ứng của hệ hở.

Các thông số vật lý đã được chọn. Thực hiện các dòng lệnh sau trong cửa sổ lệnh của MATLAB:

m=1000;b=50;u=500;

Cho chạy mô phỏng (ấn Ctrl-t hoặc chọn Start trên menu Simulation). Khi kết thúc mô phỏng, kíchđúp vào khối scope và nhấn vào nút autoscale. Bạn sẽ có đầu ra như sau.

Truy xuất Mô hình tuyến tính vào MATLAB

Một mô hình tuyến tính của 1 hệ thống (ở dạng không gian trạng thái hoặc dạng hàm truyền) có thểtruy xuất từ Simulink vào MATLAB. Điều đó được thực hiện thông qua các khối liên kết In và Out vàhàm linmod.

4

Page 360: Matlab Tutorial

Thay các khối Step Block và Scope bằng khối In Connection và Out Connection tương ứng (cáckhối này lấy từ thư viện Connections). Nó xác định đầu vào và ra của hệ thống để có thể truyxuất ra.

Lưu mô hình dưới dạng file "ccmodel.mdl" (chọn Save As từ menu File). MATLAB sẽ truy xuất ra môhình tuyến tính từ file mô hình đó chứ không cần phải làm từ 1 cửa sổ mô hình. Trong cửa sổ lệnhMATLAB, thực hiện các lệnh sau:

[A,B,C,D]=linmod('ccmodel')[num,den]=ss2tf(A,B,C,D)

Bạn sẽ thấy lệnh trên cho ra các thông số về mô hình hệ thống dưới cả dạng không gian trạng thái vàhàm truyền.

A =

-0.0500

B =

1.0000e-003

C =

1

D =

0

num =

0 0.0010

den =

1.0000 0.0500

Để kiểm nghiệm lại việc truy xuất, chúng ta sẽ lấy đáp ứng step của hệ hở đối với hàm truyền nàytrong MATLAB. Chúng ta nhân tử số hàm truyền với 500 để mô phỏng đầu vào step 500N. Thực hiệnlệnh sau trong MATLAB.

5

Page 361: Matlab Tutorial

step(500*num,den);

Bạn sẽ thấy đồ thị cho ra tương đương với đồ thị của Scope.

Thực thi bộ điều khiển PI

Trong ví dụ về điều khiển xe 1 bộ điều khiển PI được thiết kế với Kp=800 và Ki=40 để đạt được đápứng mong muốn. Chúng ta sẽ thự thi nó trong Simulink bằng cách đưa mô hình đã lập trước vào phầnnày dưới dạng 1 khối hệ thống con.

Tạo 1 cửa sổ mô hình mới.Kéo 1 khối Subsystem từ thư viện Connections vào cửa sổ mô hình của bạn.

Kích đúp vào khối đó. Bạn sẽ thấy 1 cửa sổ trống biểu diễn nội dung của hệ thống con (hiệnthời chưa có gì).Mở Mô hình điều khiển xe đã lưu trước đó ra, ccmodel.mdl.Chọn Select All từ menu Edit (hoặc Ctrl-A), sau đó chọn Copy từ menu Edit(hoặc Ctrl-C).Chọn cửa sổ hệ thống con rỗng và chọn Paste từ menu Edit (hoặc Ctrl-V). Bạn sẽ thấy hệ thốnggốc trong cửa sổ hệ thống con mới. Đóng cửa sổ đó lại.

6

Page 362: Matlab Tutorial

Bạn sẽ thấy xuất hiện đầu vào và đầu ra của khối Subsystem. Đặt tên khối này là "plant model".

Bây giờ chúng ta sẽ xây dựng 1 bộ điều khiển PI cho plant model. Trước tiên, chúng ta phải lấy tínhiệu phản hồi của đầu ra.

Vẽ 1 đường kéo ra từ đầu ra của khối plant.Thêm 1 khối Sum và đặt "+-" cho các đầu vào của nó.Trích 1 đường từ đầu ra và nối nó với đầu vào - của khối Sum.

Đầu ra của khối Sum sẽ cho biết tín hiệu về sai số. Từ đó, chúng ta tạo lập các thành phần tỉ lệ và tíchphân.

Thêm 1 khối tích phân vào phía sau khối sum và nối chúng với nhau.Thêm và liên kết 1 khối gain vào sau khối tích phân, đó là hệ số của khâu tích phân.Đánh nhãn cho khối hệ số tích phân là Ki và gán giá trị hệ số là Ki.Thêm 1 khối Gain và nối nó với 1 đường trích từ đầu ra của khối Sum.Đánh nhãn cho nó là Kp và gán giá trị hệ số là Kp.

7

Page 363: Matlab Tutorial

Bây giờ chúng ta đã có các thành phần tỉ lệ và tích phân, ta sẽ cho tổng của chúng vào vào khâu chấphành.

Thêm 1 khối Sum vào giữa khối Ki và khâu chấp hành sau đó nối các đầu ra của 2 khối gain vàocác đầu vào của khối Sum mới.Nối đầu ra của khối Sum mới tới đầu vào của khâu chấp hành.

Cuối cùng, chúng ta sẽ đưa vào tín hiệu step và quan sat đầu ra trên scope.

Gắn 1 khối step với đầu vào còn lại của khối Sum tín hiệu phản hồi.Gắn 1 khối Scope với đầu ra của khâu chấp hành.Kích đúp lên khối Step và đặt Step Time là "0" và Final Value là "u". Điều này cho phép ta cóthể thay đổi biên độ từ bên ngoài simulink.

Bạn có thể download hệ thống kín của chúng tôi bằng cách kích vào đây here.

8

Page 364: Matlab Tutorial

Trong ví dụ này, chúng ta thiết lập1 bộ điều khiển PI từ các khối cơ bản. Về sau này, chúng ta dùng 1khối hàm truyền (từ thư viện Linear) để thực hiện luôn trong 1 bước, như dưới đây.

Bạn có thể download mô hình bằng cách kích vào đây here.

Đáp ứng của hệ kín

Để mô phỏng hệ thống, trước tiên ta cần chọn khoảng thời gian mô phỏng sao cho hợp lý. ChọnParameters từ menu Simulation và nhập "10" vào trường Stop Time. Yêu cầu thiết kế bao gồm thờigian quá độ nhỏ hơn 5 giây, nên chúng ta mô phỏng trong 10 để có thể đủ để xem đầu ra như thế nào.Các tham số vật lý cần được chọn. Thực hiện các lệnh sau trong MATLAB:

m=1000;b=50;u=10;Kp=800;Ki=40;

Chạy mô phỏng (ấn Ctrl-t hoặc Start từ menu Simulation). Khi mô phỏng kết thúc, kích đúp vào khốiscope và ấn nút autoscale. Bạn sẽ thấy đầu ra như sau.

Simulink ExamplesĐiều khiển xe | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | Pitch

9

Page 365: Matlab Tutorial

Controller | Ball and Beam

Các ví dụ về điều khiển xeModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

10

Page 366: Matlab Tutorial

Ví dụ: Mô Hình Động Cơ 1 Chiều trong Simulink

Cài đặt các thông số vật lý và các phương trình hệ thốngXây dựng mô hìnhĐáp ứng của hệ hởTruy xuất mô hìnhThực thi bộ điều khiển PIĐáp ứng của hệ kín

Cài đặt các thông số vật lý và phương trình hệ thống

Một trong những thiết bị chấp hành thông dụng trong hệ thống điều khiển là động cơ điện 1 chiều. Nótrực tiếp tạo ra chuyển động quay và kết hợp với các bánh dẫn hoặc tang trống có cáp để truyềnchuyển động. Mạch điện phần ứng và biểu đồ tách liên kết của roto được cho như sau:

Với ví dụ này, giả thiết các thông số vật lý có giá trị như sau.

* momen quán tính của roto (J) = 0.01 kg.m^2/s^2* hệ số cản do hệ cơ khí (b) = 0.1 Nms

* hằng số lực điện động (K=Ke=Kt) = 0.01 Nm/Amp* điện trở (R) = 1 ohm

* điện kháng (L) = 0.5 H* đầu vào (V): nguồn điện áp

* đầu ra (theta): góc quay của trục* roto và trục coi như là không biến dạng

Momen quay T có quan hệ với dòng điện phần ứng i bởi hệ số Kt. Sức điện động e quan hệ với vậntốc quay được biểu diễn bởi các phương trình sau:

1

Page 367: Matlab Tutorial

Trong đơn vị SI (ta sẽ dùng), Kt (hằng số phần ứng) bằng Ke (hằng số của động cơ).

Xây dựng mô hình

Hệ thống này được mô hình bằng cách lấy tổng các momen quay tác dụng lên và lấy tích phân gia tốcđể cho ra vận tốc. Đồng thời, ta sẽ áp dụng định luật Kirchoff vào mạch phần ứng.

Mở Simulink và mở 1 cửa sổ mô hình mới.

Trước hết, ta sẽ mô hình tích phân của gia tốc quay và độ biến đổi của dòng phần ứng.

Thêm 1 khối tích phân (từ thư viện Linear) và vẽ các đường vào và ra cho các đầu vào ra củanó.Đánh nhãn đường vào là "d2/dt2(theta)" và đường ra là "d/dt(theta)" như bên dưới. Để thêmcác nhãn đó, kích đúp vào vùng trống phía trên các đường.Thêm 1 khối tích phân vào phía trên khối trước đó và cũng vẽ các đường vào và ra cho các đầuvào ra của nó.Đánh nhãn cho đường vào là "d/dt(i)" và đường ra là "i".

Tiếp theo, chúng ta sẽ mô hình cả định luật Newton và Kirchoff. Các định luật này khi áp dụng vào hệthống động cơ cho ta các phương trình sau:

2

Page 368: Matlab Tutorial

Gia tốc góc bằng 1/J nhân với tổng các đại lượng (1dương, 1 âm.). Tương tự, đạo hàm của dòng điệnbằng 1/L nhân với tổng của 3 đại lượng (1 dương, 2 âm.).

Thêm 2 khối Gain vào mô hình, (từ thư viện Linear) mỗi khối được gắn vào từng khối tích phân.Thay giá trị hệ số của khối gain tương ứng với gia tốc góc "1/J".Thay nhãn cho khối Gain này thành "inertia".Tương tự, thay giá trị cho khối gain còn lại là "1/L" và nhãn là Inductance.Thêm hai khối Sum (từ thư viện Linear), mội khối gắn với từng khối Gain.Thay dấu đầu vào của khối Sum tương ứng với góc quay là "+-" để có 1 đại lượng là dương, 1đại lượng là âm.Thay dấu đầu vào khối Sum còn lại thành "-+-" để biểu diễn cho các dấu trong phương trìnhKirchoff.

Bây giờ, chúng ta sẽ thêm các momen quay trong phương trình Newton. Trước hết, ta thêm momencản.

Thêm 1 khối gain vào phía dưới khối quán tính, kích chuột chọn nó và chọn Flip trong menuFormat (hoặc nhấn Ctrl-F) to flip it left-to-right.Set the gain value to "b" and rename this block to "damping".Tap a line (hold Ctrl while drawing) off the rotational integrator's output and connect it to theinput of the damping gain block.Draw a line from the damping gain output to the negative input of the rotational Sum block.

Next, we will add in the torque from the armature.

Insert a gain block attached to the positive input of the rotational Sum block with a line.Edit it's value to "K" to represent the motor constant and Label it "Kt".

3

Page 369: Matlab Tutorial

Continue drawing the line leading from the current integrator and connect it to the Kt gainblock.

Now, we will add in the voltage terms which are represented in Kirchoff's equation. First, we will addin the voltage drop across the coil resistance.

Insert a gain block above the inductance block, and flip it left-to-right.Set the gain value to "R" and rename this block to "Resistance".Tap a line (hold Ctrl while drawing) off the current integrator's output and connect it to the inputof the resistance gain block.Draw a line from the resistance gain output to the upper negative input of the current equationSum block.

Next, we will add in the back emf from the motor.

Insert a gain block attached to the other negative input of the current Sum block with a line.Edit it's value to "K" to represent the motor constant and Label it "Ke".Tap a line off the rotational integrator output and connect it to the Ke gain block.

4

Page 370: Matlab Tutorial

The third voltage term in the Kirchoff equation is the control input, V. We will apply a step input.

Insert a Step block (from the Sources block library) and connect it with a line to the positiveinput of the current Sum block.To view the output speed, insert a Scope (from the Sinks block library) connected to the outputof the rotational integrator.To provide a appropriate unit step input at t=0, double-click the Step block and set the StepTime to "0".

You can download a model file for the complete system here.

Open-loop response

To simulate this system, first, an appropriate simulation time must be set. Select Parameters from the

5

Page 371: Matlab Tutorial

Simulation menu and enter "3" in the Stop Time field. 3 seconds is long enough to view the open-loopresponse. The physical parameters must now be set. Run the following commands at the MATLABprompt:

J=0.01;b=0.1;K=0.01;R=1;L=0.5;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is finished,double-click on the scope and hit its autoscale button. You should see the following output.

Extracting a Linear Model into MATLAB

A linear model of the system (in state space or transfer function form) can be extracted from aSimulink model into MATLAB. This is done through the use of In and Out Connection blocks and theMATLAB function linmod. First, replace the Step Block and Scope Block with an In Connection Blockand an Out Connection Block, respectively (these blocks can be found in the Connections blocklibrary). This defines the input and output of the system for the extraction process.

6

Page 372: Matlab Tutorial

Save your file as "motormod.mdl" (select Save As from the File menu). MATLAB will extract the linearmodel from the saved model file, not from the open model window. At the MATLAB prompt, enter thefollowing commands:

[A,B,C,D]=linmod('motormodel')[num,den]=ss2tf(A,B,C,D)

You should see the following output, providing both state-space and transfer function models of thesystem.

A =

-10.0000 1.0000 -0.0200 -2.0000

B =

0 2

C =

1 0

D =

0

num =

0 0.0000 2.0000

den =

1.0000 12.0000 20.0200

7

Page 373: Matlab Tutorial

To verify the model extraction, we will generate an open-loop step response of the extracted transferfunction in MATLAB. Enter the following command in MATLAB.

step(num,den);

You should see the following plot which is equivalent to the Scope's output.

Implementing Lag Compensator Control

In the motor speed control root locus example a Lag Compensator was designed with the followingtransfer function.

To implement this in Simulink, we will contain the open-loop system from earlier in this page in aSubsystem block.

Create a new model window in Simulink.Drag a Subsystem block from the Connections block library into your new model window.

8

Page 374: Matlab Tutorial

Double click on this block. You will see a blank window representing the contents of thesubsystem (which is currently empty).Open your previously saved model of the Motor Speed system, motormod.mdl.Select Select All from the Edit menu (or Ctrl-A), and select Copy from the Edit menu (orCtrl-C).Select the blank subsystem window from your new model and select Paste from the Edit menu(or Ctrl-V). You should see your original system in this new subsystem window.Close this window. You should now see input and output terminals on the Subsystem block.Name this block "plant model".

Now, we will insert a Lag Compensator into a closed-loop around the plant model. First, we will feedback the plant output.

Draw a line extending from the plant output.Insert a Sum block and assign "+-" to it's inputs.Tap a line of the output line and draw it to the negative input of the Sum block.

9

Page 375: Matlab Tutorial

The output of the Sum block will provide the error signal. We will feed this into a Lag Compensator.

Insert a Transfer Function Block after the summer and connect them with a line.Edit this block and change the Numerator field to "[50 50]" and the Denominator field to "[10.01]".Label this block "Lag Compensator".

Finally, we will apply a step input and view the output on a scope.

Attach a step block to the free input of the feedback Sum block and attach a Scope block to theplant output.Double-click the Step block and set the Step Time to "0".

You can download our version of the closed-loop system here.

10

Page 376: Matlab Tutorial

Closed-loop response

To simulate this system, first, an appropriate simulation time must be set. Select Parameters from theSimulation menu and enter "3" in the Stop Time field. The design requirements included a settling timeof less than 2 sec, so we simulate for 3 sec to view the output. The physical parameters must now beset. Run the following commands at the MATLAB prompt:

J=0.01;b=0.1;K=0.01;R=1;L=0.5;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is finished,double-click on the scope and hit its autoscale button. You should see the following output.

Simulink ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Motor Speed ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

11

Page 377: Matlab Tutorial

Example: DC Motor Position Modeling in Simulink

Physical setupBuilding the modelOpen-loop responseExtracting a digital modelImplementing digital controlClosed-loop response

Physical setup

A common actuator in control systems is the DC motor. Itdirectly provides rotary motion and, coupled with wheels ordrums and cables, can provide transitional motion. Theelectric circuit of the armature and the free body diagram ofthe rotor are shown in the following figure:

For this example, we will assume the following values for the physical parameters. These values werederived by experiment from an actual motor in Carnegie Mellon's undergraduate controls lab.

* moment of inertia of the rotor (J) = 3.2284E-6 kg.m^2/s^2* damping ratio of the mechanical system (b) = 3.5077E-6 Nms* electromotive force constant (K=Ke=Kt) = 0.0274 Nm/Amp

* electric resistance (R) = 4 ohm* electric inductance (L) = 2.75E-6 H

* input (V): Source Voltage* output (theta): position of shaft

* The rotor and shaft are assumed to be rigid

The motor torque, T, is related to the armature current, i, by a constant factor Kt. The back emf, e, isrelated to the rotational velocity by the following equations:

1

Page 378: Matlab Tutorial

In SI units (which we will use), Kt (armature constant) is equal to Ke (motor constant).

Building the Model

This system will be modeled by summing the torques acting on the rotor inertia and integrating theacceleration to give the velocity, and integrating velocity to get position. Also, Kirchoff's laws will beapplied to the armature circuit. Open Simulink and open a new model window. First, we will modelthe integrals of the rotational acceleration and of the rate of change of armature current.

Insert an Integrator block (from the Linear block library) and draw lines to and from its inputand output terminals.Label the input line "d2/dt2(theta)" and the output line "d/dt(theta)" as shown below. To addsuch a label, double click in the empty space just above the line.Insert another Integrator block attached to the output of the previous one and draw a line fromits output terminal.Label the output line "theta".Insert a third Integrator block above the first one and draw lines to and from its input and outputterminals.Label the input line "d/dt(i)" and the output line "i".

2

Page 379: Matlab Tutorial

Next, we will start to model both Newton's law and Kirchoff's law. These laws applied to the motorsystem give the following equations:

The angular acceleration is equal to 1/J multiplied by the sum of two terms (one pos., one neg.).Similarly, the derivative of current is equal to 1/L multiplied by the sum of three terms (one pos., twoneg.).

Insert two Gain blocks, (from the Linear block library) one attached to each of the leftmostintegrators.Edit the gain block corresponding to angular acceleration by double-clicking it and changing itsvalue to "1/J".Change the label of this Gain block to "inertia" by clicking on the word "Gain" underneath theblock.Similarly, edit the other Gain's value to "1/L" and it's label to Inductance.Insert two Sum blocks (from the Linear block library), one attached by a line to each of theGain blocks.Edit the signs of the Sum block corresponding to rotation to "+-" since one term is positive andone is negative.Edit the signs of the other Sum block to "-+-" to represent the signs of the terms in Kirchoff'sequation.

Now, we will add in the torques which are represented in Newton's equation. First, we will add in thedamping torque.

Insert a gain block below the inertia block, select it by single-clicking on it, and select Flip fromthe Format menu (or type Ctrl-F) to flip it left-to-right.Set the gain value to "b" and rename this block to "damping".

3

Page 380: Matlab Tutorial

Tap a line (hold Ctrl while drawing) off the first rotational integrator's output (d/dt(theta)) andconnect it to the input of the damping gain block.Draw a line from the damping gain output to the negative input of the rotational Sum block.

Next, we will add in the torque from the armature.

Insert a gain block attached to the positive input of the rotational Sum block with a line.Edit it's value to "K" to represent the motor constant and Label it "Kt".Continue drawing the line leading from the current integrator and connect it to the Kt gainblock.

Now, we will add in the voltage terms which are represented in Kirchoff's equation. First, we will addin the voltage drop across the coil resistance.

Insert a gain block above the inductance block, and flip it left-to-right.Set the gain value to "R" and rename this block to "Resistance".Tap a line (hold Ctrl while drawing) off the current integrator's output and connect it to the inputof the resistance gain block.Draw a line from the resistance gain output to the upper negative input of the current equationSum block.

Next, we will add in the back emf from the motor.

Insert a gain block attached to the other negative input of the current Sum block with a line.Edit it's value to "K" to represent the motor constant and Label it "Ke".Tap a line off the first rotational integrator's output (d/dt(theta)) and connect it to the Ke gainblock.

4

Page 381: Matlab Tutorial

The third voltage term in the Kirchoff equation is the control input, V. We will apply a step input.

Insert a Step block (from the Sources block library) and connect it with a line to the positiveinput of the current Sum block.To view the output speed, insert a Scope (from the Sinks block library) connected to the outputof the second rotational integrator (theta).To provide a appropriate unit step input at t=0, double-click the Step block and set the StepTime to "0".

You can download a model file for the complete system here.

Open-loop response

To simulate this system, first, an appropriate simulation time must be set. Select Parameters from the

5

Page 382: Matlab Tutorial

Simulation menu and enter "0.2" in the Stop Time field. 0.2 seconds is long enough to view theopen-loop response. Also in the Parameters dialog box, it is helpful to change the Solver Optionsmethod. Click on the field which currently contains "ode45 (Dormand-Prince)". Select the option"ode15s (stiff/NDF)". Since the time scales in this example are very small, this stiff system integrationmethod is much more efficient than the default integration method.

The physical parameters must now be set. Run the following commands at the MATLAB prompt:

J=3.2284E-6;b=3.5077E-6;K=0.0274;R=4;L=2.75E-6;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is finished,double-click on the scope and hit its autoscale button. You should see the following output.

Extracting a Digital Model into MATLAB

6

Page 383: Matlab Tutorial

A linear digital model of this continuous-time system (in state space or transfer function form) can beextracted from a Simulink model into MATLAB. Conversion to a discrete-time (digital) system is donewith Zero-Order Hold blocks on both the inputs and outputs of the system, which act as both D/A(sample-and-hold) and A/D devices. The extraction of a model makes use of In and Out Connectionblocks and the MATLAB function dlinmod. We will start with the model which we just build. You candownload a complete version here. We will first group all of the system components (except for theStep and Scope which aren't really part of the system) into a Subsystem block.

Drag the mouse from one corner of your model window to the other to highlight all of thecomponents. If possible, avoid highlighting the Step and Scope blocks, but if you do, hold theshift key and single click on either of the Step and Scope blocks to un-highlight them. Yourmodel window should appear as shown below.

Select Create Subsystem on the Edit menu (or hit Ctrl-G). This will group all of the selectedblocks into a single block. Your window should appear as shown below.

7

Page 384: Matlab Tutorial

Change the label of the Subsystem block to "Continuous Plant". If you like, you can resize thisblock so the words "In1" and "Out1" inside of it don't overlap. To resize a block, highlight it bysingle clicking it and drag the corners to the desired size.Replace the Step Block and Scope Block with Zero Order Hold blocks (from the Discrete blocklibrary). One Zero Order Hold block is used to convert a discrete-time signal to a stepwise-constant continuous signal. The other Zero Order Hold block is used to take discrete samples ofthe output from the plant.Edit the Zero Order Hold blocks and set the Sample Time fields to 0.001 (this is fast comparedto the desired step response in the MATLAB tutorial.)Connect an In Connection Block to the input of the first Zero Order Hold block, and an OutConnection Block to the output of the second Zero Order Hold block. (these blocks can befound in the Connections block library). This defines the input and output of the system for theextraction process.Drag each block in your model so that they are arranged in a line.

Save your file as "motorpos.mdl" (select Save As from the File menu). MATLAB will extract the linearmodel from the saved model file, not from the open model window. At the MATLAB prompt, enter thefollowing commands:

[A,B,C,D]=dlinmod('motorposmodel',.001)[num,den]=ss2tf(A,B,C,D)

The extra parameter in dlinmod provides the sample time for the discrete conversion. You should seethe following output, providing discrete time models of the system both in state-space and transferfunction form.

A =

1.0000 0.0000 0.0010 0 0.0000 -0.0065 0 0.0055 0.9425

B =

0.0010 0.2359 2.0589

C =

1 0 0

8

Page 385: Matlab Tutorial

D =

0

num =

0 0.0010 0.0010 0.0000

den =

1.0000 -1.9425 0.9425 0

As noticed in above results, both numerator and denominator of the discrete transfer function haveone extra root at z = 0. These cancel each other, and the discrete-time transfer function to the motorposition output from the voltage input is:

To verify the model extraction, we will generate an open-loop step response of the extracted transferfunction in MATLAB. Enter the following commands in MATLAB.

[x1] = dstep(num,den,201);t=0:0.001:0.2;stairs(t,x1)

You should see the following plot which is equivalent to the Scope's output.

Implementing Digital Control

In the motor speed control digital example a digital controller was designed with the following transfer

9

Page 386: Matlab Tutorial

function.

Bring up the model window containing the digital system which was just extracted intoMATLAB. (You can download our version here)Delete the "In" and "Out" blocks.

We will first feed back the plant output.

Insert a Sum block and assign "+-" to it's inputs.Tap a line of the output line of the output Zero Order Hold line and draw it to the negative inputof the Sum block.

The output of the Sum block will provide the error signal. We will feed this into the digital controller.

Insert a Discrete Transfer Function Block (from the Discrete block library) after the summerand connect them with a line.Edit this block and change the Numerator field to "450*conv([1 -.85],[1 -.85])", theDenominator field to "conv([1 .98],[1 -.7])", and the Sample Time to ".001".Label this block "Controller" and resize it to view the entire contents.

10

Page 387: Matlab Tutorial

Finally, we will apply a step input and view the output on a scope.

Attach a Step block to the free input of the feedback Sum block and attach a Scope block to theplant output.Double-click the Step block and set the Step Time to "0".

You can download our version of the closed-loop system here.

Closed-loop response

To simulate this system, first, an appropriate simulation time must be set. Select Parameters from theSimulation menu and enter "0.05" in the Stop Time field. The design requirements included a settlingtime of less than 0.04 sec, so we simulate for 0.05 sec to view the output. The physical parametersmust now be set. Run the following commands at the MATLAB prompt:

J=3.2284E-6;b=3.5077E-6;K=0.0274;R=4;L=2.75E-6;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is finished,double-click on the scope and hit its autoscale button. You should see the following output.

11

Page 388: Matlab Tutorial

Simulink ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Motor Position ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

12

Page 389: Matlab Tutorial

Example: Bus Suspension Modeling in Simulink

Physical setupBuilding the modelOpen-loop responseExtracting the ModelImplementing Full State FeedbackClosed-loop response

Physical setup

Designing an automatic suspension system for a bus turns out to be an interesting control problem. When thesuspension system is designed, a 1/4 bus model (one of the four wheels) is used to simplify the problem to aone dimensional spring-damper system. A diagram of this system is shown below:

Where:

* body mass (m1) = 2500 kg,* suspension mass (m2) = 320 kg,

* spring constant of suspension system(k1) = 80,000 N/m,* spring constant of wheel and tire(k2) = 500,000 N/m,

* damping constant of suspension system(b1) = 350 Ns/m.* damping constant of wheel and tire(b2) = 15,020 Ns/m.

* control force (u) = force from the controller we are going to design.

Design requirements:

A good bus suspension system should have satisfactory road holding ability, while still providing comfortwhen riding over bumps and holes in the road. When the bus is experiencing any road disturbance (i.e. potholes, cracks, and uneven pavement),the bus body should not have large oscillations, and the oscillationsshould dissipate quickly. Since the distance X1-W is very difficult to measure, and the deformation of thetire (X2-W) is negligible, we will use the distance X1-X2 instead of X1-W as the output in our problem.Keep in mind that this is an estimation.

1

Page 390: Matlab Tutorial

The road disturbance (W) in this problem will be simulated by a step input. This step could represent the buscoming out of a pothole. We want to design a feedback controller so that the output (X1-X2) has anovershoot less than 5% and a settling time shorter than 5 seconds. For example, when the bus runs onto a 10cm high step, the bus body will oscillate within a range of +/- 5 mm and return to a smooth ride within 5seconds.

Building the Model

This system will be modeled by summing the forces acting on both masses (body and suspension) andintegrating the accelerations of each mass twice to give velocities and positions. Newton's law will beapplied to each mass. Open Simulink and open a new model window. First, we will model the integrals ofthe accelerations of the masses.

Insert an Integrator block (from the Linear block library) and draw lines to and from its input andoutput terminals.Label the input line "a1" (for acceleration) and the output line "v1" (for velocity) To add such a label,double click in the empty space just above the line.Insert another Integrator block connected to the output of the first.Draw a line from its output and label it "x1" (for position).Insert a second pair of Integrators below the first with lines labeled "a2", "v2", and "x2".

Next, we will start to model Newton's law. Newton's law for each of these masses can be expressed as:

2

Page 391: Matlab Tutorial

These equations can be represented with gain blocks (for 1/M1 and 1/M2) and two summation blocks.

Insert two Gain blocks, (from the Linear block library) one attached to the inputs of each of theintegrator pairs.Edit the gain block corresponding to M1 by double-clicking it and changing its value to "1/m1".Change the label of this Gain block to "Mass 1" by clicking on the word "Gain" underneath the block.Similarly, edit the other Gain's value to "1/m2" and it's label to "Mass 2". (You may want to resize thegain blocks to view the contents. To do this, single click on the block to highlight it, and drag one ofthe corners to the desired size.)

There are three forces acting on M1 (one spring, one damper, and the input, u) and five forces acting on M2(two springs, two dampers, and the input, u).

Insert two Sum blocks (from the Linear block library), one attached by a line to each of the Gainblocks.Edit the signs of the Sum block corresponding to M1 to "+--" to represent the three forces (two ofwhich will be negative)Edit the signs of the other Sum block to "++-++" to represent the five forces, one of which will benegative.

Now, we will add in the forces acting on each mass. First, we will add in the force from Spring 1. This forceis equal to a constant, k1 times the difference X1-X2.

Insert a sum block after the upper pair of integrators.Edit its signs to "+-" and connect the "x1" signal to the positive input and the "x2" signal to thenegative input.Draw a line leading from the output of the Sum block.

3

Page 392: Matlab Tutorial

Insert a Gain block above the "Mass1" block.Flip it left-to-right by single-clicking on it and selecting Flip Block from the Format menu (or hitCtrl-F).Edit the value of this gain to "k1" and label the block "Spring 1".Tap a line off the output of the last Sum block and connect it to the input of this gain block.Connect the output of this gain block (the spring force) to the second input of the Mass 1 Sum block.This input should be negative since the Spring 1 pulls down on Mass 1 when X1 > X2.Tap a line off the spring force line and connect it to the second input of the Mass 2 Sum block. Thisinput is positive since Spring 1 pulls up on Mass 2.

Now, we will add in the force from Damper 1. This force is equal to b1 times V1-V2.

Insert a sum block below the Mass 1's first integrator.Flip it left-to-right, and edit it's signs to "+-".Tap a line off the "v1" line and connect it to the positive input of this Sum block.Tap a line off the "v2" line and connect it to the negative input of this Sum block.Insert a Gain block to the left of this Sum block and flip it left-to-right.Edit it's value to "b1" and label it "Damper 1".Connect the output of the new Sum block to the input of this gain block.Connect the output of this gain block (the damper force) to the third input of the Mass 1 Sum block.This input is negative, similar to Spring 1's force on Mass 1.Tap a line off Damper 1's force line and connect it to the first input (which is positive) of Mass 2'sSum block.

4

Page 393: Matlab Tutorial

Now we will add in the force from Spring 2. This force acts only on Mass 2, but depends on the groundprofile, W. Spring 2's force is equal to X2-W.

Insert a Step block in the lower left area of your model window. Label it "W".Edit it's Step Time to "0" and it's Final Value to "0". (We will assume a flat road surface for now).Insert a Sum block to the right of the W Step block and edit its signs to "-+".Connect the output of the Step block to the positive input of this Sum block.Tap a line off the "x2" signal and connect it to the negative input of the new Sum block.Insert a Gain block to the right of this Sum block and connect the Sum's output to the new Gain'sinput.Change the value of the gain to "k2" and label it "Spring 2".Connect the output of this block (Spring 2's force) to the fourth input of Mass 2's Sum block. Thisforce adds in in the positive sense.

5

Page 394: Matlab Tutorial

Next, we will add in the force from Damper 2. This force is equal to b2 times V2-d/dt(W). Since there is noexisting signal representing the derivative of W we will need to generate this signal.

Insert a Derivative block (from the Linear block library) to the right of the W step block.Tap a line of the Step's output and connect it to the input of the Derivative block.Insert a Sum block after the Derivative block and edit it's signs to "+-".Connect the Derivative's output to the positive input of the new Sum block.Tap a line off the "v2" line and connect it to the negative input of this Sum block.Connect the output of this Sum block (Damper 2's force) to the fifth input of Mass 2's Sum block. Thisforce also adds in with positive sign.

The last force in the input U acting between the two masses.

6

Page 395: Matlab Tutorial

Insert a Step block in the upper left of the model window.Connect it's output to the remaining input of Mass 1's Sum block (with positive sign).Tap a line off this signal and connect it to the remaining input of Mass 2's Sum block (with negativesign).Edit this Step block's Step Time to "0" and leave its Final Value "1".Label this Step block "U".Finally, to view the output (X1-X2) insert a Scope connected to the output of the rightmost Sumblock.

You can download a model file for the complete system here.

Open-loop response

To simulate this system, first, an appropriate simulation time must be set. Select Parameters from theSimulation menu and enter "50" in the Stop Time field. 50 seconds is long enough to view the open-loopresponse. The physical parameters must now be set. Run the following commands at the MATLAB prompt:

m1=2500;m2=320;k1=80000;k2=500000;b1 = 350;b2 = 15020;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is finished, double-click onthe scope and hit its autoscale button. You should see the following output.

7

Page 396: Matlab Tutorial

Extracting a Linear Model into MATLAB

A linear model of the system (in state space or transfer function form) can be extracted from a Simulinkmodel into MATLAB. This is done through the use of In and Out Connection blocks and the MATLABfunction linmod. We will extract only the model from the input U to the output X1-X2.

First, replace the U Step block with an In Connection Block.Also, replace the Scope block with an Out Connection Block. (These blocks can be found in theConnections block library). This defines the input and output of the system for the extraction process.

Save your file as "suspmod.mdl" (select Save As from the File menu). MATLAB will extract the linear modelfrom the saved model file, not from the open model window. At the MATLAB prompt, enter the followingcommands:

[A,B,C,D]=linmod('suspmodel')[num,den]=ss2tf(A,B,C,D)

You should see the following output, providing both state-space and transfer function models of the system.

8

Page 397: Matlab Tutorial

A =

1.0e+003 *

0 0 0 0.0010 0 0 0.0010 0 0.2500 -1.8125 -0.0480 0.0011 -0.0320 0.0320 0.0001 -0.0001

B =

0 0 -0.0031 0.0004

C =

1 -1 0 0

D =

0

num =

0 0.0000 0.0035 0.0188 0.6250

den =

1.0e+004 *

0.0001 0.0048 0.1851 0.1721 5.0000

To verify the model extraction, we will generate an open-loop step response of the extracted transferfunction in MATLAB. Enter the following command in MATLAB.

step(num,den);

You should see the following plot which is equivalent to the Scope's output.

9

Page 398: Matlab Tutorial

Implementing Full State Feedback

In the Bus Suspension Control State Space example a full-state feedback controller was designed feedingback the following five states:

The controller used the following feedback gain matrix:

To implement this in Simulink, we will contain the open-loop system from earlier in this page in a Subsystemblock.

Create a new model window.Drag a Subsystem block from the Connections block library into your new model window.

Double click on this block. You will see a blank window representing the contents of the subsystem(which is currently empty).Open your previously saved model of the Bus Suspension system, suspmod.mdl.Select Select All from the Edit menu (or Ctrl-A), and select Copy from the Edit menu (or Ctrl-C).Select the blank subsystem window from your new model and select Paste from the Edit menu (or

10

Page 399: Matlab Tutorial

Ctrl-V). You should see your original system in this new subsystem window (you may need to use thescroll bars to center on it).Label the In Connection block "U", and the Out Connection block "y1".Replace the W Step block with an In Connection block and label this block "W".

Now we will generate the other state outputs from the subsystem.

Insert an Out block below the "y1" block and label it "d/dt(y1)", Tap a line off the line leading into theDamper 1 gain block (V1-V2) and connect it to the d/dt(y1) Out block.Insert another Out block below the "d/dt(y1)" Out block and label it "x1".Tap a line off the "x1" line and connect it to this Out block.Insert another Out block below the "x1" Out block and label it "d/dt(x1)".Tap a line off the "v1" line and connect it to this Out block.

11

Page 400: Matlab Tutorial

The final, extra, state needs to be generated, which is the integral of Y1.

Insert an Integrator block above the "y1" Out block and connect its input with a line tapped of theinput to the "y1" Out block.Insert an Out block, label it "int(y1)", and connect it to the output of the new integrator.

Since the state outputs will be used to form a vector, it is important that they be numbered in the right order.

Edit the "x1" Out block and change its Port Number to "1".Similarly, change the "d/dt(x1)" Out block's port number to "2", "y1" Out's port number to "3","d/dt(y1)" Out's port number to "4", and "int(y1)" Out's port number to "5".The In blocks should be numbered such that "U" is "1" and "W" is "2". Some of these numbers mayalready be correct.

12

Page 401: Matlab Tutorial

Close the Subsystem window. You should now see input and output terminals on the Subsystem block.Name this block "Suspension Model".You should resize this block so that you can read all of the labels. To do this, highlight it by single-clicking on it and drag one of the highlighted corners to the right size. Notice that the model has twoinputs and five outputs. Each input and output is a scalar signal in this model.

Now, we will build a full-state feedback controller around the plant model. First, we need to create a vectorsignal out of the five scalar outputs in order to multiply by the feedback gain matrix K.

Insert a Mux block (from the Connections block library) to the right of the Suspension Model block.The Mux takes multiple inputs and combines them into a vector signal. By default, the Mux has threeinputs.Edit the Mux block and change the Number of Inputs to "5".Resize the Mux so that it is the same height as the Suspension Model block.Connect each of the Suspension Model's outputs to the Mux's inputs in order.

Now, we will close the loop.

Insert a Matrix Gain block (from the Linear block library) below the Suspension Model block.Flip the Matrix Gain left-to-right and edit its value to "K".Insert a Sum block to the left of the Suspension Model block.Edit its signs to "+-".Connect the output of the Matrix Gain to the negative input of the Sum block.Connect the output of the Sum block to the "U" input of the Suspension Model.

13

Page 402: Matlab Tutorial

Insert a Step block and connect it to the positive input of the Sum block.Label the step block "r" and edit its Step Time to "0" and its Final Value to "0" (we are commandingthe bust to stay level).Insert a Step block and connect it to the "W" input of the Suspension Model.Edit its Step Time to "0" and its Final Value to "-.1" (we are now assuming a 10cm deep pothole).Insert a Scope block and tap a line off the "y1" output of the Suspension Model and connect it to theScope.

You can download our version of the closed-loop system here.

Closed-loop response

To simulate this system, first, an appropriate simulation time must be set. Select Parameters from theSimulation menu and enter "2" in the Stop Time field. The design requirements included a settling time ofless than 5 sec, and the system actually settles in 2 sec. The physical parameters must now be set. Run thefollowing commands at the MATLAB prompt:

m1=2500;m2=320;k1=80000;k2=500000;b1 = 350;b2 = 15020;

14

Page 403: Matlab Tutorial

The last step is to assign values to the feedback gain matrix K. Execute the following command at theMATLAB prompt.

K= [ 0 2.3e6 5e8 0 8e6 ];

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is finished, double-click onthe scope and hit its autoscale button. You should see the following output.

Simulink ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | Pitch Controller| Ball and Beam

Bus Suspension ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space | DigitalControl | Simulink Basics | Simulink Modeling | Examples

15

Page 404: Matlab Tutorial

Ví dụ: Mô hình Con lắc ngược trong SimulinkThiết lập bài toán và yêu cầu thiết kếPhân tích lực và thiết lập phương trình của hệ thốngXây dựng mô hìnhĐáp ứng của hệ hởXuất mô hình đã được tuyến tính hoáThực thi điều khiển PIDĐáp ứng của hệ hở

Thiết lập bài toán và yêu cầu thiết kế

Xe và con lắc ngược như sau được đẩy đi với 1 xung lực F. Xác định các phương trình động lực họcchuyển động của hệ thống, và tuyến tính hoá góc quay của con lắc, theta = 0 (nói cách khác, giả sửcon lắc không dịch chuyển quá vài độ so với phương thẳng đứng tương ứng với góc là 0). Ta cần tìm 1bộ điều khiển thoả mãn các yêu cầu sau.

Ví dụ ta giả sử rằng

M khối lượng xe 0.5 kgm khối lượng con lắc 0.2 kgb ma sát của xe 0.1 N/m/secl chiều dài tới trọng tâm con lắc 0.3 mI momen quán tính con lắc 0.006 kg*m^2F ngoại lực tác động vào xex tọa độ vị trí xetheta góc quay của con lắc

Trong ví dụ này, chúng ta sẽ thực thi 1 bộ điều khiển PID chỉ áp dụng cho hệ thống một vào-một ra(SISO), nên chúng ta cũng sẽ chỉ quan tâm tới việc điều khiển góc quay của con lắc. Do vậy, ta không

1

Page 405: Matlab Tutorial

quan tâm tới điều kiện ràng buộc nào về vị trí của xe. Chúng ta sẽ giả sử rằng hệ thống ban đầu ở vị trícân bằng, và chịu táci dụng của 1 xung lực 1N. Con lắc sẽ quay đến vị trí tận cùng trên bên phải trongvòng 5 giây và sau đó sẽ không bao giờ dịch chuyển quá0.05 rad so với phương thẳng đứng.

Các yêu cầu thiết kế đặt ra là:

Thời gian ổn định không quá 5 giây.Con lắc không bao giờ được quay quá 0.05 rad so với phương thẳng đứng.

Phân tích lực và thiết lập phương trình hệ thống

Dưới đây là hai biểu đồ Giải phóng liên kết của hệ thống.

Hệ thống trên đòi hỏi mô hình trong Simulink phải khá uyển chuyển bởi sự ràng buộc vật lý (khớp nối)giữa xe và con lắc làm cho hệ thống có 2 bậcn tự do. Cả xe và con lắc đều có 1 bậc tự do tương ứng làX và theta. Chúng ta sẽ mô hình hoá các phương trình Newton cho cả 2 bậc tự do này.

Là cần thiết khi ta đưa các lực tương tác N và P giữa xe và con lắc vào để mô hình hoá hệ thống.Tộng hợp các lực này đòi hỏi cần có phương trình động lực học theo phương x và y của con lắc theotheta. Trong phần MATLAB về ví dụ mô hình hoá con lắc các lực tương tác được giải bằng phươngpháp đại số. Tóm lại ở đay, chúng ta muốn sử dụng sức mạnh mô hình hoá của Simulink và để cho môphỏng làm các công việc tính toán đại số. Do vậy, chúng ta sẽ mô hình hoá hai phương trình theophương x và y của con lắc.

2

Page 406: Matlab Tutorial

Tuy nhiên, xp và yp là các hàm của theta. Do vậy, chúng ta có thể biểu diễn vi phân của chúng thôngqua vi phân của theta.

Biểu thức trên có thể được thay thế cho biểu thức của N và P. Thay vì tiếp tục các phép biến đổi đạisố ở đây, chúng ta sẽ biểu diễn các phương trình trên trong Simulink.

Simulink có thể tính toán trực tiếp trên các phương trình phi tuyến, do vậy chúng ta không cần tuyếntính hóa các phương trình như đã thực hiện trong phần MATLAB tutorials.

Xây dựng mô hình trong Simulink

Trước hết, chúng ta sẽ mô hình các trạng thái của hệ thống thông qua theta và x. We will representNewton's equations for the pendulum rotational inertia and the cart mass.

Mở 1 cửa sổ mô hình mới trong Simulink, sau đó chỉnh lại kích thước cho đủ (vì đây là 1 môhình rộng).Thêm 2 khối tích phân vào (từ thư viện Linear) gần phía dưới của mô hình và liên kết chúng vớinhau thành chuỗi.Vẽ 1 đường từ khối tích phân thứ 2 và đánh nhãn là "theta". (Để chèn nhãn vào, kích đúp lên vịtrí mà bạn muốn đặt.)Đánh nhãn đường nối giữa 2 khối tích phân là "d/dt(theta)".Vẽ 1 đường nối tới khối tích phân thứ hai và đánh nhãn là "d2/dt2(theta)".Thêm 1 khối Gain (từ thư viện Linear) vàp phía trái của khối tích phân thứ nhất và liên kết đầura của nó tới đường d2/dt2(theta).

3

Page 407: Matlab Tutorial

Thay giá trị hệ số của khối đó thành "1/I".Thay nhãn của khối đó thành "Pendulum Inertia" bằng cách kích đúp vào "Gain". (bạn có thểchèn thêm 1 đường mới vào nhãn bằng cách ấn return).Thêm 1 khối Sum (từ thư viện Linear) vào phía trái của khối Pendulum Inertia và nối đầu ra củanó với đầu vào của Pendulum Inertia.Thay nhãn của khối này thành Sum Torques on Pend.Xây dựng 1 loạt các khối khác giống như thế ở phía trên mô hình các nhãn "x" thay cho "theta".Khối gain có giá trị là "1/M" với nhãn là "Cart Mass", và khối Sum có nhãn là "Sum Forces onCart".Thay đổi khối Sum Forces thành "-+-" biểu thị cho các lực tác động ngang lên xe.

Bây giờ ta sẽ thêm hai lực tác dụng vào xe.

Thêm 1 khối Gain vào phía trên khối Cart Mass. Thay giá trị của nó thành "b" và đánh nhãn là"damping".Xoay khối này sang phải bằng cách kích chuột chon nó rồi chọn Flip Block từ menu Format(hoặc ấn Ctrl-F).Trích tín hiệu từ đường d/dt(x) (giữ Ctrl trong khi vẽ) and connect it to the input of the dampingblock.Connect the output of the damping block to the topmost input of the Sum Forces block. Thedamping force then has a negative sign.Insert an In block (from the Connections block library) to the left of the Sum Forces block andchange its label to "F".

4

Page 408: Matlab Tutorial

Connect the output of the F in block to the middle (positive) input of the Sum Forces block.

Now, we will apply the forces N and P to both the cart and the pendulum. These forces contributetorques to the pendulum with components "N L cos(theta) and P L sin(theta)". Therefore, we need toconstruct these components.

Insert two Elementary Math blocks (from the Nonlinear block library) and place them oneabove the other above the second theta integrator. These blocks can be used to generate simplefunctions such as sin and cos.Edit upper Math block's value to "cos" and leave the lower Math block's value "sin".Label the upper (cos) block "Vertical" and the lower (sin) block "Horizontal" to identify thecomponents.Flip each of these blocks left-to-right.Tap a line off the theta line and connect it to the input of the cos block.Tap a line of the line you just drew and connect it to the input of the sin block.Insert a Gain block to the left of the cos block and change its value to "l" (lowercase L) and itslabel to "Pend. Len."Flip this block left-to-right and connect it to the output of the cos block.Copy this block to a position to the left of the sin block. To do this, select it (by single-clicking)and select Copy from the Edit Menu and then Paste from the Edit menu (or hit Ctrl-C andCtrl-V). Then, drag it to the proper position.Connect the new Pend. Len.1 block to the output of the sin block.Draw long horizontal lines leading from both these Pend. Len. blocks and label the upper one "l

5

Page 409: Matlab Tutorial

cos(theta)" and the lower one "l sin(theta)".

Now that the pendulum components are available, we can apply the forces N and P. We will assumewe can generate these forces, and just draw them coming from nowhere for now.

Insert two Product blocks (from the Nonlinear block library) next to each other to the left andabove the Sum Torques block. These will be used to multiply the forces N and P by theirappropriate components.Rotate the left Product block 90 degrees. To do this, select it and select Rotate Block from theFormat menu (or hit Ctrl-R).Flip the other product block left-to-right and also rotate it 90 degrees.Connect the left Product block's output to the lower input of the Sum Torques block.Connect the right Product block's output to the upper input of the Sum Torques block.Continue the l cos(theta) line and attach it to the right input of the left Product block.Continue the l sin(theta) line and attach it to the right input of the right Product block.Begin drawing a line from the open input of the right product block. Extend it up and the to theright. Label the open end of this line "P".Begin drawing a line from the open input of the left product block. Extend it up and the to theright. Label the open end of this line "N".Tap a line off the N line and connect it to the open input of the Sum forces block.

6

Page 410: Matlab Tutorial

Next, we will represent the force N and P in terms of the pendulum's horizontal and verticalaccelerations from Newton's laws.

Insert a Gain block to the right of the N open ended line and change its value to "m" and itslabel to "Pend. Mass".Flip this block left-to-right and connect it's to N line.Copy this block to a position to the right of the open ended P line and attach it to the P line.Draw a line leading to the upper Pend. Mass block and label it "d2/dt2(xp)".Insert a Sum block to the right of the lower Pend. Mass block.Flip this block left-to-right and connect its output to the input of the lower Pend. Mass block.Insert a Constant block (from the Sources block library) to the right of the new Sum block,change its value to "g" and label it "Gravity".Connect the Gravity block to the upper (positive) input of the newest Sum block.Draw a line leading to the open input of the new Sum block and label it "d2/dt2(yp)".

7

Page 411: Matlab Tutorial

Now, we will begin to produce the signals which contribute to d2/dt2(xp) and d2/dt2(yp).

Insert a Sum block to the right of the d2/dt2(yp) open end.Change the Sum block's signs to "--" to represent the two terms contributing to d2/dt2(yp).Flip the Sum block left-to-right and connect it's output to the d2/dt2(yp) signal.Insert a Sum block to the right of the d2/dt2(xp) open end.Change the Sum block's signs to "++-" to represent the three terms contributing to d2/dt2(xp).Flip the Sum block left-to-right and connect it's output to the d2/dt2(xp) signal.The first term of d2/dx2(xp) is d2/dx2(x). Tap a line off the d2/dx2(x) signal and connect it tothe topmost (positive) input of the newest Sum block.

8

Page 412: Matlab Tutorial

Now, we will generate the terms d2/dt2(theta)*lsin(theta) and d2/dt2(theta)*lcos(theta).

Insert two Product blocks next to each other to the right and below the Sum block associatedwith d2/dt2(yp).Rotate the left Product block 90 degrees.Flip the other product block left-to-right and also rotate it 90 degrees.Tap a line off the l sin(theta) signal and connect it to the left input of the left Product block.Tap a line off the l cos(theta) signal and connect it to the right input of the right Product block.Tap a line off the d2/dt2(theta) signal and connect it to the right input of the left Product block.Tap a line of this new line and connect it to the left input of the right Product block.

9

Page 413: Matlab Tutorial

Now, we will generate the terms (d/dt(theta))^2*lsin(theta) and (d/dt(theta))^2*lcos(theta).

Insert two Product blocks next to each other to the right and slightly above the previous pair ofProduct blocks.Rotate the left Product block 90 degrees.Flip the other product block left-to-right and also rotate it 90 degrees.Tap a line off the l cos(theta) signal and connect it to the left input of the left Product block.Tap a line off the l sin(theta) signal and connect it to the right input of the right Product block.Insert a third Product block and insert it slightly above the d/dt(theta) line. Label this block"d/dt(theta)^2".Tap a line off the d/dt(theta) signal and connect it to the left input of the lower Product block.Tap a line of this new line and connect it to the right input of the lower Product block.Connect the output of the lower Product block to the free input of the right upper Productblock.Tap a line of this new line and connect it to the free input of the left upper Product block.

10

Page 414: Matlab Tutorial

Finally, we will connect these signals to produce the pendulum acceleration signals. In addition, wewill create the system outputs x and theta.

Connect the d2/dt2(theta)*lsin(theta) Product block's output to the lower (negative) input of thed2/dt2(yp) Sum block.Connect the d2/dt2(theta)*lcos(theta) Product block's output to the lower (negative) input ofthe d2/dt2(xp) Sum block.Connect the d/dt(theta)^2*lcos(theta) Product block's output to the upper (negative) input ofthe d2/dt2(yp) Sum block.Connect the d/dt(theta)^2*lsin(theta) Product block's output to the middle (positive) input of thed2/dt2(xp) Sum block.Insert an Out block (from the Connections block library) attached to the theta signal. Label thisblock "Theta".Insert an Out block attached to the x signal. Label this block "x". It should automatically benumbered 2.

11

Page 415: Matlab Tutorial

Now, save this model as pend.mdl.

Open-loop response

To generate the open-loop response, it is necessary to contain this model in a subsystem block.

Create a new model window (select New from the File menu in Simulink or hit Ctrl-N).Insert a Subsystem block from the Connections block library.Open the Subsystem block by double clicking on it. You will see a new model window labeled"Subsystem".Open your previous model window named pend.mdl. Select all of the model components byselecting Select All from the Edit menu (or hit Ctrl-A).Copy the model into the paste buffer by selecting Copy from the Edit menu (or hit Ctrl-C).Paste the model into the Subsystem window by selecting Paste from the Edit menu (or hitCtrl-V) in the Subsystem windowClose the Subsystem window. You will see the Subsystem block in the untitled window with oneinput terminal labeled F and two output terminals labeled Theta and x.Resize the Subsystem block to make the labels visible by selecting it and dragging one of thecorners.Label the Subsystem block "Inverted Pendulum".

12

Page 416: Matlab Tutorial

Now, we will apply a unit impulse force input, and view the pendulum angle and cart position. Animpulse can not be exactly simulated, since it is an infinite signal for an infinitesimal time with timeintegral equal to 1. Instead, we will use a pulse generator to generate a large but finite pulse for a smallbut finite time. The magnitude of the pulse times the length of the pulse will equal 1.

Insert a Pulse Generator block from the Sources block library and connect it to the F input ofthe Inverted Pendulum block.Insert a Scope block (from the Sinks block library) and connect it to the Theta output of theInverted Pendulum block.Insert a Scope block and connect it to the x output of the Inverted Pendulum block.Edit the Pulse Generator block by double clicking on it. You will see the following dialog box.

Change the Period value to "10" (a long time between a chain of impulses - we will beinterested in only the first pulse).Change the Duty Cycle value to ".01" this corresponds to .01% of 10 seconds, or .001 seconds.Change the Amplitude to 1000. 1000 times .001 equals 1, providing an approximate unitimpulse.Close this dialog box. You system will appear as shown below.

13

Page 417: Matlab Tutorial

We now need to set an appropriate simulation time to view the response.

Select Parameters from the Simulation menu.Change the Stop Time value to 2 seconds.Close this dialog box

You can download a version of the system here. Before running it, it is necessary to set the physicalconstants. Enter the following commands at the MATLAB prompt.

M = .5; m = 0.2; b = 0.1; i = 0.006; g = 9.8; l = 0.3;

Now, start the simulation (select Start from the Simulation menu or hit Ctrl-t). If you look at theMATLAB prompt, you will see some error messages concerning algebraic loops. Due to the algebraicconstraint in this system, there are closed loops in the model with no dynamics which must be resolvedcompletely at each time step before dynamics are considered. In general, this is not a problem, butoften algebraic loops slow down the simulation, and can cause real problems if discontinuities existwithin the loop (such as saturation, sign functions, etc.)

Open both Scopes and hit the autoscale buttons. You will see the following for theta (left) and x(right).

14

Page 418: Matlab Tutorial

Notice that the pendulum swings all the way around due to the impact, and the cart travels along witha jerky motion due to the pendulum. These simulations differ greatly from the MATLAB open loopsimulations because Simulink allows for fully nonlinear systems.

Extracting the linearized model into MATLAB

Since MATLAB can't deal with nonlinear systems directly, we cannot extract the exact model fromSimulink into MATLAB. However, a linearized model can be extracted. This is done through the use ofIn and Out Connection blocks and the MATLAB function linmod. In the case of this example, will usethe equivalent command linmod2, which can better handle the numerical difficulties of this problem.

To extract a model, it is necessary to start with a model file with inputs and outputs defined as In andOut blocks. Earlier in this tutorial this was done, and the file was saved as pend.mdl. In this model,one input, F (the force on the cart) and two outputs, theta (pendulum angle from vertical) and x(position of the cart), were defined. When linearizing a model, it is necessary to choose an operatingpoint about which to linearize. By default, the linmod2 command linearizes about a state vector ofzero and zero input. Since this is the point about which we would like to linearize, we do not need tospecify any extra arguments in the command. Since the system has two outputs, we will generate twotransfer functions.

At the MATLAB prompt, enter the following commands

[A,B,C,D]=linmod2('pend') [nums,den]=ss2tf(A,B,C,D) numtheta=nums(1,:) numx=nums(2,:)

You will see the following output (along with algebraic loop error messages) providing a state-spacemodel, two transfer function numerators, and one transfer function denominator (both transferfunctions share the same denominator).

A =

0 0 1.0000 0 0 0 0 1.0000 31.1818 0.0000 0.0000 -0.4545 2.6727 0.0000 0.0000 -0.1818

15

Page 419: Matlab Tutorial

B =

0 0 4.5455 1.8182

C =

1 0 0 0 0 1 0 0

D =

0 0

nums =

0 0.0000 4.5455 0.0000 0.0000 0 0.0000 1.8182 0.0000 -44.5455

den =

1.0000 0.1818 -31.1818 -4.4545 0.0000

numtheta =

0 0.0000 4.5455 0.0000 0.0000

numx =

0 0.0000 1.8182 0.0000 -44.5455

To verify the model, we will generate an open-loop response. At the MATLAB command line, enter thefollowing commands.

t=0:0.01:5; impulse(numtheta,den,t); axis([0 1 0 60]);

You should get the following response for the angle of the pendulum.

16

Page 420: Matlab Tutorial

Note that this is identical to the impulse response obtained in the MATLAB tutorial pendulum modelingexample. Since it is a linearized model, however, it is not the same as the fully-nonlinear impulseresponse obtained in Simulink.

Implementing PID control

In the pendulum PID control example, a PID controller was designed with proportional, integral, andderivative gains equal to 100, 1, and 20, respectively. To implement this, we will start with ouropen-loop model of the inverted pendulum. And add in both a control input and the disturbanceimpulse input to the plant.

Open your Simulink model window you used to obtain the nonlinear open-loop response.(pendol.mdl)Delete the line connecting the Pulse Generator block to the Inverted Pendulum block.(single-click on the line and select Cut from the Edit menu or hit Ctrl-X).Move the Pulse Generator block to the upper left of the window.Insert a Sum block to the left of the Inverted Pendulum block.Connect the output of the Sum block to the Inverted Pendulum block.Connect the Pulse generator to the upper (positive) input of the Sum block.

17

Page 421: Matlab Tutorial

Now, we will feed back the angle output.

Insert a Sum block to the right and below the Pulse Generator block.Change the signs of the Sum block to "+-".Insert a Constant block (from the Sources block library) below the Pulse generator. Change itsvalue to "0". This is the reference input.Connect the constant block to the upper (positive) input of the second Sum block.Tap a line off the Theta output of the Inverted Pendulum block and draw it down and to the left.Extend this line and connect it to the lower (negative) input of the second Sum block.

Now, we will insert a PID controller.

Double-click on the Blocksets & Toolboxes icon in the main Simulink window. This will open anew window with two icons.In this new window, double-click on the SIMULINK extras icon. This will open a window withicons similar to the main Simulink window.Double-click on the Additional Linear block library icon. This will bring up a library of Linearblocks to augment the standard Linear block library.Drag a PID Controller block into your model between the two Sum blocks.Connect the output of the second Sum block to the input of the PID block.Connect the PID output to the first Sum block's free input.

18

Page 422: Matlab Tutorial

Edit the PID block by doubleclicking on it.Change the Proportional gain to 100, leave the Integral gain 1, and change the Derivative gainto 20.Close this window.

You can download our version of the closed-loop system here

Closed-loop response

We can now simulate the closed-loop system. Be sure the physical parameters are set (if you just ranthe open-loop response, they should still be set.) Start the simulation, double-click on the Theta scopeand hit the autoscale button. You should see the following response:

19

Page 423: Matlab Tutorial

This is identical to the closed-loop response obtained in the MATLAB tutorials. Note that the PIDcontroller handles the nonlinear system very well because the angle is very small (.04 radians).

Simulink ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Inverted Pendulum ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

20

Page 424: Matlab Tutorial

Example: Modeling a Pitch Controller in SimulinkPhysical setup and system equationsBuilding the State-Space ModelOpen-loop responseExtracting the model into MATLABBuilding a full-state feedback controllerClosed-loop response

Physical setup and system equations

The equations governing the motion of an aircraft are a very complicated set of six non-linear coupleddifferential equations. However, under certain assumptions, they can be decoupled and linearized intothe longitudinal and lateral equations. Pitch control is a longitudinal problem, and in this example, wewill design an autopilot that controls the pitch of an aircraft. In this example, we will begin with thelinearized state-space equation model which was obtained in the MATLAB Tutorials: pitch controlexample This model, with numerical values substituted in, is as follows:

in state-space form, the equations are as follows:

Which can be written as:

Building the state-space model

We will model these state equations explicitly in Simulink taking advantage of vector lines to carry the

1

Page 425: Matlab Tutorial

state vector signal X. Vector lines are produced automatically in Simulink when blocks input or outputvector signals. First, we will represent the derivative of the state.

Open a new model window in Simulink.Insert an Integrator block from the Linear block library.Draw a line from the output of the Integrator and label it "X". To label a line, double click nearthe line where you want the label to appear.Draw a line leading to the input of the Integrator and label it "d/dt(X)"

Now, we will represent the first state equation, which is d/dt(X)=Ax+Bu.

Insert a Matrix Gain block from the Linear block library below the integrator.Flip this block left-to-right. To do this, select it with the mouse (single-click) and select FlipBlock from the Format menu (or hit Ctrl-F).Edit the Matrix Gain block (by double clicking). Change the Gain Matrix field to "A" (which wewill define later in MATLAB) and close the dialog box.Change the label of this block from Matrix Gain to "A" by single clicking on the existing label.Tap a line off the state signal, X (hold Ctrl while drawing the line to tap) and connect it to theinput of the A block. This creates the signal Ax.Insert a Sum block (from the Linear block library) to the left of the integrator and connect it'soutput to the line leading to the Integrator's input.Draw a line from the output of the A matrix block to the lower (positive) input of the Sumblock.Insert another Matrix Gain block to the left of the Sum block. Change it's Matrix Gain value to"B" and change it's label to "B".Connect the B matrix output to the other (positive) input of the Sum block.Draw a line leading to the input of the Sum block. This is the input signal, u.

2

Page 426: Matlab Tutorial

Now we will form the output signal which is equal to Cx+Du.

Insert a Matrix Gain block to the right of the integrator and attach the integrator's output to theinput of the Matrix Gain.Change the Matrix Gain value to "C" and change it's label to "C".Insert another Matrix Gain block below the "C" block, and change both it's value and label to"D".Tap a line off the u signal (the input line of the B matrix block) and attach it to the input of the"D" matrix block.Insert a Sum block to the right of the C matrix block.Connect the outputs of the C and D matrix blocks to the inputs of the Sum block.

Next, we will apply inputs and extract outputs from this system. We will use In and Out blocks for thispurpose. These blocks allow the system to be extracted into MATLAB and they allow the system to beplaced into a Subsystem block for use within another model.

Insert an In block (from the Connections block library) and connect it to the open line whichconnects to the input of the B matrix block.Change the label of the In block to "deltac" (corresponding to the angle of the elevator).Insert an Out block (from the Connections block library) and connect it to the output of therightmost Sum block.Change the label of this Out block to "theta" (corresponding to the pitch angle of the plane).Insert an Out block above the Theta block, and change it's label to "X" corresponding to thestate vector of the system. (This will be used later to implement full-state feedback.Tap a line off the X signal (leading from the second integrator) and connect it to the X Outblock.

3

Page 427: Matlab Tutorial

Save this model as "pitch.mdl" (or download ours here.)

Open-loop response

To generate the open-loop response, it is first necessary to contain this model in a subsystem block.

Create a new model window (select New from the File menu in Simulink or hit Ctrl-N).Insert a Subsystem block from the Connections block library.Open the Subsystem block by double clicking on it. You will see a new model window labeled"Subsystem".Open your previous model window named pitch.mdl. Select all of the model components byselecting Select All from the Edit menu (or hit Ctrl-A).Copy the model into the paste buffer by selecting Copy from the Edit menu (or hit Ctrl-C).Paste the model into the Subsystem window by selecting Paste from the Edit menu (or hitCtrl-V) in the Subsystem windowClose the Subsystem window. You will see the Subsystem block in the untitled window with oneinput terminal labeled deltac and two output terminals labeled theta and x.Resize the Subsystem block to make the labels visible by selecting it and dragging one of thecorners.Label the Subsystem block "Plane Pitch Model".

Insert a Step block (from the Sources block library) and connect it to the input of the PlanePitch Model.Edit the Step block (by double clicking on it to bring up the dialog box) and change the StepTime value to 0. Close the Step block dialog box.Insert a Scope block (from the Sinks block library) and connect it to the theta output of thePlane Pitch Model.

4

Page 428: Matlab Tutorial

Before obtaining a step response, we must set the constants in the matrices A, B, C, and D. Enter thefollowing commands at the MATLAB prompt.

A=[-0.313 56.7 0; -0.0139 -0.426 0; 0 56.7 0];B=[0.232; 0.0203; 0];C=[0 0 1];D=[0];

We are now ready to run the simulation. If you like, you can download our version of the open-loopsystem here. Start the simulation by selecting Start from the Simulation menu (or hit Ctrl-t). When thesimulation is finished, open the Scope by double clicking on it and hit the Scope's autoscale button.You will see the following response.

Extracting the model into MATLAB

The Simulink model can be extracted into an equivalent state-space model in MATLAB. This is donethrough the use of In and Out Connection blocks and the MATLAB function linmod.

To extract a model, it is necessary to start with a model file with inputs and outputs defined as In andOut blocks. Earlier in this tutorial this was done, and the file was saved as pitch.mdl. In this model,one input, deltac (the elevator angle) and two outputs, theta (pitch angle) and X (the state vector),were defined. We must truncate the output and feedthrough matrices (Co and Do) to provide only thefirst input.

At the MATLAB prompt, enter the following commands

[Ao,Bo,Co,Do]=linmod('pitch');

5

Page 429: Matlab Tutorial

Ao Bo Co=Co(1,:) Do=Do(1,:)

You will see the following output providing the open-loop model of the system.

Ao =

-0.3130 56.7000 0 -0.0139 -0.4260 0 0 56.7000 0

Bo =

0.2320 0.0203 0

Co =

0 0 1

Do =

0

Note that the matrices Ao, Bo, Co, and Do are the same at the original matrices A, B,C, and D.

Building a full-state feedback controller

In the CTMS Example: Pitch Controller -- State Space Method page, a full-state feedback controllerwas designed using the LQR method. We will now construct this controller in Simulink.

Bring up your open-loop Pitch model window (or download ours here)Insert a Matrix Gain block below the Plane Pitch Model and change both its Matrix Gain valueand it's label to "K".Flip the K matrix block left-to-right.Insert a Sum block to the left of the Plane Pitch Model and change it's value to "+-".Connect the state vector X output of the Plane Pitch Model to the input of the K matrix block.Connect the output of the K matrix block to the second (negative) input of the Sum block.Connect the Step block to the first (positive) input of the Sum block.Connect the Sum block's output to the input of the Plane Pitch Model.

6

Page 430: Matlab Tutorial

You can download our version of the closed-loop model here.

Closed-loop response

Before simulating the closed-loop system, we must first determine the gain matrix K using the LQRmethod. Execute the following commands at the MATLAB prompt.

p=50; Q=[0 0 0; 0 0 0; 0 0 p]; [K]= lqr (A,B,Q,1)

Start the simulation in Simulink. Open the scope window and hit the Autoscale button. You should seethe following response.

Simulink ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Pitch Controller ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

Tutorials

7

Page 431: Matlab Tutorial

MATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

8

Page 432: Matlab Tutorial

Example: Modeling the Ball and Beam Experimentin Simulink

Problem Setup and System EquationsBuilding the Simulink ModelOpen-Loop ResponseExtracting the Model into MATLABConstructing a Lead Compensator ControllerClosed-Loop Response

Problem Setup

A ball is placed on a beam, see figure below, where it is allowed to roll with 1 degree of freedom alongthe length of the beam. A lever arm is attached to the beam at one end and a servo gear at the other.As the servo gear turns by an angle theta, the lever changes the angle of the beam by alpha. When theangle is changed from the horizontal position, gravity causes the ball to roll along the beam. Acontroller will be designed for this system so that the ball's position can be manipulated.

For this problem, we will assume that the ball rolls without slipping and friction between the beam andball is negligible. The constants and variab for this example are defined as follows:

M mass of the ball 0.11 kgR radius of the ball 0.015 md lever arm offset 0.03 mg gravitational acceleration 9.8 m/s^2L length of the beam 1.0 m

1

Page 433: Matlab Tutorial

J ball's moment of inertia 9.99e-6 kgm^2r ball position coordinatealpha beam angle coordinatetheta servo gear angle

The design criteria for this problem are:

Settling time less than 3 secondsOvershoot less than 5%

The second derivative of the input angle alpha actually affects the second derivative of r. However,we will ignore this contribution. The Lagrangian equation of motion for the ball is then given by thefollowing:

The beam angle (alpha) can be expressed in terms of the angle of the gear (theta).

Building the Model in Simulink

In this example, rather than express all the forces and geometric constraints (which is difficult tomodel in Simulink for dynamic systems with constraints) we will model the nonlinear Lagrangianequation of motion directly. This equation gives d/dt(r) as a function of the state and input variab, r,d/dt(r), alpha, and d/dt(alpha). We will make use of the Nonlinear Function Block to express thisfunction. First, we must express the derivatives of the output, r.

Open a new model window in Simulink.Insert an Integrator block from the Linear block library.Insert a second Integrator to the right of the first, and connect the two with a line.Label the line connecting the two "d/dt(r)". To label a line, double-click near the line where youwant the label (in this case, just below the line)Draw a line from the second Integrator and label it "r".Insert an Out block from the Connections block library and connect it to the "r" signal line. Thiswill form the output of the system.Change the label of the Out block to "r" by single-clicking on the existing "Out" label.

2

Page 434: Matlab Tutorial

Now, we will insert the function which takes the vector [r d/dt(r) alpha d/dt(alpha)] and returnsd/dt(r).

Insert a Fcn block from the Nonlinear library and connect its output to the input of the firstIntegrator.Edit the Fcn block by double clicking it, and change it's function to the following:

(-1/(J/(R^2)+m))*(m*g*sin(u[3])-m*u[1]*(u[4])^2)

This function block takes an input vector, u, where each component is referred to as u[1], u[2],etc. In our case, u[1]=r, u[2]=d/dt(r), u[3]=alpha, and u[4]=d/dt(alpha).

Close the dialog box and change the label of the Fcn block to "Ball-Beam Lagrangian Model"(you can add newlines in the label by hitting return).

Now, we will begin to construct the function input vector u by feeding back the state signals from theintegrators and forming a vector from them with a Mux block.

Insert a Mux block from the Connections block library and connect its output to the input of theBall-Beam block.Edit the Mux block (by double-clicking on it) and change its number of inputs to 4. The Muxblock should now have four inputs.Tap a line off the d/dt(r) signal (hold Ctrl while drawing) and connect it to the second input ofthe Mux block.

3

Page 435: Matlab Tutorial

Tap a line of the r signal and connect it to the first input of the Mux block.

Now we will construct the signals alpha and d/dt(alpha) from the input theta.

Insert an In block on the left side of your model window. Change its label to "theta".Insert a Gain block and connect it to the theta block. Change its gain value (double-click on it)to "d/L".Connect the output of the gain block to the third input of the Mux block. Label this line "alpha".Insert a Derivative block from the Linear block library and place it underneath the alpha signalline.Tap a line off the output of the Gain block and connect it to the input of the Derivative block.Connect the output of the Derivative block to the fourth input off the Mux block.

Save your model as "ball.mdl". You can download ours here. Open Loop Response To generate theopen-loop response, it is first necessary to contain this model in a subsystem block.

Create a new model window (select New from the File menu in Simulink or hit Ctrl-N).Insert a Subsystem block from the Connections block library.Open the Subsystem block by double clicking on it. You will see a new model window labeled"Subsystem".Open your previous model window named ball.mdl. Select all of the model components byselecting Select All from the Edit menu (or hit Ctrl-A).Copy the model into the paste buffer by selecting Copy from the Edit menu (or hit Ctrl-C).Paste the model into the Subsystem window by selecting Paste from the Edit menu (or hitCtrl-V) in the Subsystem windowClose the Subsystem window. You will see the Subsystem block in the untitled window with oneinput terminal labeled theta and one output terminal labeled r.Resize the Subsystem block to make the labels visible by selecting it and dragging one of thecorners.Label the Subsystem block "Ball and Beam Model".

4

Page 436: Matlab Tutorial

Insert a Step block (from the Sources block library) and connect it to the input of the Ball andBeam Model.Edit the Step block (by double clicking on it to bring up the dialog box) and change the StepTime value to 0. Close the Step block dialog box.Insert a Scope block (from the Sinks block library) and connect it to the output of the Ball andBeam Model.

Before obtaining a step response, we must set the physical parameters Enter the following commandsat the MATLAB prompt.

m = 0.111; R = 0.015; g = -9.8; L = 1.0; d = 0.03; J = 9.99e-6;

We are now ready to run the simulation. If you like, you can download our version of the open-loopsystem here. Start the simulation by selecting Start from the Simulation menu (or hit Ctrl-t). When thesimulation is finished, open the Scope by double clicking on it and hit the Scope's autoscale button.You will see the following response.

5

Page 437: Matlab Tutorial

From this plot it is clear that the system is unstable in open-loop causing the ball to roll right off theend of the beam. Therefore, some method of controlling the ball's position in this system is required.Later in this tutorial, we will implement a lead compensator.

Extracting the Model into MATLAB

The Simulink model can be extracted into an equivalent state-space or transfer function model inMATLAB. This is done through the use of In and Out Connection blocks and the MATLAB functionlinmod.

To extract a model, it is necessary to start with a model file with inputs and outputs defined as In andOut blocks. Earlier in this tutorial this was done, and the file was saved as ball.mdl. In this model, oneinput, theta (the input crank angle) and one output, r (ball position), were defined.

At the MATLAB prompt, enter the following commands

[A,B,C,D]=linmod('ball') [num,den]=ss2tf(A,B,C,D)

You will see the following output providing the open-loop model of the system.

A =

0 1 0 0

B =

0 0.2100

C =

1 0

D =

0

6

Page 438: Matlab Tutorial

num =

0 0 0.2100

den =

1 0 0

We can verify this model by obtaining an open-loop step response. Enter the following command atthe MATLAB prompt:

step(num,den);

You will see the following open-loop response:

Building a Lead Compensator Controller

In the CTMS Example: Solution to the Ball & Beam Problem Using Root Locus Method a leadcompensator was designed with a zero at -0.01 and a pole at -5, with a gain of 37.1. We will nowconstruct this controller in Simulink.

Bring up your open-loop Ball and Beam model window (or download ours here)Delete the line which connects the Step block to the Ball and Beam model block.Insert a Transfer Function block from the linear block library to the left of the Ball and Beamblock, and connect its output to the input of the Ball and Beam block.Edit the Transfer Function block and change its numerator to "[1 0.01]" and its denominator to"[1 5]".Change the label of the Transfer Function block to "Lead Compensator".Insert a Gain block to the left of the Lead Compensator and connect its output to the Leadcompensator's input.Change the Gain value to "37.1".Insert a Sum block to the left of the Gain block and change it's value to "+-". Connect the

7

Page 439: Matlab Tutorial

output of the Sum to the input of the Gain block.Tap a line off the output of the Ball and Beam model and connect it to the negative input of theSum.Connect the Step block to the positive input of the Sum block

You can download our version of the closed-loop model here.

Closed-Loop Response

Start the simulation in Simulink. Open the scope window and hit the Autoscale button. You should seethe following response.

Simulink ExamplesCruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum | PitchController | Ball and Beam

Ball and Beam ExamplesModeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Simulink

TutorialsMATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State Space |Digital Control | Simulink Basics | Simulink Modeling | Examples

8