Monday, September 19, 2011

DC Motor Speed Modeling in Matlab


DC Motor Speed Modeling in Matlab


DC MOTOR MODELLING

A common actuator in control systems is the DC motor. It directly provides rotary motion and, coupled with wheels or drums and cables, can provide transitional motion. The electric circuit of the armature and the free body diagram of the rotor are shown in the following figure:

For this example, we will assume the following values for the physical parameters.

  • moment of inertia of the rotor (J) = 0.01 kg.m^2/s^2
  • damping ratio of the mechanical system (b) = 0.1 Nms
  • electromotive force constant (K=Ke=Kt) = 0.01 Nm/Amp
  • electric resistance (R) = 1 ohm 
  • electric inductance (L) = 0.5 H
  •  input (V): Source Voltage


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


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



Next, we will start to modelling with Newton's law and Kirchoff's law. These laws applied to the motor system give the following equations:




The transfer function of the model is derived as follows:



The denominator and numerator is given by:


MATLAB representation:

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);
step(motor,0:0.1:10);
title('Step Response for the Open Loop System');
xlabel('Time in s')
ylabel('Speed in rad/s')
The response of the system as shown in figure:
PID controller Design: 

The PID controller tuning is done manually by changing the Kp, Ki and Kd values. 
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);

Kp=100;
Ki=100;
Kd=10;
PID=tf([Kd Kp Ki],[1 0]); 
sys_closed=feedback(PID*motor,1);
step(sys_closed)
title('Closed loop response')

The closed loop response is given by the


Tune the parameters and find out the better response.




Sunday, September 18, 2011

Conditional Control


Conditional Control — if, else, switch

Conditional statements enable you to select at run time which block of code to execute. The simplest conditional statement is an if statement. For example:
% Generate a random number
a = randi(100, 1);

% If it is even, divide by 2
if rem(a, 2) == 0
    disp('a is even')
    b = a/2;
end
if statements can include alternate choices, using the optional keywords elseif or else. For example:
a = randi(100, 1);

if a < 30
    disp('small')
elseif a < 80
    disp('medium')
else
    disp('large')
end
Alternatively, when you want to test for equality against a set of known values, use a switch statement. For example:
[dayNum, dayString] = weekday(date, 'long', 'en_US');

switch dayString
   case 'Monday'
      disp('Start of the work week')
   case 'Tuesday'
      disp('Day 2')
   case 'Wednesday'
      disp('Day 3')
   case 'Thursday'
      disp('Day 4')
   case 'Friday'
      disp('Last day of the work week')
   otherwise
      disp('Weekend!')
end
For both if and switch, MATLAB executes the code corresponding to the first true condition, and then exits the code block. Each conditional statement requires the end keyword.
In general, when you have many possible discrete, known values, switch statements are easier to read than if statements. However, you cannot test for inequality between switch and case values. For example, you cannot implement this type of condition with a switch:
yourNumber = input('Enter a number: ');

if yourNumber < 0
    disp('Negative')
elseif yourNumber > 0
    disp('Positive')
else
    disp('Zero')
end

Array Comparisons in Conditional Statements

It is important to understand how relational operators and if statements work with matrices. When you want to check for equality between two variables, you might use
if A == B, ...
This is valid MATLAB code, and does what you expect when A and B are scalars. But when A and B are matrices, A == B does not test if they are equal, it tests where they are equal; the result is another matrix of 0's and 1's showing element-by-element equality. (In fact, if A and B are not the same size, then A == B is an error.)
A = magic(4);     B = A;     B(1,1) = 0;

A == B
ans =
     0     1     1     1
     1     1     1     1
     1     1     1     1
     1     1     1     1
The proper way to check for equality between two variables is to use the isequal function:
if isequal(A, B), ...
isequal returns a scalar logical value of 1 (representing true) or 0 (false), instead of a matrix, as the expression to be evaluated by the if function. Using the A and B matrices from above, you get
isequal(A, B)
ans = 
    0
Here is another example to emphasize this point. If A and B are scalars, the following program will never reach the "unexpected situation". But for most pairs of matrices, including our magic squares with interchanged columns, none of the matrix conditions A > B, A < B, or A == B is true for all elements and so the else clause is executed:
if A > B
   'greater'
elseif A < B
   'less'
