control tutorials for matlab and simulink - simulink basics tutorial

Upload: manoj-hande

Post on 01-Mar-2016

94 views

Category:

Documents


1 download

DESCRIPTION

Control Tutorials for MATLAB and Simulink - Simulink Basics Tutorial

TRANSCRIPT

  • SearchControlTutorialsEffectsTips

    INTRODUCTION CRUISECONTROL MOTORSPEED

    SimulinkBasicsTutorial

    Simulink isagraphicalextension toMATLAB formodelingandsimulationof

    systems.One of the main advantages of Simulink is the ability to model a

    nonlinearsystem,whichatransferfunctionisunabletodo.Anotheradvantage

    ofSimulinkistheabilitytotakeoninitialconditions.Whenatransferfunctionis

    built,theinitialconditionsareassumedtobezero.

    Contents

    StartingSimulink

    ModelFiles

    BasicElements

    SimpleExample

    RunningSimulations

    BuildingSystems

    InSimulink,systemsaredrawnonscreenasblockdiagrams.Manyelementsof

    blockdiagramsareavailable, suchas transfer functions, summing junctions,

    etc.,aswellasvirtualinputandoutputdevicessuchasfunctiongeneratorsand

    oscilloscopes. Simulink is integrated with MATLAB and data can be easily

    transferedbetweentheprograms.In thesetutorials,wewillapplySimulink to

    theexamplesfromtheMATLABtutorialstomodelthesystems,buildcontrollers,

    and simulate the systems. Simulink is supported on Unix, Macintosh, and

    WindowsenvironmentsandisincludedinthestudentversionofMATLABfor

    personal computers. For more information on Simulink, please visit the

    Mathworkslinkatthetopofthepage.

    Theideabehindthesetutorialsisthatyoucanviewtheminonewindowwhile

    runningSimulink inanotherwindow.Systemmodel filescanbedownloaded

    from the tutorialsandopened inSimulink.Youwillmodify andextend these

    system while learning to use Simulink for system modeling, control, and

    simulation.Donotconfusethewindows, icons,andmenusinthetutorialsfor

    youractualSimulinkwindows.Mostimagesinthesetutorialsarenotlivethey

    simplydisplaywhatyoushouldseeinyourownSimulinkwindows.AllSimulink

    operationsshouldbedoneinyourSimulinkwindows.

    SYSTEM

    MODELING

    ANALYSIS

    CONTROL

    PID

    ROOTLOCUS

    FREQUENCY

    STATESPACE

    DIGITAL

    SIMULINK

    MODELING

    CONTROL

    TIPS ABOUT BASICS HARDWARE INDEX NEXT

  • StartingSimulink

    Simulink is started from the MATLAB command prompt by entering the

    followingcommand:

    simulink

    Alternatively,youcanhittheSimulinkbuttonatthetopoftheMATLABwindow

    asshownhere:

    When itstarts,Simulinkbringsupasinglewindow,entitledSimulinkLibrary

    Browserwhichcanbeseenhere.

    ModelFiles

    InSimulink,amodel isacollectionofblockswhich, ingeneral, representsa

    system.Inaddition,todrawingamodelintoablankmodelwindow,previously

    savedmodelfilescanbeloadedeitherfromtheFilemenuorfromtheMATLAB

    commandprompt.Asanexample,downloadthefollowingmodelfilebyclicking

    on the following link and saving the file in the directory you are running

    MATLABfrom.

    simple.mdl

    Openthis file inSimulinkbyentering the followingcommand in theMATLAB

    commandwindow.(Alternatively,youcanloadthisfileusingtheOpenoptionin

    theFilemenuinSimulink,orbyhittingCtrlOinSimulink).

    simple

    Thefollowingmodelwindowshouldappear.

  • A new model can be created by selectingNew from the File menu in any

    Simulinkwindow(orbyhittingCtrlN).

    BasicElements

    TherearetwomajorclassesofitemsinSimulink:blocksandlines.Blocksare

    usedtogenerate,modify,combine,output,anddisplaysignals.Linesareused

    totransfersignalsfromoneblocktoanother.

    Blocks

    ThereareseveralgeneralclassesofblockswithintheSimulinklibrary:

    Sources:usedtogeneratevarioussignals

    Sinks:usedtooutputordisplaysignals

    Continuous: continuoustime system elements (transfer functions, state

    spacemodels,PIDcontrollers,etc.)

    Discrete:linear,discretetimesystemelements(discretetransferfunctions,

    discretestatespacemodels,etc.)

    Math Operations: contains many common math operations (gain, sum,

    product,absolutevalue,etc.)

    Ports&Subsystems:containsusefulblockstobuildasystem

    Blocks have zero to several input terminals and zero to several output

    terminals. Unused input terminals are indicated by a small open triangle.

    Unusedoutput terminalsare indicatedbyasmall triangularpoint.Theblock

    shownbelowhasanunusedinput terminalonthe leftandanunusedoutput

    terminalontheright.

  • Lines

    Linestransmitsignalsinthedirectionindicatedbythearrow.Linesmustalways

    transmitsignals from theoutput terminalofoneblock to the input terminalof

    anotherblock.Onexceptiontothisisalinecantapoffofanotherline,splitting

    the signal to each of two destination blocks, as shown below (click here to

    downloadthemodelfilecalledsplit.mdl).

    Lines can never inject a signal into another line lines must be combined

    throughtheuseofablocksuchasasummingjunction.

    A signal can be either a scalar signal or a vector signal. For SingleInput,

    SingleOutput (SISO) systems, scalar signals are generally used. For Multi

    Input,MultiOutput(MIMO)systems,vectorsignalsareoftenused,consistingof

    twoormorescalarsignals.Thelinesusedtotransmitscalarandvectorsignals

    areidentical.Thetypeofsignalcarriedbyalineisdeterminedbytheblockson

    eitherendoftheline.

    SimpleExample

  • (1)

    Thesimplemodelconsistsofthreeblocks:Step,TransferFunction,andScope.

    The Step is aSource block from which a step input signal originates. This

    signalistransferredthroughtheline inthedirectionindicatedbythearrowto

    theTransferFunctionContinuousblock.TheTransferFunctionblockmodifies

    itsinputsignalandoutputsanewsignalonalinetotheScope.TheScopeisa

    Sinkblockusedtodisplayasignalmuchlikeanoscilloscope.

    TherearemanymoretypesofblocksavailableinSimulink,someofwhichwill

    bediscussedlater.Rightnow,wewillexaminejustthethreewehaveusedin

    thesimplemodel.

    ModifyingBlocks

    Ablockcanbemodifiedbydoubleclickingonit.Forexample, ifyoudouble

    click on the TransferFunction block in the Simple model, you will see the

    followingdialogbox.

    Thisdialogboxcontains fields for thenumeratorand thedenominatorof the

    block'stransferfunction.Byenteringavectorcontainingthecoefficientsofthe

    desirednumeratorordenominatorpolynomial,thedesiredtransferfunctioncan

    beentered.Forexample,tochangethedenominatorto

  • (1)

    enterthefollowingintothedenominatorfield

    [124]

    andhittheclosebutton,themodelwindowwillchangetothefollowing,

    whichreflectsthechangeinthedenominatorofthetransferfunction.

    TheStep block can also be doubleclicked, bringing up the following dialog

    box.

    Thedefaultparametersinthisdialogboxgenerateastepfunctionoccurringat

    time=1sec,fromaninitiallevelofzerotoalevelof1(inotherwords,aunit

  • time=1sec,fromaninitiallevelofzerotoalevelof1(inotherwords,aunit

    step at t = 1). Each of these parameters can be changed.Close this dialog

    beforecontinuing.

    ThemostcomplicatedofthesethreeblocksintheScopeblock.Doubleclicking

    onthisbringsupablankoscilloscopescreen.

    Whenasimulationisperformed,thesignalwhichfeedsintothescopewillbe

    displayedinthiswindow.Detailedoperationofthescopewillnotbecoveredin

    this tutorial. The only function we will use is the autoscale button, which

    appearsasapairofbinocularsintheupperportionofthewindow.

    RunningSimulations

    Torunasimulation,wewillworkwiththefollowingmodelfile:

    simple2.mdl

    DownloadandopenthisfileinSimulinkfollowingthepreviousinstructionsfor

    thisfile.Youshouldseethefollowingmodelwindow.

  • Before running a simulation of this system, first open the scope window by

    doubleclickingonthescopeblock.Then,tostartthesimulation,eitherselect

    StartfromtheSimulationmenu,clickthePlaybuttonatthetopofthescreen,or

    hitCtrlT.

    Thesimulationshouldrunveryquicklyandthescopewindowwillappearas

    shownbelow.

    Notethatthesimulationoutput(showninyellow)isataverylowlevelrelative

    totheaxesofthescope.Tofixthis,hittheautoscalebutton(binoculars),which

    willrescaletheaxesasshownbelow.

  • Notethatthestepresponsedoesnotbeginuntilt=1.Thiscanbechangedby

    doubleclickingonthestepblock.Now,wewillchangetheparametersof the

    systemandsimulatethesystemagain.DoubleclickontheTransferFunction

    blockinthemodelwindowandchangethedenominatorto:

    [120400]

    Rerunthesimulation(hitCtrlT)andyoushouldseewhatappearsasa flat

    line in the scopewindow.Hit theautoscale button, and you should see the

    followinginthescopewindow.

    Noticethattheautoscalebuttononlychangestheverticalaxis.Sincethenew

    transferfunctionhasaveryfastresponse,itcompressedintoaverynarrowpart

    ofthescopewindow.Thisisnotreallyaproblemwiththescope,butwiththe

    simulation itself. Simulink simulated the system for a full ten seconds even

    thoughthesystemhadreachedsteadystateshortlyafteronesecond.

    Tocorrect this,youneedtochangetheparametersof thesimulation itself. In

    the model window, select Configuration Parameters from the Simulation

    menu.Youwillseethefollowingdialogbox.

  • Therearemanysimulationparameteroptionswewillonlybeconcernedwith

    thestartandstoptimes,whichtellSimulinkoverwhattimeperiodtoperformthe

    simulation.ChnageStarttimefrom0.0to0.8(sincethestepdoesn'toccuruntil

    t=1.0).ChangeStoptimefrom10.0to2.0,whichshouldbeonlyshortlyafter

    thesystemsettles.Closethedialogboxandrerunthesimulation.After hitting

    theautoscalebutton,thescopewindowshouldprovideamuchbetterdisplay

    ofthestepresponseasshownbelow.

    BuildingSystems

    In this section, you will learn how to build systems in Simulink using the

    building blocks in Simulink's Block Libraries. You will build the following

    system.

  • Ifyouwouldliketodownloadthecompletedmodel,clickhere.

    First,youwillgatherallofthenecessaryblocksfromtheblocklibraries.Then

    you will modify the blocks so they correspond to the blocks in the desired

    model. Finally, you will connect the blocks with lines to form the complete

    system.Afterthis,youwillsimulatethecompletesystemtoverifythatitworks.

    GatheringBlocks

    Followthestepsbelowtocollectthenecessaryblocks:

    Createanewmodel(NewfromtheFilemenuorhitCtrlN).Youwillgeta

    blankmodelwindow.

    ClickontheSourceslistinginthemainSimulinkwindow.

    ThiswillbringuptheSourcesblocklibrary.Sourcesareusedtogenerate

    signals.

  • Drag theStep block from theSources window into the left side of your

    modelwindow.

    ClickontheMathOperationslistinginthemainSimulinkwindow.

    Fromthislibrary,dragaSumandGainblock into themodelwindowand

    placethemtotherightoftheStepblockinthatorder.

    ClickontheContinuouslistinginthemainSimulinkwindow.

    First,fromthislibrary,dragaPIDControllerblock into themodelwindow

    andplaceittotherightoftheGainblock.

    From the same library, drag a Transfer Function block into the model

    windowandplaceittotherightofthePIDControllerblock.

  • ClickontheSinkslistinginthemainSimulinkwindow.

    DragtheScopeblockintotherightsideofthemodelwindow.

    ModifyBlocks

    Followthesestepstoproperlymodifytheblocksinyourmodel.

    DoubleclickontheSumblock.Sinceyouwillwantthesecondinputtobe

    subtracted,enter+intothelistofsignsfield.Closethedialogbox.

    DoubleclicktheGainblock.Changethegainto2.5andclosethedialog

    box.

    DoubleclickthePIDControllerblockandchangetheProportionalgainto

    1andtheIntegralgainto2.Closethedialogbox.

    Doubleclick the Transfer Function block. Leave the numerator [1], but

    changethedenominatorto[124].Closethedialogbox.Themodelshould

    appearas:

  • ChangethenameofthePIDControllerblock toPIController by double

    clickingonthewordPIDController.

    Similarly,changethenameoftheTransferFunctionblocktoPlant.Now,all

    theblocksareenteredproperly.Yourmodelshouldappearas:

  • ConnectingBlockswithLines

    Nowthattheblocksareproperlylaidout,youwillnowconnectthemtogether.

    Followthesesteps.

    DragthemousefromtheoutputterminaloftheStepblockto thepositive

    inputoftheSuminput.AnotheroptionistoclickontheStepblockandthen

    CtrlClickontheSumblocktoconnectthetwotogther.Youshouldseethe

    following.

    Theresultinglineshouldhaveafilledarrowhead.Ifthearrowheadisopen

    andred,asshownbelow,itmeansitisnotconnectedtoanything.

  • You can continue the partial line you just drew by treating the open

    arrowheadasanoutputterminalanddrawingjustasbefore.Alternatively,

    ifyouwanttoredrawtheline,orifthelineconnectedtothewrongterminal,

    you should delete the line and redraw it. To delete a line (or any other

    object),simplyclickonittoselectit,andhitthedeletekey.

    DrawalineconnectingtheSumblockoutputtotheGaininput.Alsodrawa

    linefromtheGaintothePIController,alinefromthePIController to the

    Plant,anda line from thePlant to theScope.You shouldnowhave the

    following.

    The line remaining to be drawn is the feedback signal connecting the

    output of thePlant to the negative input of theSum block. This line is

    differentintwoways.First,sincethislineloopsaroundanddoesnotsimply

    followtheshortest(rightangled)routesoitneedstobedrawninseveral

    stages.Second,thereisnooutputterminaltostartfrom,sothelinehasto

    tapoffofanexistingline.

    Draga lineoff thenegativeportionof theSum block straight down and

    releasethemousesothelineisincomplete.Fromtheendpointofthisline,

    click anddrag to the linebetween thePlant and theScope. The model

    shouldnowappearasfollows.

  • Finally,labelswillbeplacedinthemodeltoidentifythesignals.Toplacea

    labelanywhereinthemodel,doubleclickatthepointyouwantthelabelto

    be.StartbydoubleclickingabovethelineleadingfromtheStepblock.You

    willgetablanktextboxwithaneditingcursorasshownbelow.

    Typeanr in thisbox, labelingthereferencesignalandclickoutside it to

    endediting.

    Labeltheerror(e)signal,thecontrol(u)signal,andtheoutput(y)signalin

    thesamemanner.Yourfinalmodelshouldappearas:

  • Tosaveyourmodel,selectSaveAsintheFilemenuandtypeinanydesired

    modelname.Thecompletedmodelcanbefoundhere.

    Simulation

    Nowthatthemodeliscomplete,youcansimulatethemodel.SelectStartfrom

    theSimulationmenutorunthesimulation.Doubleclickonthe_Scope_block

    toviewitsoutput.Hittheautoscalebutton(binoculars)andyoushouldseethe

    following:

    TakingVariablesfromMATLAB

    Insomecases,parameters,suchasgain,maybecalculatedinMATLABtobe

    used inaSimulinkmodel. If this is the case, it is not necessary to enter the

    resultoftheMATLABcalculationdirectlyintoSimulink.Forexample,suppose

    wecalculatedthegaininMATLABinthevariableK.Emulatethisbyentering

    thefollowingcommandattheMATLABcommandprompt.

    K=2.5

    This variable cannowbeused in theSimulinkGain block. In your Simulink

    model,doubleclickontheGainblockandenterthefollowingtheGainfield.

    K

  • Close thisdialogbox.Noticenow that theGain block in theSimulinkmodel

    showsthevariableKratherthananumber.

    Now, you can rerun the simulation and view the output on the Scope. The

    resultshouldbethesameasbefore.

    Now, ifanycalculationsaredone inMATLABtochangeanyof thevariables

    usedintheSimulinkmodel,thesimulationwillusethenewvaluesthenexttime

    itisrun.Totrythis,inMATLAB,changethegain,K,byenteringthefollowingat

  • itisrun.Totrythis,inMATLAB,changethegain,K,byenteringthefollowingat

    thecommandprompt.

    K=5

    Start theSimulink simulation again, bring up theScopewindow, and hit the

    autoscale button. You will see the following output which reflects the new,

    highergain.

    Besides variables and signals, even entire systems can be exchanged

    betweenMATLABandSimulink.

    PublishedwithMATLAB7.14

    AllcontentslicensedunderaCreativeCommonsAttributionShareAlike4.0International

    License.