Dspaceinsimulink PDF
Dspaceinsimulink PDF
Dspaceinsimulink PDF
INTRODUCTION TO
MATLAB, SIMULINK,
AND
DSPACE
Comments: This document is strongly complimented by a series of video tutorials produced by Math Works, the parent company of MatLab and Simulink. These tutorials can be found online at: http://www.mathworks.com/academia/student_center/tutorials/index. html?link=body Comments in the left margin will direct you to the appropriate videos or other references for each lesson. Activities are provided for the lessons so that you can test your understanding of the concepts presented. A writing icon indicates that you should record your work and turn it in to your TA for grading.
Aside: When opening MatLab in the ME 421 Lab the following windows will open: Select dSPACE RTI Platform Support Select RTI1104 RTI Unsuitable Configuration Preferences Select Set Preferences Automatically
Slides 1-13
The layout of the MatLab desktop may be different from that in the tutorial but all of the windows discussed can be found.
Activity 1:
1. Create a folder to store your work 2. Open MatLab 3. Change directories to your new folder
ME 421 Lab 1 Page 1 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
MATLAB Fundamentals
Slides 16-25
Help in MatLab - doc opens MatLab documentation, doc command gives specific information about a specific command - help command gives information about the command in the command window - There are many online sources of information about MatLab. - There is more information in MathWorks video tutorials. - There are also text tutorials and forums on the MathWorks site. Variables: - All variables are arrays and can have a variety of dimensions. - Variables are double (16 digits of data) by default though they only display 5 (this can be changed using short/long commands) - Variables are created by assigning value on right of the equal sign to the variable name on the left. - Variable names must start with a letter but can contain letters, numbers, and underscores. They are case sensitive. Aside: Avoid assigning variables names that already have meaning in MatLab. To find out if your variable name (vname) has a meaning in MatLab use help vname.
ME 421 Lab 1 Page 2 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Working with Variables: - Variables are listed in the Workspace window or can be listed using the whos command. - You can view and edit the contents of a variable using the variable editor that is opened when you double click on a variable in the Workspace window. - You can also enter a variables name in the command window to display its content. Other useful MatLab Commands:
<up arrow> diary fname diary on diary off Scrolls through past commands entered at the >> Very useful for repetitive entries or to correct minor mistakes Saves any new content in the command window to the file fname. Repeating the command appends to the end of the file (it does not overwrite). Diary on and off will toggle the diary on and off. If no fname is give the file will be saved to diary in the current directory Comment - everything on the same line following this sign is a comment and will not be evaluated. Allows you to continue your input on the next line if it gets long. Deletes the variable x from the workspace. clear all or clear will remove all variables. Lists current variables with details Ending an expression with ; hides the output Aborts the command that is executing
% ...
clear x whos
;
<ctrl C>
Activity 2:
1. Make a variable t with the value 0.4 and a variable x with a value of 2. 2. Use MatLab to evaluate the following expression.
v (sin(2 t) x )2 2 x e t
ME 421 Lab 1 Page 3 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
MATLAB Fundamentals
Slides 26-30
Though not mentioned in the tutorial you can also create vectors by simply listing the values in []
Matrixes: - 2-dimentional list of data - Create by listing numbers or by combining vectors or other matrixes. o Enter by row (elements separated by space or ,) and separate rows with ; Example: >> A = [5,4,3;8,7,6] A = 5 4 3 8 7 6 o Use vector or matrix names as elements (sizes must match) Special Matrixes
zeros(m,n) eye(m,n) ones(m,n) diag(v,k) rand(m,n) m by n matrix of zeros m by n identity matrix m by n matrix of ones Square matrix with v (a vector) as the kth diagonal and zeros elsewhere m by n matrix of random numbers chosen from a uniform distribution on the interval (0,1)
Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
o In variable editor: select data, right click, select Create variable from Selection, name variable o Index notation: A(i,j) (i row, j column) Specify index or range of index (a:b) : means all possible indexes Example: A(4,:) all elements in the 4th row o Index notation: single index A(k) count starting at top left and moving down each column. o end specifies last element Matrix Math
Let A and B be matrices; v and u are vectors; and c and d are constants. A + c, v + c A c, v c A + B, v + u A B, v u A*c A/c A .* B, v.*u A ./ B, v./u A * B, v * u, A*v A.^c A^c Adds c to each element in the matrix or vector Subtracts c from each element in the matrix or vector Adds each element in A (or v) to the corresponding element in B (or u) (sizes must match) Subtracts each element in A (or v) to the corresponding element in B (or u) (sizes must match) Multiplies each element of A by c Divides each element of A by c Multiplies each element in A (or v) by the corresponding element in B (or u) (sizes must match) Multiplies each element in A (or v) by the corresponding element in B (or u) (sizes must match) Cross product of A and B (inner dimensions must agree) Takes each element times itself c times Finds the product of A times itself c times (A must be square)
Activity 3:
1. Create the row vector v1 = 2 4 6 8 using the equal spacing command and v2 = 1 4 7 10 using the linspace command. 2. Create the column vector v3 with the values 3 7 2 3. Use matrix math to find A, the cross product of v3 and v2 (Note: you will need to determine the correct order of v3 and v2 for this to work) 4. Use index notation to extract the following from A a. x = 8 b. v4 = 7 28 49 70 c. B = 28 49 8 14
ME 421 Lab 1 Page 5 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Slides 1-13
Activity 4:
1. Use the documentation to find out how the max command works. 2. Use the max command to find the maximum value in the following matrix A= 4 2 0 9 3. Use a MatLab Function to find the following x = 4 + 8 + 10 + 2 - 3
ME 421 Lab 1 Page 6 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Visualizing Data
Slides 1-9
Slides 1-6
Change display window Create m-file to re-create graph at later point with File -> Generate M-File From the command line add title, etc with title(text), xlabel(text), ylabel(text), legend(text) Include formatting in your plot(x,y) command (see doc for specifications) Put several sets of axes in the same window with subplot
Activity 5:
1. Create a plot of y=sin(2 x) where x goes from 0 to 2 in steps of 0.1. 2. Add a title and axis labels to your graph 3. Indicate one of the x-intercepts with an arrow and a label (hint use plot tools) 4. Plot z=cos(2 x) on the same plot as a red dashed line.
ME 421 Lab 1 Page 7 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
LESSON 6:
M-FILES: SCRIPTS AND FUNCTIONS
General Information: - Scripts: group of MatLab commands - Functions: operates on inputs to produce outputs - Write programs in the MatLab editor (works like text editor)
Use same commands as in Command Window but will only execute at the end. Can be reused easily. Use comments (%) to clarify the program for future reference.
M-Files Scripts: - Collection of commands. - Save as name.m (m-file) - Run using the run button, double clicking the m-file in the Current Directory Window, or typing the script name in the Command Window
M-Files Functions: - First line must be the function declaration: function [out1,out2] = function_name(in1, in2) - Can take in any number of inputs and put out any number of outputs. - Save file with same name as function - Run function by calling it from the workspace or other m-file - Variables in function code do not need to match variable names in call statement. - Separate Workspace that is cleared on completion.
Activity 6:
1. Write a function that evaluates the expression below for any two inputs of t, and x
y 2sin2t 3x
ME 421 Lab 1 Page 8 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Programming in MatLab
Slides 11-20
while loop: run iterations until a condition is no longer true while condition1 == true runloop end -
for loop: repeat an operation for a given number of iterations for counter = range runloop end
Range can be any vector (ordered or unordered) but if counter is used and an index it must be a positive index. Exit loops with an if statement and the break command.
Activity 7:
1. Write code to calculate the following iterative expression where x goes from 0 to 10 in steps of h=0.1 and the initial value of y is 1. y j 1 y j hx j 2. Check the sizes of your x and y vectors. If necessary change your code so that they are the same size.
ME 421 Lab 1 Page 9 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Slides 1-6
odefun is the name of a function m-file that evaluates the function as rearranged in (1) and must have the declaration: function dx=odefun(t,x)
Higher Order ODEs - Need to rewrite as system of 1st order equations (1) Solve for the highest derivative (2) Rename as the 1st derivative of a dummy variable (3) Integrate the expression in (2) (4) If (3) isnt first order repeat (2) & (3) (5) Substitute so that lhs are first derivatives and there are no derivatives on the rhs. - Use ode45 with vector inputs - The order in the vectors needs to be consistent - Yout will be a matrix - select the correct column based on the order of the vector.
Activity 8:
1. Use ode45 to solve the following 1st order differential equation from 0 to 5sec. (Hint: this is the same expression as in Activity 6 if y=dx so you can use the function you wrote there) plot the results.
15 x 10 sin 2t 5x
x0
2. Write the following as a system of 1st order equations. (No code needed hand work is ok)
3 7x x 12 x x
ME 421 Lab 1 Page 10
5 sin( 2 t )
Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Useful Blocks:
1 Gain
Gain multiply by a constant Add or subtract input signals Multiplies or divides signals Applies the given function to the input Integrates the input
Sine Wave
Add
ME 421 Lab 1 Page 11 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Drag block from library into diagram Join blocks by drawing signal connections from output-ports to input-ports Double click a block to change parameters and get more information Label a block and signal connection by clicking on label or double clicking on connection. Turn a block by right clicking and selecting format, Save a model using the save button. Recall it by typing its name in the workspace (from correct directory) or double clicking the model in the Current Directory Window.
Activity 9:
1. Code the following equation in Simulink.
y 25sin(2t ) 4 t 2
2. Attach a scope output block 3. Label your blocks and signal connections appropriately
ME 421 Lab 1 Page 12 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Slides 27-36
Adjust the stop time in the stop time box. A stop time of Inf will give you a continuous run. You can stop the simulation with the stop button.
View Results: - Double click on the scope to view the results. - Auto-scale the axis with the binoculars button.
Changing Run Parameters: - Menu Simulation Configuratons Parameters Solver - Common changes: step size, solver type (ode45, etc) Finding Help: - Help buttons in Configuration Parameters - Help on each block parameter screen - Simulink Documentation
Activity 10:
1. Run the simulink model you created in Activity 9. 2. Use the scope to view your results include a screen shot of this plot. 3. Change the solver parameters to determine the step size that causes the output to no long look realistic (include thisincorrect plot).
ME 421 Lab 1 Page 13 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Slides 38 - 47
Activity 11:
1. Replace the scopes in the Simulink model in Activity 9 & 10 with To Workspace outputs. 2. Change the model so that the multiplication factor 4 is now a variable M defined in MatLab 3. Write a MatLab script that a. Assigns a value to M b. Runs the Simulink model c. Plots the results of y vs time
ME 421 Lab 1 Page 14 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Slides 21 - 27
Some ODEs have forcing functions. These can be incorporated using source blocks.
Activity 12:
1. Use simulink to numerically solve the following differential equation below from 0-5 sec.
15 x 10 sin 2t 5x
x0
2. Output the results to MatLab and create a plot of the results. 3. How do these results compare to the results generated by ode45 in Activity 8?
ME 421 Lab 1 Page 15 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Create Simulink model and use ADC and DAC ports to interface with dSpace.
Activity 13:
1. Create a Simulink diagram that: a. Outputs a sine wave to dSpace through DACH 2 b. Collects data from dSpace through ADCH 8 and sends it to a scope. 2. Get approval of your model from your supervisor before proceeding to the next lesson.
ME 421 Lab 1 Page 16 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
(3) Create a new experiment (4) Create a new layout (5) Build the simulink model (6) Create the control desk layout - Select desired instrument and draw box for location & size - Must include a CaptureSettings box to collect data (7) Link your model variable to the instruments& plots in the layout - Find appropriate simulink block in model tab - Drag variable/parameter name from model tab to instrument. (8) Add all open files to experiment (9) Save experiment Steps to reusing an old Control Desk experiment: (1) Open experiment file (2) Click on the model tab right click in lower left panel select load application (3) Trouble shooting: a. If there is no model lab: Re-make the simulink model b. Correct any broken links between instruments and variables.
Activity 14:
1. Create a Control Desk Experiment that works with your simulink model from Activity 13 and has the following properties: a. Allows you to the change the frequency and amplitude of the sine wave output (use NumericInput box). b. Shows plots of both the sine wave output and the input. c. Runs for 10 seconds. d. Records data for the input channel. 2. Turn in a screen shot of your Control Desk layout 3. Save your experiment and associated files
ME 421 Lab 1 Page 17 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
press the
dSpace Tutorial
Activity 15:
1. Connect your dSpace output port to the oscilloscope to check your output. 2. Connect the signal generator to your dSpace input port to provide data to collect.
3. Run your Control Desk experiment 4. Output a sine wave with an amplitude of 1.5 V and a frequency of 6.3 rad/sec and use the oscilloscope to verify this output (Note: the oscilloscope measures frequency in Hz). Save your oscilloscope data and include it in your activity report. 5. Use the signal generator to create a sawtooth wave with an amplitude of 1 V and a frequency of 1 Hz. Collect this data with dSpace and record it to a file.
ME 421 Lab 1 Page 18 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009
Activity 16:
1. Use matlab to open the data you collected in Activity 15. 2. Plot it as a green line with appropriate title and axis labels.
ME 421 Lab 1 Page 19 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009