ME 125L - Spring 2009 ME 125L – Spring 2009 Instrumentation Basics M. R. Gustafson II Contents 1 Introduction 2 2 Simulink Demonstration 2.1 Starting Simulink . . . . . . . . 2.2 Basic Blocks and Connections . 2.3 Running Simulations . . . . . . 2.4 Creating Arbitrary Inputs . . . 2.5 Transferring Data . . . . . . . . 2.6 Naming and Arranging Blocks . 2.7 Saving and Printing Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 2 5 6 7 7 7 3 dSPACE Blocks 8 4 General Procedure for dSPACE Cards 9 5 Assignment 1: RC Circuit Analysis 5.1 Start MATLAB and ControlDesk . 5.2 Simulink Model . . . . . . . . . . . 5.3 Simulink Configuration . . . . . . . 5.4 Hardware Connections . . . . . . . 5.5 Open and Build the System . . . . 5.6 Make Handles to Blocks . . . . . . 5.7 Interacting Through a Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 10 10 10 11 11 12 12 6 Assignment 2: Angular Measurements 6.1 Simulink Model . . . . . . . . . . . . . 6.2 Hardware Connections . . . . . . . . . 6.3 Open and Build the System . . . . . . 6.4 Interacting Using ControlDesk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 14 14 15 15 7 Assignment 3: Voltage Control 7.1 Simulink Model . . . . . . . . . 7.2 Hardware Connections . . . . . 7.3 Open and Build the System . . 7.4 Interacting Using ControlDesk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 17 17 17 17 . . . . . . . . . . . . . . . . . . . . . . . 8 Transferring Files 18 9 Take-Home Assignment 18 10 Conclusion 18 Copyright 2009, Gustafson et al. 1 ME 125L - Spring 2009 1 Introduction For the past few labs, you have been using the dSPACE processor cards to set and measure different voltages and to process the collected data. For this week, you will be learning how to set up a MATLAB Simulink model to program the dSPACE card; how to write MATLAB .m files to initialize, run, and monitor those programs; and finally how to use the dSPACE ControlDesk to create an interactive connection to the dSPACE cards. 2 2.1 Simulink Demonstration Starting Simulink Simulink is an add-on package to MATLAB - it is installed on all the PCs in the lab. To start Simulink, you must first start MATLAB, select the RTI1104 Platform if you are asked, then type simulink at the command prompt within MATLAB. At that point, the Simulink library window will come up. While you will not be creating your model in this window, you will be using it to obtain access to the many different built-in blocks that Simulink provides. To start your own model, go to File->New->Model. Now you have a blank canvas to work with. To fill it in, you need to know what the basic blocks are, how to bring them into your model, and how to connect them. For this week, you will be putting all your files in a folder called C:\ILAB\NET_IDS\ where NET IDS will be the NET IDs of the people working on the lab. For example, if mje7 and mfs2 are working on this lab, inside the ILAB folder they would create an MJE7 MFS2 folder and store everything there. The name of this file should be SimDemo1.mdl, so go ahead and save the model now - you may have to create the ILAB folder on the C drive, and will definitely have to create the NET IDS folder. 2.2 Basic Blocks and Connections The Simulink library is broken up into several categories, and each category contains several building blocks for modeling signals and systems. To look at the contents of a particular category, just click its name in the library browser. For example, if you open the Simulink group and click on the Sources category icon, the right-hand window will show you a list of blocks containing several different ways that MATLAB can generate a signal. If you want to add one of these to your model, all you have to do is click and hold on it with the left mouse button, then drag it onto your canvas. Try this with the Signal Generator block. Your model should now have a single Signal Generator. Signal Generator To examine and change the possible parameters of a block, simply double-click on it in your model window. The Signal Generator, for example, allows you to choose what wave form you would like, the time base to use, the amplitude of the signal, the frequency, and what units of frequency to use. If you were to want to use an input of x(t) = sin(8t), for example, you would choose a sine wave, using the simulation time, with an amplitude of 1 and a frequency of 8 radians per second. Go ahead and make those changes, then click the OK button to accept them. Once you have some kind of input signal, you may want to process it. There are many different ways to process a signal in Simulink, ranging from basic mathematics to advanced image processing and frequency analysis. For now, open up the Math Operations category by clicking it in the library browser. Among the different operations you can perform is the Gain block, which acts like a multiplier. Drag a copy of this into Copyright 2009, Gustafson et al. 2 ME 125L - Spring 2009 your model, so that now you have a Signal Generator and a Gain block. Move the Gain block so it is about an inch to the right of the Signal Generator. 1 Signal Generator Gain If you double-click this block, you will see that it has more options than you may have thought for a simple gain. Generally, however, you will only need to change the Gain itself. Go ahead and set the gain to 2 and click the Apply button. Notice that the number inside the block itself changes as a result. 2 Signal Generator Gain The number in the gain block will reflect the actual gain if there is room for it - otherwise the gain block will have the letter K in it. For example, if you put in 0.0001 for the gain and hit Apply again, the block will just have a K in it. −K− Signal Generator Gain If you really want to see the gain, you can change the size of the block to make it large enough that the number will fit inside: .0001 Signal Generator Gain though generally you will not want to resize blocks just to see the contents. The main blocks you will be resizing are those with multiple inputs or outputs, for example, summation blocks there the larger size will make it easier to track and attach the different inputs. In this case, change the gain back to 2 and hit OK, then make the gain block a more normal size. Finally, you will want to have some way of viewing or saving the data. If you go back to the library browser and open up the Sinks category, you will see the various ways that MATLAB can take a signal and either send the information to the screen, to the workspace, or to a file. In this case, you are going to want to both view and manipulate the data, so drag both a Scope and a To Workspace to your model. Put both about an inch to the right of the Gain block, with the Scope about an inch above and the To Workspace about an inch below. Copyright 2009, Gustafson et al. 3 ME 125L - Spring 2009 Scope 2 Signal Generator Gain simout To Workspace If you double-click the scope, an oscilloscope window will appear. The scope is useful for viewing the signals throughout a simulation in real time. Generally, you will add these during the construction of a model, but once you have completed the model, you will want a more permanent record of the data obtained. This is where the To Workspace block comes in. The To Workspace block will record the signal values sent to it as a variable in the MATLAB workspace. If you double-click on the block, you will note that you can change the variable name - go ahead and make this y. The Save format that is most readily used is Array, so go ahead and make that change as well. The default cases for the other parameters will generally work fine. Once done, click OK and notice that the name of the variable is now showing inside of the block. Scope 2 Signal Generator Gain y To Workspace Now that the blocks are in place, you need to connect them. You will notice if you run the cursor over the small port symbol (the >) of a block that the cursor changes from an arrow to crosshairs. The way you connect blocks is to pick the port of one block, hold down the left mouse button, and drag until you hit another port (or another wire). Go ahead and connect the Signal Generator to the Gain block by putting the cursor on top of the output port of the Signal Generator, holding down the left mouse button, and dragging until the cursor is over the input port of the Gain block. You will notice that the cursor changes to double crosshairs when you have found a terminus for your wire. Now connect the output of the Gain block to the Scope. Scope 2 Signal Generator Gain y To Workspace Copyright 2009, Gustafson et al. 4 ME 125L - Spring 2009 If you also want to connect the Gain block to the To Workspace block, you will need to first click on the input of the To Workspace then drag until you hit the wire connecting the scope to the gain block. You cannot go back to the Gain block’s output port, because every input or output port can only be used once as the start of a wire. Since every wire should have at least one new port connection, you must begin from that port. Again, you will get the double crosshairs when you are over a wire such that a connection will be made and you will notice a node symbol (small black dot) at the connection. If you make a mistake and drop the wire before it is connected, you will get a dashed red wire with a port symbol at the end of it. You can remove this wire by left clicking on it (thereby selecting it) and hitting delete. At this point, your model should have all four blocks properly wired, with a gain of 2 and a To Workspace variable called y: Scope 2 Signal Generator Gain y To Workspace There should also be an open Scope window that came about when your double-clicked the Scope block. 2.3 Running Simulations Now that you have a basic block diagram with an input signal going through a system that multiplies that signal by 2 as well as two different ways of examining the data, you are ready to simulate the system. Within the Simulation menu of your model, go to Configuration Parameters and you will discover that Simulink has an extensive array of options from which to choose. For now, the critical part is telling MATLAB to store all the data and telling MATLAB the simulation time. Go to the Data Import/Export selection and un-check the Limit data points... option in the Save options. For whatever reason, MATLAB defaults on only storing the last thousand data points unless you specify otherwise. Generally, you will want Simulink to report all the data. With respect to timing, go to the Solver selection. Set the simulation to go from 0 to 10 seconds and make sure the Type is “Fixed-step” and the step size is 0.001. Once you have those things set, click OK. Then, to run the simulation, go to Simulation and Start. The scope will show the values of the output, and when the simulation is finished, MATLAB will beep. Note - MATLAB may issue a warning that “The model ’untitled’ does not have continuous states,” this is not a problem. It just means MATLAB uses a different solver. If you type whos in MATLAB, you will discover that not only did you generate an array called y but that Simulink also created an array called tout for you. Now you can run the simulation and, when finished, issue the command plot(tout, y) in MATLAB’s command window to plot the signal. You should see a sinusoid with an amplitude of 2 and a frequency of 8 rad/sec - which is about 1.27 Hz. The period should therefore be about 0.79 seconds. Copyright 2009, Gustafson et al. 5 ME 125L - Spring 2009 2.4 Creating Arbitrary Inputs There are several ways to create different inputs signals. The Signal Generator is certainly the easiest way to create a basic sinusoid, square wave, or sawtooth. For other signals, you can use a combination of sources and basic math to get what you want. There is even a Signal Builder block that can be used to draw signals. Generally, however, the easiest way to create an input is to use a Clock block and feed it into a Fcn block. Go ahead and save your current model as SimDemo1.mdl, then do a “save as” and call it SimDemo2.mdl. Now select and delete both the Signal Generator and the Gain block. Among other changes, you will now be left with unconnected lines, denoted by red dotted lines - this model is shown at left in the figure below. These can be deleted by selecting them and hitting delete, or they can be reused by putting a block’s input or output ports close enough that Simulink thinks they should be connected. For example, drag a Clock block from the Sources category such that the output of the Clock is near the left-most part of the left line. It will attach itself to that wire, though the wire will remain red since its output end is still unconnected. Now open the User-Defined Functions category and drag a Fcn block into your model, placing it in the space vacated by the gain block. The Fcn block is larger that the Gain block so you can only snag one of the wires. To get the other one, you can drag the Fcn block again or use the arrow keys to move it until it connects and the wire turns solid black. You should now have the model at right: Scope Scope f(u) Clock Fcn y y To Workspace To Workspace After deleting Signal Generator and Gain blocks. After adding Clock and Fcn blocks. To enter a function, double-click the Fcn block. Note that the expression is currently a function of the vector u. This vector represents the different inputs to the block. Right now, we are only using a single input - though later you can use multiplexers to send multiple streams along a single line. Your function, therefore, should be written in terms of u[1]. For example, if you want the output of the function to be e−t/3 cos(4t), then the input to this block should be exp(-u[1]/3)*cos(4*u[1]). Note - Simulink does not like using the “.*” version of multiplication. Once you have that function entered, re-run the simulation. If you make a plot of y as a function of tout using the command plot(tout, y), you should get: 1 0.8 0.6 0.4 0.2 0 −0.2 −0.4 −0.6 −0.8 0 1 2 3 4 5 6 7 8 Copyright 2009, Gustafson et al. 6 9 10 ME 125L - Spring 2009 2.5 Transferring Data As mentioned earlier, you will often want to transfer data from the Simulink simulation to the workspace. The To Workspace block is the easiest way to get a signal’s information to the workspace - but only if you are running a simulation! If you are using Simulink to compile a model for the dSPACE cards, you will not be using the To Workspace blocks. For simulations, just make sure that the variable name is unique for each of the blocks and that you have used the Array method for storing the data. There are also From Workspace blocks if you want to pass in value and time data from the workspace. 2.6 Naming and Arranging Blocks You can change the name of blocks in Simulink by double-clicking the name you want to change. This can be very useful if your blocks have real-world analogs. You can also probably come up with much more interesting names than “To Workspace” for your outputs. Avoid using dots or slashes in the block names, however. Stick with letters and numbers if at all possible. Also - make all these changes before you start writing codes or ControlDesk layouts for models - the codes and ControlDesk components will be linked to particular blocks through their names; changing a name in the model means having to change the name in all the scripts and layouts as well. When creating block diagrams, you may also occasionally want to “aim” a block in a different direction - to do this, simply pick the block, then go to the Format menu and select either Flip Block or Rotate Block. You have already seen that you can resize blocks. Take note the other options in the Format menu there may be times with particularly sophisticated models that you will want to use various colors and other options to help clarify your system. 2.7 Saving and Printing Models To save a Simulink model, just go to the File menu and select either Save or Save As. Simulink models should end with .mdl. To print your model, you can either use the Print function in the File menu or type print -deps -sMODELNAME FILENAME.eps The following code will not only print the model based on the filename, it will also save and close the model window when the script is finished: M o d e l N a m e = ’ SimDemo2 ’ eval ( s p r i n t f( ’ print -s % s - deps % smodel ’ , ModelName , M o d e l N a m e )) save_system( ModelName) c l o s e _ s y s t e m ( M o d e l N a m e) The name of the saved picture of the model will be ModelNamemodel.eps. If you are going to do several things with the same model, you may want to add some kind of flag in the sprintf command to differentiate among plots. For example, if you are running code in a loop based on some integer counter k, you could use the following code: eval ( s p r i n t f( ’ print -s % s - deps % s m o d e l _ %0.0 f ’ , ModelName , ModelName , k )) Copyright 2009, Gustafson et al. 7 ME 125L - Spring 2009 3 dSPACE Blocks In addition to the blocks that come with Simulink, the dSPACE cards shipped with their own blockset - this group can be seen at the bottom of the library browser. Select the dSPACE RTI1104 group and, within it, the DS1104 MASTER PPC category. The right-hand window will now show several different blocks. The most important are: • DS1104MUX ADC: gains access to the first four ADC (analog-to-digital, or input) channels, which are multiplexed. Multiplexed means that all four measurements will be taken at once - in Simulink, to access the individual channels, you will thus have to demultiplex them. There is a DEMUX block for just this purpose. • DS1104ADC C5: gains access to ADC channel 5 of the dSPACE card. Note that if you drag in more than one block, it will automatically go to the next channel (6, 7, etc.). Also, once you have added a block to your model, you can double-click on it and manually change the channel. • DS1104DAC C1: gains access to DAC (digital-to-analog, or output) channel 1 of the dSPACE card. As above, if you drag in more than one block, it will automatically go to the next output channel (2, 3 etc.). Also, once you have added a block to your model, you can double-click on it and manually change the channel. • DS1104ENC POS C1: gains access to the first encoder input channel. This is a very powerful block, as it does all the data processing required to convert a digital rotary encoder signal into an angular measurement. Several of these blocks will be used in the assignments for this lab and are described below. For the ADC and DAC blocks, you have to have a gain block between the value you want and the block, because the dSPACE card scales its data. For the measurements, the output of the block will report between -1 and 1; these values relate to a range from -10 V to 10 V respectively, so to measure the actual voltage, you will need to multiply the block output by 10. Similarly, the DAC inputs expect values between -1 and 1; these again relate to desired voltages between -10 V and 10 V. Given that, there needs to be a gain of 0.1 between the desired voltage and the DAC input. To make things easier, you can download two template files from the Pratt Pundit page on DSPACE: http://pundit.pratt.duke.edu/wiki/DSPACE One contains a full set of blocks for the ADC channels, including a demultiplexer for the first four channels and gain blocks for all ten channels. The other contains a full set of blocks for the DAC channels, including gain blocks. Download these to your ILAB/NET IDS directory before going on. You will want to copy the blocks out of these two templates when you are making your Simulink models. Copyright 2009, Gustafson et al. 8 ME 125L - Spring 2009 4 General Procedure for dSPACE Cards To use the dSPACE cards in concert with Simulink and dSPACE’s ControlDesk program, you will likely go through the following procedure: • Start MATLAB and ControlDesk. • If not already done, create or update a Simulink model to upload to the dSPACE card and save it. • Build the physical system and make all the relevant connections to the dSPACE card. • Run a script that will: define any global variables, open the model, compile the model using the real-time workshop, and upload the compiled model to the dSPACE card. • If using MATLAB to monitor and/or control the experiment, run a script that will define connections between the dSPACE card and MATLAB. This will allow MATLAB to set and read variables on the dSPACE card using a suite of commands contained within the mlib function. Then write a MATLAB script to use those connections. • If using ControlDesk to monitor and/or control the experiment, create a layout with the various virtual gages, displays, and the like and animate it in ControlDesk. interact with the dSPACE card or write a script in MATLAB to access Note - the ControlDesk portion can really only be done once a Simulink model has been compiled and uploaded to the dSPACE card. There are three assignments in this lab. The first two assignments will guide you through parts of the above process; the third assignment will call on you to use the skills obtained from the first two parts to build an open-loop control system involving an RC circuit and a rotary encoder. Copyright 2009, Gustafson et al. 9 ME 125L - Spring 2009 5 Assignment 1: RC Circuit Analysis For this part of the assignment, you are going to be building an RC circuit and analyzing it using the dSPACE card. Specifically, you will be building the following circuit, including the output channel and measurement channels indicated: R + DACH1 − ADCH5 C ADCH1 You will also be monitoring the experiment and making a plot with MATLAB. Though you will not be using ControlDesk for this particular part of the assignment, you might as well have it running since you will be using it for the other two parts. 5.1 Start MATLAB and ControlDesk Make sure that both MATLAB has completely started up before running ControlDesk, and be sure to select the RTI1104 platform support option. Then, make sure ControlDesk has finished starting up before progressing further. 5.2 Simulink Model Generate a Simulink model that has two input channels - ADC1 (which is part of the multiplexed set of measurements) and ADC5 (which is an individual measurement). Since you are only taking two measurements, you could have chosen two from the multiplexer or two individual channels, but part of the purpose of this assignment is to see the differences between those two modes. Next, add an output channel DAC1. In this case, DAC1 will set a voltage across a series combination of a resistor and a capacitor. ADC1 will be measuring the total voltage across the combination and ADC5 will be measuring the capacitor voltage only. Note that you will want to copy these from the templates downloaded earlier from the Pratt Pundit page on DSPACE. Save the file as Assignment1.mdl. 5.3 Simulink Configuration Next, you will need to check on the simulation parameters. In the model window, go to Simulation-> Configuration Parameters. Make the following changes: • In the Solver section, make sure to use a fixed-step solver and change the fixed-step size to 0.001. This simulation should be allowed to run from 0 to Inf. • In the Optimization section, remove the checks in the boxes beside Block reduction optimization and Signal storage reuse • In the Hardware Implementation section, check or change the following: • Device type → “Custom”, Byte ordering → “Big Endian”, Signed integer division rounds to → “zero” Copyright 2009, Gustafson et al. 10 ME 125L - Spring 2009 • In the Real-Time Workshop section, make sure the System target file is rti1104.tlc. Change this if you need to. Once all these settings are checked, click Apply, then OK. Go ahead and save the model again. 5.4 Hardware Connections On the ProtoBoard, put a 10 kΩ resistor in series with a 100 µF non-polarized capacitor. You can tell if a capacitor is non-polarized if it has the letters “NP” stamped on the side. Put these close enough to the right side of the board that three of the BNC leads can reach. Now, make the following connections between the BNC “converter panel,” the circuit, and the CP1104: • Connect the common BNC ground (blue wire) to the free capacitor end - this will be the ground voltage for the circuit. Make sure that particular wire is connected to several of the BNC converters - you will need three converters total for this particular assignment. You can ignore the “IN” and “OUT” labels on the panel. • Connect one of the BNC measurement leads (red wire) to the free resistor end, then attach a BNC cable between there and DACH1 on the CP1104 - this is the channel that will be providing a voltage to the series combination of R and C. • Connect another of the BNC measurement leads to the free resistor end, then attach a BNC cable between there and ADCH1 on the CP1104 - this is the channel that will be measuring the total voltage across the series. • Finally, connect one of the BNC measurement leads to where the resistor and capacitor are connected on the breadboard, then attach a BNC cable between there and ADCH5 - this is the channel that is measuring the capacitor voltage. Note - given the way all the BNC leads are grounded, it would be impossible to directly measure the resistor voltage with just one channel (unless you broke one of the ground connections between BNC converters). However, if the resistor voltage were required, you could simply take the difference between ADCH1 and ADCH5. 5.5 Open and Build the System Create a script that defines the name of the Simulink file, opens it in Simulink, and compiles it with the real-time workshop. The script should also run a different script that will contain the commands MATLAB needs to have access to some of the information on the dSPACE card. Call this m-file Init1.m and put in the following code: % Opens the s i m u l i n k p r o g r a m and builds it . M o d e l N a m e = ’ Assignment1 ’ o p e n _ s y s t e m ( M o d e l N a m e ); r t w b u i l d( M o d e l N a m e ); % G e n e r a t e s h a n d l e s to blocks MakeHandles1; Save it in your ILAB/NET IDS folder. This code will basically allow you to open the model file if it is not already open, compile it with the rtwbuild program, and then run a script you are about to write to get handles to the important blocks of the system. Do not run this code yet - you must at least have the MakeHandles1.m file done before running! Copyright 2009, Gustafson et al. 11 ME 125L - Spring 2009 5.6 Make Handles to Blocks The Init1 command above will run a script you are about to write called MakeHandles1.m. Open a new m-file and put in the following code: % Select the board mlib ( ’ SelectBoard ’ , ’ ds1104 ’); % Define global v a r i a b l e s for m e a s u r e m e n t and output c h a n n e l s global ADC1 ADC5 DAC1 %% Note - the h a n d l e s below assume use of the ADC and DAC t e m p l a t e s % ( specifically , the names of the blocks there ) % Define A / D h a n d l e s ADC1 = mlib ( ’ GetTrcVar ’ , ’ Model Root / ADC1 / Out1 ’); ADC5 = mlib ( ’ GetTrcVar ’ , ’ Model Root / ADC5 / Out1 ’); % Define D / A h a n d l e s DAC1 = mlib ( ’ GetTrcVar ’ , ’ Model Root / DAC1 / Out1 ’); Save this file, then run the Init1.m script. At this stage, the program is actually running on the card. To see what is happening, you will either need to access the card through MATLAB or through the Control Desk. For this first assignment, you will be accessing it through MATLAB 5.7 Interacting Through a Script The MATLAB script on the following page will go through the process of zeroing out DACH1 for 5 seconds (allowing the capacitor voltage to decay to nearly 0 volts), then increasing that voltage to 5 V and taking 5 seconds of data, then setting the voltage back to 0 V and taking about 5 more seconds of data. Note that the data collection in this case is running asynchronously - that is, the rate at which data points are collected is not exact. A copy of the script is available for copying and pasting through a link in the “Files for Labs” section of the Pratt Pundit page on dSPACE: http://pundit.pratt.duke.edu/wiki/DSPACE If your program runs successfully, you should end up with a graph that looks like: 6 5 4 3 2 1 0 0 2 4 6 8 10 Show this to your TA before moving on. Copyright 2009, Gustafson et al. 12 12 ME 125L - Spring 2009 %% Close f i g u r e s and clear - NOTE - g l o b a l s will still work ! close all ; clear %% Access dSPACE card mlib ( ’ SelectBoard ’ , ’ ds1104 ’) %% Define g l o b a l s for ADC and DAC %% A s s u m e s ADC / DAC h a n d l e s have been d e f i n e d global ADC1 ADC5 DAC1 %% Gather data using the dSpace card % Set v o l t a g e to 0 and wait 5 s e c o n d s f p r i n t f( ’ S e t t i n g 0 V on DACH1 - w a i t i n g 5 s e c o n d s\n ’) mlib ( ’ Write ’ , DAC1 , ’ Data ’ , 0) pause (5) % Start data c o l l e c t i o n and start c o u n t e r f p r i n t f( ’ S t a r t i n g data c o l l e c t i o n\n ’) Count = 0; % Set v o l t a g e to 5 V and start timer f p r i n t f( ’ S e t t i n g 5 V on DACH1 \n ’) mlib ( ’ Write ’ , DAC1 , ’ Data ’ , 5); tic ; % Run for 5 s e c o n d s - a s y n c h r o n u s data c o l l e c t i o n mode while toc <5 % Increment counter Count = Count +1; % Tell dSPACE which c h a n n e l s to a c q u i r e and start a c q u i s i t i o n mlib ( ’ Set ’ , ’ TraceVars ’ ,[ ADC1 ; ADC5 ] , ’ NumSamples ’ ,1); mlib ( ’ StartCapture ’) % Do not go to next step until data is taken while mlib ( ’ CaptureState ’)~=0 end % Store time and data in Count row of vector tout ( Count , :) = toc ; data ( Count , :) = mlib ( ’ FetchData ’); end % Set v o l t a g e to 0 and take data for a n o t h e r ~5 s e c o n d s % ( see above for c o m m e n t s) f p r i n t f( ’ S e t t i n g 0 V on DACH1 \n ’) mlib ( ’ Write ’ , DAC1 , ’ Data ’ , 0) while toc <10 Count = Count +1; mlib ( ’ Set ’ , ’ TraceVars ’ ,[ ADC1 ; ADC5 ] , ’ NumSamples ’ ,1); mlib ( ’ StartCapture ’) while mlib ( ’ CaptureState ’)~=0 end tout ( Count ) = toc ; data ( Count , :) = mlib ( ’ FetchData ’); end f p r i n t f( ’ F i n i s h e d with data c o l l e c t i o n \n ’) %% Make a plot plot ( tout , data ) Copyright 2009, Gustafson et al. 13 ME 125L - Spring 2009 6 Assignment 2: Angular Measurements For the next part of this lab, you will be using the AMT102-V Encoder in order to measure the angle of rotation of the motor shaft. The 102V is a variable-resolution incremental rotary encoder. The basic concept of the rotary encoder is that the wheel is broken up into two rings, and each ring can be either “on” or “off” at a given time. The pattern of “on” and “off” repeats symmetrically throughout the wheel - the difference between the two wheels is that one’s pattern is a quarter-period shifted from the other. In this way, a device capable of detecting the order in which signals change on the two rings can determine the direction of spin; the speed with which the signals change gives an indication of speed. Using the four dip switches on the interior of the AMT102-V, you can set up to sixteen different resolutions - basically, setting the number of “on off” patterns on each ring. At the lowest resolution, the AMT102V can detect angular changes of 1/48th of a revolution; at the highest resolution, the AMT102V can detect changes as small as 1/2048th of a revolution. For this particular experiment a resolution of 1/100th of a revolution will work well. To achieve this, open the case on the AMT102-V and set switch 1 off (down) and switches 2, 3, and 4 on (up). Other configurations may be seen at http://www.cui.com/amt/DIP switch settings.pdf. Although programs can be written to convert the ring signals into angular measurements, the dSPACE system already has two inputs specifically geared towards taking rotary encoder data and converting it to a more useful signal. In addition, the Simulink blockset for the dSPACE cards has a block for reading the encoder input channels. This makes using rotary encoders much, much easier. 6.1 Simulink Model MATLAB and the ControlDesk should already be open - in case not, open them both up. If MATLAB asks you to “Select dSPACE RTI Platform Support,” choose the RTI1104 option. If need be, start Simulink by typing simulink at the command prompt. When the Simulink Library Browser window comes up, go to File->New->Model to start your new model. For this part of the assignment, you are going to create the blocks needed in order to take measurements from the encoder and send them to the ControlDesk. Save the model as Assignment2.mdl in your ILAB/NET IDS directory. In the Simulink Library Browser, expand thedSPACE RTI1104 group, then click on the DS1104 MASTER PPC group. Drag a DS1104ENC SETUP block and a DS1104ENC POS C1 block into your blank model. Double click the SETUP block and make sure both encoder channels are set for single-ended TTL. Double click the POS block and make sure the Unit is set to Channel 1. Next, in the Simulink Library Browser, go into the Simulink group and click on the Sinks category. Grab two Out blocks - note that the number in the second Out block becomes a 2 when you put it in your model. Connect the first Out to the Enc position output and connect the second Out to the Enc delta position output. Then save the file. Next, you will need to check on the simulation parameters. Use basically the same setup in the “Simulink Configuration” portion above - Section 5.3 on page 10 - only this time use a fixed-step size of 0.1 instead of 0.001. 6.2 Hardware Connections First, plug the 15-pin connector cable from the AMT102-V into the Inc1 slot on the CP1104. The wires have already been soldered such that the four signals and the power wire for the AMT102V will be properly connected to their matching lines. The red wire will be providing 5 V from the dSPACE card to the AMT102V while the black wire will be setting the ground voltage. The green wire is the index signal - once per revolution, this signal will go high. It is a rudimentary way of measuring each time the wheel goes through one revolution. The CLP1104 shows this signal as Index 1 on the right bank of LEDs. Finally, the white and brown wires will be measuring the two ring voltages - the CLP1104 lists these as Phi0 1 and Phi90 1, respectively, on the right bank of LEDs. Copyright 2009, Gustafson et al. 14 ME 125L - Spring 2009 Once you connect the AMT102-V to the Inc1 connector, you should be able to turn the wheel and see the LEDs blink. Specifically, both Phi0 and Phi90 should flicker 100 times for a full revolution while Index 1 will only flicker once. Test this by turning the wheel one-quarter turn, counting the Phi0 flickers as you go - you should end up with 25. Then, keep turning the wheel until the Index 1 light comes on. Now, try turning the wheel in the opposite direction - you should notice the pattern of when the top two lights come on will reverse itself. Next you are going to write the Simulink code to allow the dSPACE card to read the encoder and display the angle in the ControlDesk. 6.3 Open and Build the System Now you are going to use the Real-Time Workshop to compile code for the dSPACE card. Create a script that defines the name of the Simulink file, opens it in Simulink, and compiles it with the real-time workshop. Call this m-file Init2.m and put in the following code: % Opens the s i m u l i n k p r o g r a m and builds it . M o d e l N a m e = ’ Assignment2 ’ o p e n _ s y s t e m ( M o d e l N a m e ); r t w b u i l d( M o d e l N a m e ); Note this time you are not making handles - this is because you are going to be interacting with the dSPACE card through ControlDesk and not through a MATLAB script; ControlDesk builds its own handles. 6.4 Interacting Using ControlDesk Now within ControlDesk, go to File->New Experiment..., call the experiment DisplayEncoder and set the working root to your ILAB/NET IDS folder. Switch to ControlDesk. Then, note the following: • In the bottom of the ControlDesk, there are various tabs - for example, Log Viewer, File Selector, etc. Once a Simulink model is built and sent to the dSPACE cards, one of the tabs should be the SDF tab for the Assignment2 model - that is the area where ControlDesk keeps all the handles to a particular code. Go ahead and select it. The window just above the tabs should now show a ”tree” with the model name at the top (using all lower-case letters) followed by Model Root, Labels, and Task Info. • Expand the Model Root and the entries below it will be the blocks from the Simulink model, plus an extra RTI Data block that MATLAB added automatically. • Click on the Out1 entry and the right-side window will now indicate that there is a Variable called In1 associated with it. That means ControlDesk has access to the input of that block. • To monitor a variable, you will need to create a layout. Just above the variable explorer window and on the left of the ControlDesk is a set of four tabs. The second one, marked by a yellow rectangle above a blue square and red rectangle, is the Instrumentation tab. If you are unsure what a tab means, hover over it and a description will appear - the one for the tab you want right now is “Instrumentation.” Select that. The window above it will indicate ”No layouts open!” • Double-click the ”No layouts open!” and a new layout, layout1 will appear. This area is where you can add gages, graphs, and other monitoring and instrumentation. To see what objects are available, go to the View menu and select Controlbars->Instrument Selector (unless it is already checked). The Instrument Selector should now be on the right side of the screen. • For this assignment, you are going to want to have two Display Virtual Instruments. Click on the Display in the Virtual Instruments menu, then draw a box in layout1. When you drop the second corner, a Display will be added to the layout. Do this again to make a second Display. Make them approximately the same shape. Copyright 2009, Gustafson et al. 15 ME 125L - Spring 2009 • To tell the ControlDesk what you will be monitoring, you need to drag a variable from the variable list on the bottom right of the screen and drop it on the display. Make sure that the Out1 block is still selected at the bottom left, then drag the word In1 from the variable list and drop it on the first Display in layout1. The title of the Display should now be Out1/In1 indicating the block and value being displayed. Similarly, choose the Out2 variable in the block list, then drag its In1 variable to the second Display - it will now read Out2/In1. • Save the experiment, then go to File->Save and save the layout - be sure to save the layout in the same folder you are saving everything else. Give the layout a name Assignment2 NETID where NETID is your NETID. Every layout must have a unique name. • Now, you want to tell ControlDesk to actively animate the layout. Near the middle of the icon bar at the top of the window, you should see two red icons - the red square means the program is actively running on the dSPACE card. To the right of the book-like red icon, there are three icons letting you know what state the layout is in. The first one, with stacked rectangles, means you are editing the layout. The second one, where the yellow rectangle is replaced with a yellow...star...thing...is the test mode for seeing what the layout will look like. The third, where the bottom red rectangle has been replaced by an arrow, is the Animation Mode - that is the one you want to use when you want ControlDesk to actively link your virtual instruments to the dSPACE card. Again, if you are unsure what an icon does, hover over it and ControlDesk will tell you. Go ahead and click on Animation Mode. • At this point, the first display is showing you the number of signal changes the encoder has received and the second one is calculating the number of signal changes per second the encoder has received. As a test, rotate the shaft of the encoder until the first display reads “0,” then twist it one-quarter turn. The display should now read close to 25 since the encoder is set up to make 100 changes per rotation. Keep changing the position of the encoder shaft, changing speeds as you go, to see the two different values produced. • While this display is good for determining the number of signal changes, it is more likely that you want to know the number of degrees through which the shaft has turned. ControlDesk will allow you to do math in between reading the signal from the encoder block and producing an output. To make changes in the layout, first put the layout in Edit Mode by clicking the stacked rectangles button just to the right of the red book. The layout goes into edit mode, and the displays show whatever values were last read from the card. • Double-click the first display, then choose the Value Conversion tab. In the Forward box of the Conversion functions area, you are going to want to take the source, which changes by 100 per rotation, and make a function that instead changes by 360 per rotation. The easiest way to do this is to type 360*(x/100) in that box. Hit the Apply button, and notice when you do so that the inverse function is automatically calculated. Hit OK, and put the layout back into Animation Mode. • Now turn the encoder shaft to get it back to 0. Turn the shaft a quarter-turn and notice now, instead of 25 (for 25 signal changes), the display reads approximately 90 (for 90 degrees). Congratulations! You have successfully built a Simulink library to read the encoder, compiled it and loaded it onto the dSPACE card, and created a layout to allow you a “peek” at the measurements being taken by the card. Save the experiment and the layout, then close the layout. In ControlDesk, you should not have layouts for multiple models open at the same time. Copyright 2009, Gustafson et al. 16 ME 125L - Spring 2009 7 Assignment 3: Voltage Control For this final assignment, your task will be to create a system where the output voltage of the dSPACE card is controlled by the angle of the rotary encoder. You will then also have a ControlDesk layout that monitors the various voltages in the system. The measured voltages will be the total voltage, the voltage across the resistor, and the voltage across the capacitor. Assuming MATLAB and ControlDesk are already running: 7.1 Simulink Model Create a Simulink model that has the required encoder blocks (SETUP and CH1), two ADC blocks, and a DAC block. Note that you can copy these from the previous two assignment models, though the output port numbers will change since there will be more than 2. Pay careful attention to the output port numbering. Next, you need to connect the blocks such that the encoder value sets the DAC voltage - one full turn of the encoder should change the voltage by 1 V. This will mean first removing DAC1’s input port, then determining the math required to take a signal from the Enc position output and send it to the DG1 block. Keep in mind that the encoder position is given as the number of signal changes (currently 100 per rotation) and that the input to the DG1 block will be the voltage. Use basically the same setup in the “Simulink Configuration” portion above - Section 5.3 on page 10 - only again use a fixed-step size of 0.1 instead of 0.001. 7.2 Hardware Connections The hardware connections will be those already made in Sections 5.4 and 6.2. That is, the encoder is attached to the Inc1 input on the CP1104, DACH1 is connected across the series connection of a resistor and a capacitor, ADCH1 is measuring the total voltage and ADCH5 is measuring the capacitor voltage. 7.3 Open and Build the System Create a script that defines the name of the Simulink file, opens it in Simulink, and compiles it with the real-time workshop. Call this m-file Init3.m. You will be controlling and monitoring the experiment solely through ControlDesk, meaning you do not need to worry about handles. 7.4 Interacting Using ControlDesk Once you initialize and build the system, its SDF file should be available in ControlDesk. Now create a layout that has five Displays: the raw encoder count (i.e. changes by 100 each revolution), the encoder position in degrees (i.e. changes by 360 each revolution), the value of DACH1, the value of ADCH1, and the value of ADCH5. When you animate the layout, try rotating the wheel one turn - make sure the encoder count changes by 100, the degrees display changes by 360, and both the values obtained for DACH1 and ADCH1 change by 1 V. You may need to reconsider which blocks’ inputs or outputs you are linking to the displays if the values are off. Go back to edit mode, fix the linkages, and then re-animate; iterate this process until your five displays are acting the way they should be. You should also note how the capacitor voltage tracks the voltage you are applying to the RC circuit. Copyright 2009, Gustafson et al. 17 ME 125L - Spring 2009 8 Transferring Files You will want to save the files from this week onto your OIT account. Go to the Start Button, then All Programs, then SSH Secure Shell, then Secure File Transfer Client. Log into your favorite OIT machine. The left side of the screen will be the file structure for the PC you are on and the right side will be the file structure of your OIT account. Note that on the PC, your files are stored in the ILAB/NET IDS folder you created. You can actually drag and drop the whole folder to your OIT account to make sure you have all the required files. 9 Take-Home Assignment Your lab instructor will give you the take-home assignment. 10 Conclusion Once you have successfully completed this assignment, you should be able to design Simulink models that take advantage of the real-time toolbox as well as the dSPACE cards to form an integral part of a controller loop. Copyright 2009, Gustafson et al. 18