elseif A == B
   'equal'
else
   error('Unexpected situation')
end
Several functions are helpful for reducing the results of matrix comparisons to scalar conditions for use with if, including
isequal
isempty
all
any

Global Variables


Global Variables

If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the functions. Do the same thing at the command line if you want the base workspace to access the variable. The global declaration must occur before the variable is actually used in a function. Although it is not required, using capital letters for the names of global variables helps distinguish them from other variables. For example, create a new function in a file called falling.m:
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
Then interactively enter the statements
global GRAVITY
GRAVITY = 32;
y = falling((0:.1:5)');
The two global statements make the value assigned to GRAVITY at the command prompt available inside the function. You can then modify GRAVITY interactively and obtain new solutions without editing any files.

Useful functions and operations in Matlab


Useful functions and operations in Matlab

Using Matlab as a calculator is easy.
Example: Compute 5 sin(2.53-pi)+1/75. In Matlab this is done by simply typing
5*sin(2.5^(3-pi))+1/75
at the prompt. Be careful with parantheses and don't forget to type * whenever you multiply!
Note that Matlab is case sensitive. This means that Matlab knows a difference between letters written as lower and upper case letters. For example, Matlab will understand sin(2) but will not understand Sin(2).
Here is a table of useful operations, functions and constants in Matlab.
Operation, function or constantMatlab
command
+ (addition)+
- (subtraction)-
× (multiplication)*
/ (division)/
|x| (absolute value of x)abs(x)
square root of xsqrt(x)
exexp(x)
ln x (natural log)log(x)
log10 x (base 10 log)log10(x)
sin xsin(x)
cos xcos(x)
tan xtan(x)
cot xcot(x)
arcsin xasin(x)
arccos xacos(x)
arctan xatan(x)
arccot xacot(x)
n! (n factorial)gamma(n+1)
e (2.71828...)exp(1)
 3.14159265...pi
i   (imaginary unit, sqrt(-1))i

Loops in Matlab


LOOPS

In this tutorial we will demonstrate how the for and the while loop are used. First, the for loop is discussed with examples for row operations on matrices and for Euler's Method to approximate an ODE. Following the for loop, a demonstration of the while loop is given. 

For Loops

The for loop allows us to repeat certain commands. If you want to repeat some action in a predetermined way, you can use the for loop. All of the loop structures in matlab are started with a keyword such as "for", or "while" and they all end with the word "end". Another deep thought, eh. The for loop is written around some set of statements, and you must tell Matlab where to start and where to end. Basically, you give a vector in the "for" statement, and Matlab will loop through for each value in the vector: For example, a simple loop will go around four times each time changing a loop variable, j:
>> for j=1:4,
   j
end


j =

     1


j =

     2


j =

     3


j =

     4

>>
When Matlab reads the "for" statement it constructs a vector, [1:4], and j will take on each value within the vector in order. Once Matlab reads the "end" statement, it will execute and repeat the loop. Each time the for statement will update the value of j and repeat the statements within the loop. In this example it will print out the value of j each time. For another example, we define a vector and later change the entries. Here we step though and change each individual entry:
>> v = [1:3:10]

v =

     1     4     7    10

>> for j=1:4,
     v(j) = j;
end
>> v

v =

     1     2     3     4

Note, that this is a simple example and is a nice demonstration to show you how a for loop works. 
A better example, is one in which we want to perform operations on the rows of a matrix. If you want to start at the second row of a matrix and subtract the previous row of the matrix and then repeat this operation on the following rows, a for loop can do this in short order:
>> A = [ [1 2 3]' [3 2 1]' [2 1 3]']

A =

     1     3     2
     2     2     1
     3     1     3

>> B = A;
>> for j=2:3,
    A(j,:) = A(j,:) - A(j-1,:)
end

A =

     1     3     2
     1    -1    -1
     3     1     3


A =

     1     3     2
     1    -1    -1
     2     2     4

For a more realistic example, since we can now use loops and perform row operations on a matrix, Gaussian Elimination can be performed using only two loops and one statement:
>> for j=2:3,
     for i=j:3,
        B(i,:) = B(i,:) - B(j-1,:)*B(i,j-1)/B(j-1,j-1)
     end
   end

B =

     1     3     2
     0    -4    -3
     3     1     3


B =

     1     3     2
     0    -4    -3
     0    -8    -3


B =

     1     3     2
     0    -4    -3
     0     0     3



Another example where loops come in handy is the approximation of differential equations. The following example approximates the D.E. y'=x^2-y^2, y(0)=1, using Euler's Method. First, the step size, h, is defined. Once done, the grid points are found, and an approximation is found. The approximation is simply a vector, y, in which the entry y(j) is the approximation at x(j).
>> h = 0.1;
>> x = [0:h:2];
>> y = 0*x;
>> y(1) = 1;
>> size(x)

ans =

     1    21

>> for i=2:21,
    y(i) = y(i-1) + h*(x(i-1)^2 - y(i-1)^2);
   end
>> plot(x,y)
>> plot(x,y,'go')
>> plot(x,y,'go',x,y)

While Loops

If you don't like the for loop, you can also use a while loop. The while loop repeats a sequence of commands as long as some condition is met. This can make for a more efficient algorithm. In the previous example the number of time steps to make may be much larger than 20. In such a case the for loop can use up a lot of memory just creating the vector used for the index. A better way of implementing the algorithm is to repeat the same operations but only as long as the number of steps taken is below some threshold. In this example the D.E. y'=x-|y|, y(0)=1, is approximated using Euler's Method:
>> h = 0.001;
>> x = [0:h:2];
>> y = 0*x;
>> y(1) = 1;
>> i = 1;
>> size(x)

ans =

           1        2001

>> max(size(x))

ans =

        2001

>> while(i<max(size(x)))
     y(i+1) = y(i) + h*(x(i)-abs(y(i)));
     i = i + 1;                         
   end
>> plot(x,y,'go')

POLYNOMIALS


POLYNOMIALS

In MATLAB, a polynomial is represented by a vector. To create a polynomial in MATLAB, simply enter each coefficient of the polynomial into the vector in descending order. For instance, let's say you have the following polynomial:
To enter this into MATLAB, just enter it as a vector in the following manner
    x = [1 3 -15 -2 9]
    
         x =
              1  3  -15  -2  9
    
MATLAB can interpret a vector of length n+1 as an nth order polynomial. Thus, if your polynomial is missing any coefficients, you must enter zeros in the appropriate place in the vector. For example,
would be represented in MATLAB as:
    y = [1 0 0 0 1]
    
You can find the value of a polynomial using the polyval function. For example, to find the value of the above polynomial at s=2,
    z = polyval([1 0 0 0 1],2)
    
         z =
              17
    
You can also extract the roots of a polynomial. This is useful when you have a high-order polynomial such as
Finding the roots would be as easy as entering the following command;
    roots([1 3 -15 -2 9])
            
    
         ans =
            -5.5745
             2.5836
            -0.7951
             0.7860
    
Let's say you want to multiply two polynomials together. The product of two polynomials is found by taking the convolution of their coefficients. MATLAB's function conv that will do this for you.
    x = [1 2];
    y = [1 4 8];
    z = conv(x,y)
    
         z =
              1  6  16  16
    
Dividing two polynomials is just as easy. The deconv function will return the remainder as well as the result. Let's divide z by y and see if we get x.
    [xx, R] = deconv(z,y)
    
         xx =
              1  2
    
         R =
              0  0  0  0
    
As you can see, this is just the polynomial/vector x from before. If y had not gone into z evenly, the remainder vector would have been something other than zero.

Plots in Matlab


Plots:
It is also easy to create plots in MATLAB.
y = f(x), and then plot the set points (xi, yi). By default matlab draws a straight line connecting neighboring points, The basic method for plotting a function f(x) in matlab is to create an array of x values, calculate a second array while the points themselves are invisible.
x1 = [0:0.25:4*pi]; % creates an array from 0 to 4*pi with a spacing of 0.25
x2 = linspace(0,4*pi,1000); % creates an array from 0 to 4*pi with 1000 evenly spaced points
y1 = 5*sin(x1).*cos(x1).^2; % calculate y = f(x)
y2 = 5*sin(x2).*cos(x2).^2; % note the use of the element-by-element operations .* .^ ./
plot(x1,y1);
hold on;
plot(x2,y2,’color’,’g’,’LineStyle’,’--’),’LineWidth’,2);
hold off;