VisSim/Embedded Controls Developer for TI C2000

Download Report

Transcript VisSim/Embedded Controls Developer for TI C2000

VisSim for Dynamic Simulation and Control Design

Visual Solutions, Inc.

487 Groton Road, Westford MA 01886 USA (800) VISSIM-1 www.vissim.com

Agenda

• Morning – VisSim product line review – VisSim basics – Dynamic systems with feedback – Building hierarchical systems – Data import/export – System tuning with auto restart • Afternoon – Optimization – PID Tuning – 3D plotting & animation – UML State Charts

VisSim Overview

• Visual block diagram software for dynamic system simulation and embedded system development.

– Automatic production of high quality fixed point code – Exceptional dynamic and DSP-in-loop simulation capabilities – Automatic programming of on-chip DSP peripherals

Product Line

• VisSim Core Visual Simulation Tool - build, simulate and debug dynamic systems – Simulink Translator – State Transition block – Over 100 built-in blocks – Built-in C interpreter – Matlab interface – Royalty free redistributable Viewer

VisSim Viewer

• Free redistributable run-time version of VisSim • Download from www.vissim.com/downloads/demos.html

• Allows free distribution of models to anyone • Easy way to share ideas, models and simulations • Supply proof-of-concept simulations to potential customers

VisSim Add-ons

• Real-Time - Allows up to 30 kHz closed loop sampling from VisSim on PC • C-Code - Generates ANSI C from diagram • Analyze - Frequency domain analysis of linearized non-linear subsystem • Fixed-point - Block set of bit true scaled integer operations for simulation and code generation

VisSim Add-ons (cont.)

• Comm - Physical layer data communication • Optimize Pro - Generalized Reduced Gradient method of parameter optimization • Neural nets - Neural network construction and training package • DSP Targets - F243,LF2407, F2812, C30,C40,C67

VisSim/Real-Time

• Supports National Instruments and Measurement Computing • Analog (12-16 bit), digital, thermocouple, counter, PWM, encoder • Devices can be PCI, PCMCIA, USB, ISA • 30 kHz closed loop sampling straight from Windows/NT,XP – (Jitter ~1-5ms) • Just place block and select “Run in Real-Time” from Simulations Properties dialog.

VisSim/CAN

• VisSim driver for USB device that connects to Controller Area Network (CAN) bus • Can read and write CAN packets up to 1 kHz rate.

• Packets configurable as to: – data length – number and types of data elements in the packet – Byte sex (bigendian vs little endian) • Enable pin on write, data ready pin on read

VisSim/Motion

• Extensive block set for simulation of electric motor systems • Supports AC induction, brush and brushless DC motors • Stepper motors • Low level PWM switching simulation level • Selection of Sensors, Loads, Controllers, Transforms

VisSim/OPC

• OLE for Process Control • VisSim OPC block set has server connection block, OPC read and OPC write block • Connects to any server (Kepware, Matrikon etc.) Supports all major DCS, PLC vendors (Honeywell, Allen Bradley, Foxboro, GE Fanuc, Siemens, etc)

VisSim Plays Well with Others

• OLE interface- allows inclusion of any OLE compliant software – VisSim - Mathcad OLE interface allows graphics plus data exchange • VisSim - Matlab Integration allows matrix data exchange and Matlab expression evaluation • Simulink Translator brings Simulink diagrams into VisSim workspace.

VisSim Custom Block API

• MSVC Wizard creates project for custom block. Just drop in code.

• API allows: – Menu positioning – Block & connector naming and data typing – Code generation – Simulation info on integration method, integration step, time step, current time etc.

VisSim Co-simulation API

• VisSim co-simulation API allows fast, efficient interprocess communication for co-simulation interfacing.

• Based on NT shared memory and Events • In use by iLogix Statemate • General purpose API

Large Model Support

• Load 300,000 block model in under 2 minutes • Embed blocks insert separate component model files as subsystems • Path aliases allow macro expansion to remove file system dependencies • Tags allow quick navigation in large system

Diagram Construction

• Insert block by clicking toolbar icon or Block menu • Change parameter by double or right mouse click on block • Connect by mouse-down on connector, drag, mouse up on or near target connector • Must have consumer to execute (Plot, display, export etc.)

Exercise: Plot sin

     Insert sin and plot blocks Connect sin to plot and run Right click sin, change to 1 Hz, and run Double click plot title bar to enlarge Double click again to restore

Block manipulation

• Select blocks by left-mouse+drag background • Right click to operate on selected blocks • Edit menu also operates on selected blocks • Left-mouse+drag on any selected block moves group • Left click background to remove selection

Exercise: Add triangle wave

    Insert triangle wave to existing sin plot Connect triangle to plot and run Select sin and triangle blocks Right click one, select “align outputs”  Try and keep wires short and straight if possible

System Properties

• System/System Properties… • Sets start time/stop time for simulation • Sets step interval for both simulation and code gen • Auto-restart puts sim in continuous mode for Monte Carlo or parametric investigation • “Retain states”: states not initialized on restart • “Run in real-time” for real-time response • “RT Scale Factor” to run at some multiple faster or slower than real-time

Exercise: Change Time Range

    Select System Properties… Enable run in real time Run diagram again. Now it takes 10 real secs.

  Useful for monitoring embedded target > 1 kHz Data acquisition and control Change End Time to 1 sec, rerun

Simulation Debug

• Single step button (click single “shoe”) • Right click on connector to see value • Stop block allows user controlled stop point • Error block allows user controlled error alert • Interactive plots • Display blocks

Exercise: Basic 2

nd

order system

• Create new diagram • Insert and connect const “1” to two 1/S integrators and a plot.

• Input is acceleration, output is position, intermediate pin is velocity.

• Run (what is expected output?)

Exercise: More 2

nd

order system

• Put summing junction between const and 1/S • Output of 1 st 1/S is velocity, 2 nd is position • Put feedback gain from “position” to summer • Change sign on sum feedback (ctrl+right+click) • Run (what is expected output?) • x” = 1 + -kx

VisSim Variables

• VisSim variables allow data exchange by name instead of by wire – Create variables “u” and “y” to represent input and output to filter and wire to diagram. Use variable “find” operation. Note “Find definition only” option • Variable Scoping – “:” prefixed variables are scoped to current level – “::” prefixed variables are scoped to definition level and down

Usage of Variables

• Built-in variables: pi, $timeStart, $timeStep, $timeEnd, $runCount, $firstPass, $lastPass, $randomSeed • Variable block • Can use in many blocks as parameters: 1/S, gain, transferFunction, const etc.

• Expression block • Constants • Scoping (:prefix local, ::definition scope)

Exercise: More 2

nd

order system

• Change feedback gain to “k” • Insert Annotation >Variable block • Right+click and name “K” • Insert Signal Producer > slider block, cx to var • Right+click and change bounds to 0 to 10 • Run

Finding Blocks or Variables

• Edit/Find… dialog lets you search for variables or blocks • Can look only for definitions • Case sensitivity • Partial match • Match on block type

Plot Options

• • • • • • • Right click to configure -> Most options obvious Plot averaging filters data points over multiple runs Marker count of -1 marks all points Multiple XY traces uses pairs of inputs for each trace Line type controls paint style of data points Max plotted points limits total # of points in sim range (0 plots all points)

Plot Options(cont)

• • • • • “External Trigger” places enable pin on plot and only plots when pin is 1 “Read Coordinates” enables interactive coordinate readout “Snap to Data” restrict readout to actual data points “Over Plot” retains data run to run “Save Data to File” saves current plot data to a file

Exercise: Add damping term to 2

nd

order system

• • • • Add pin to sum input (Edit > Add Connector, then

click next to existing connector when grey bar

appears) and ctrl+right+click to toggle sign Add new gain called kDamp Copy/paste slider and “k” var rename var to “kDamp” and reconnect

Numerical Integration

• Change time step for 2nd order system • Notice instability at large step relative to system frequency • Euler is simplest fastest, least accurate • Adaptive step are most accurate • Stiff good for solving “stiff” sets of equations (hi freq component that has small amplitude)

Exercise: Change integration step and method for 2

nd

order system

• • • Change time step to .5

Run, and see divergence due to numerical instability Change integration method to adaptive step and see that system is now stable – Adaptive step tries smaller steps to see if it improves results – Gives good answer but is slow

Limited and Reset Integral

• Limited Integrator lets you specify upper and lower limits for the internal state. Avoids “windup” of limit block and plain integrator – Wire slider->limited integrator->plot – Connect const 50 to u, and 0 to l of limited integ – Set to “run in real-time”, click 'go' and play with slider – Add 1/s in parallel and plot both outputs. Notice “windup” • Reset Integrator allows you to reset internal state on the fly. (See bounce.vsm)

Plot Axis Settings

• • • • • Bounds set here for “fixed bounds” option Scaling is applied to x axis Sub Plot Count gives multiple y-axis windows Axis divisions fixes tick count manually Retrace options restricts plot to given interval and sets x-axis interval (used for eye-diagrams)

View Options

• Presentation Mode: Prettier diagrams • Display Mode: for front panels and animation • Data Types: colors connectors based on data type. Green=integer, yellow=scaled integer, red=floating point, purple=matrix – Fat wires=Matrix, thin wire=scalar • Block labels appear under block • Connector labels appear on compound block or user function block

Hierarchy

• Edit/Create Compound… creates container for selection • Edit/Add Connector.. gets “Add” cursor. Click cursor on block to add connectors. Click left side to add on left edge, right side to add right.

• Edit/Remove Connector… gets “Remove” cursor. Click cursor on block to remove connectors. Click left side to remove on left edge, right side to remove from right.

• Ctrl+Right-Mouse on Compound to edit subsystem properties • Click Right-Mouse on Compound to enter compound • Click Right-Mouse on background to leave compound • Double-Left click on connector to add label

Subsystem Properties

• Local Time – allows running at slower rate than main sim. Must be multiple of base clock for DSP targeting.

• External Trigger – Use external logic to control execution of subsystem.

• Name – Applies name to face of block • Bitmap- Applies bitmap image to face of block • Password protection – Use password to control access to compound contents • Create dialog box from contained dialog constants

User Dialog Box

• Insert “Dialog Constant” blocks into compound contents for each dialog item.

• Dialog constants can be numeric, integer list, or boolean.

• Check “Create dialog box from contained dialog constants” option in compound block.

• User selections are saved to .vsm file.

• Nice way to encapsulate complexity.

Exercise: Create compound from 2

nd

order system

• Select 2 nd order system, right click on a selected block and create compound • Insert dialog constants for feedback gains • Ks (spring const) Kd (damping factor) • Label input and output pins • Enable “create dialog from contained dialog constants” in compound properties • Right click compound to see user dialog • Run

Labeling

• Use label block to insert label anywhere in diagram • Label can be hyperlink to doc or URL • Doc can link to .vsm label • Double left click Compound connector to give a label • Use Comment block to put large body of scrollable rich text into diagram

System Setup: Preferences

• Checkpoint state: saves integrator, delay states and plot contents to file – Useful for restarting from known state • Notify Sim End: gives message box on sim end • Warn nonintegral clock: gives warning at sim start if requested time step for periodic signal like pulseTrain, squareWave etc. is not integral multiple of sim timeStep.

• Warn nonintegral delay: warn if continuous delay is given time delay that is not integral multiple of timeStep • Checkpoint during sim: saves checkpointed diagram to file with name suffixed with current time at specified checkpoint intervals.

• Check Connections: warns of unconnected inputs at sim start.

• Warn numeric overflow: warn if conversion causes numeric truncation • Startup Script file: Specify .m or .c file to run before starting sim • Random Seed: specify starting random seed for random variables.

• Frequency Units: specify units for filter design wizards in transfer function

Conditionals (“if-then”)

• • Relational expressions can be used anywhere Merge and case use a selector input to produce an output from several possible inputs – Create new diagram with button, merge, 2 consts and display

Dialog Table

• Inserts parametric data from an external data set or spread sheet.

• User selects item from 1 st dropdown combo.

column via • See Diagrams > examples > blocks > signalProducer > dialogTable.vsm

Exercise: Build IIR Filter 1

• Place step, xfer, and plot blocks in workspace • Connect & run • Change sim rate to .001, end time to .1

• Design 2nd order 100Hz Butterworth lowpass filter • run

Build filter 2

• Ctrl-Rt quick dup xfer, convert copy from S->Z domain • run • enable fixed point precision • run • change to 2 bits magnitude • run - zoom plot

FIR filter

• Rt-click xfer, check “discrete”, click FIR Filter button • For each band, enter start, end freq, weight & gain • Be sure to leave room between end of one band and start of next • Click “Calc Filter” • FIR requires large state count (>10) for good operation

Discrete systems

• 1/Z sampled delay - clock input • Discrete transfer function • Sample hold • Other blocks work with both continuous and discrete systems • Compound block can be enabled, or run at different sampling rate • Work with scaled fixed-point data

Data Import/Export/Lookup Table

• Import block – Can import text data, .mat, .wav

– Optional header supplies time start/stop/step info • Export block – Can export text, .mat, .wav

– Can control data flush interval, inclusion of import header • Map block – 1D, 2D, 3D lookup tables

Import Export Usage

• How to use...

– Place sin block and export in work space, configure export for file name “test.dat”, wire sin to export and run. Note possibility for decimation, data flush interval, and suppression of header information.

– Place import block in diagram, configure for “test.dat”, connect to plot, and run. Note possibility for interpolation and extrapolation.

Import/Export features

• Import block

– Option for ‘,’ as decimal point – Allows text data column. Treats as null.

– Accepts hh:mm:ss.ff time notation as data element

• Export block

– Option for ‘,’ as decimal point – Can make data export background task

Matrix Operations

• All arithmetics (add,mul,div,gain etc) • Const block takes matrix syntax ([1:n],eye(n) etc.

• Unit delay, merge, plot, display all take matrix operations • Matrix mul, buffer, dot product, vector sum, diag, PSD, fft,ifft,transpose,reshape,index

Q&A - Lunch

• 1 hour

Put .vsm files on VisSim menu

• Save to directory structure that you want mirrored in VisSim menu • Edit > Preferences… > Menu Directories – Double click “…” – Add directory path to be put on menu and menu name to be stored under – Next time you restart VisSim, all .vsm files in directory tree will appear on VisSim menu

Optimization

• Built-in optimizer can find optimal system parameters – Open diagram \vissim80\examples\SystemID\2ndOrder6DOF.vsm

– Note that cost function can be anything, but a good one is integral of square error between test function and data set

Issues when optimizing

• OptimizePro addon will restrict parameter search to bounds in parameterUnknown blocks. Built-in solver will not.

• Do not simply sum multiple error terms for cost function, as terms may cancel. Terms must be squared or abs() before sum.

• Try to minimize # of unknowns as optimization can bog down with too many unknowns • If using real-world plant, allow settling time between runs • Cost function is typically integration of sum of square error

• • • •

PID Tuning

ParameterUnknown blocks for PID terms Use overshoot penalty to find stable solution Use sliders with simple plant in auto-restart mode to examine the PID response space Good paper “PID Control System Analysis & Design” Feb 2006, IEEE Control Systems Magazine ↑ KP ↑ KI ↑ KD Effects of independent P, I, and D tuning on closed-loop response.

Rise Time - Overshoot ++ ++ - Settling Time + ++ - Steady-State Error - -- ~ - derivative term can degrade stability if plant has transport delay - 80% of PID controllers in use have the derivative part switched off Stability Degrade Degrade Improve

PID structures

• Simple 3 term: y = e(x)(K p + K – Implement s (d/dx) via zero/pole, zero gives derivative, pole is tuned for low pass filter.

i /s + K d s) • If T i ≥ 4T D can do series PD-PI: y =e(x)+ T D

s) K

P (1 +1/αT i

s)

Where α =(1 ± √(1 − 4T D

/ T

i ) )/2 > 0 • Examine response w/autorestart, sample plant, and sliders for gains.

• Can be helpful to fix d/dt coef by hand and opt P and I

State Transition Block

• Allows creation of any number of states • Each state has any number of transition conditions to change to another state • Conditions are written in C code and may reference VisSim variables (must be syntactic C – no space or punctuation in name) • Block output is current state, and rule that last fired to enter this state • VisSim lets you use state names anywhere you can use expressions, like const and expression blocks

3D Plotting

• 3D plot block takes time sequence of 3 element vectors for xyz position • Use mouse to rotate and zoom plot even while simulation running • See Diagrams > Examples > New in 7.0 >

3D Animation

• Manipulate individual meshes • Manipulate objects in 3D VRML (.wrl) file • Manipulate scene elements with mouse • Control “camera” (view angle, position) programatically • See Diagrams > Examples > New in 7.0 > Lunar Lander Game

Event Logging

• Event log quietly tracks time-stamped events • Signal Consumer > EventLog takes event string and boolean enable pin to send text to log • Signal Consumer > EventDisplay gives display of all events in run • VisSim/RT and VisSim/OPC have quiet eventLog mode

VisSim/OPC Client

• OPC server block select server connection and connection mode (continous connection vs sim run connection) • OPC read/write blocks select tags to read and write.

• Works with any OPC server

Scaled Fixed-Point Operations

• Arithmetics (add,mul,div,gain etc) • Limit, unit delay, merge, map, PI regulator • Hands-on • Make sample diagram of sin->FixPt gain->plot • run - observe high/low values in block.

• Change scaling to 13.16. Run. Observe plot • Change sin amplitude to 4, scaling to 1.16

• Run. Enable Tools/FixedPoint Configure… Autoscale. Rerun.

VisSim/Embedded Controls Developer

• Bundle of VisSim, C-Code, C2000 target, TI DMC block-set , fixed-point block set, TI Code Composer Studio plug-in • Supports F243, LF2407, F2812 on-chip peripherals: Analog in, PWM, CAN, encoder, event capture, serial, SPI, I/O ports, watch dog

DSP Target Support

• Texas Instruments: TMS320F243, LF2407, F2812,F2808,C31, C32, C44, C54xx,C67xx • Card Vendors: Innovative Integrations, California Spectrum Digital, Houston, Texas Softbaugh, Atlanta, GA

Debug, Test, and Validate

Minimize time spent in debug and test • • • • Use high-level, pre debugged blocks Support simulation of controller at block level on PC Allow mouse probe of every input and output to display values at any instant Debug block-level simulation on PC

Debug and Validation

Pure simulation plus DSP-in-loop simulation and block level monitoring gives rapid feedback of controller response

VisSim on PC

Peripheral Input Blocks C2000 TM DSP Peripheral Output Blocks External Hardware (I/O Only) VisSim block diagram

• • • •

User Blocks DMC Blocks Fixed-Point Blocks

Test DSP based controller against virtual plant on PC using JTAG HotLink

Standard Blocks

Inject plant failure modes to test controller response High/Low watermark on fixed-point blocks gives numerical “headroom” safety factor Interactive DSP utilization gives continuous CPU load factor Interactively Change DSP controller gains from VisSim and plot DSP response.

Debug and Validate

Rapid diagram edit-compile-download-debug cycle (under 10 secs)

Plant Under Control

• • •

C2000 Peripherals

Control Application Code *

JTAG * Code automatically generated, compiled, linked, and downloaded VisSim on PC

VisSim Interface block downloads and monitors code running on DSP C2000 DSP

• • •

VisSim blocks for: Virtual plant Interactive gains Plots of DSP response

DSP-in-loop simulation of controller at code level on DSP through automatic code generation, compile, link, and download, and using JTAG in Real-Time Monitor mode Test, debug, and validate the complete control system executing on DSP using an interface block Provide test input vectors and observe DSP results in VisSim on PC

Build AC - induction DSP in loop

• Open AC induction motor speed control system – C:\visSim50\Embed_Controls_Developer\c2407(281 2)eZdsp\QuickStart\acim_spd_control_qs.vsm

• Run and observe pure simulation results • Select controller, click Tools/Codgen…, click “Include VisSim Comm Interface” • Push “Codegen” button 7

Insert DSP component

• Delete simulated controller • Insert VisSim/DSP|C2407(F28xx)|DSPinterface block • Wire up in diagram same as simulated controller • Save diagram as -d.vsm

Add blinking LED to controller

• Add blink logic to sim model – Hint LED connected to C0 (2407) or F14 (F2812) • Re-codegen • Re-rerun DSP based version • Compare F2812 waveforms to LF2407 – Difference is due to increased JTAG delays in 2407 part

Burn FLASH

• Create FLASHable blink program and burn to flash.

Note that 2812 must use Spectrum Digital FLASH utility.

Break

• 15 min

Basic pressure-flow system

• Pressure differential causes flow • Integral of flow into a volume gives current mass occupying the volume • P volume = nRT/V

Review of User Diagram

Look at specific customer diagram

On-chip peripherals

• All on-board DSP peripherals supported including: analog inputs (outputs on EVM) digital inputs and outputs simple PWMs and full compare PWMs quadrature encoder event capture, watch dog, interrupt, CAN bus serial port SPI I/O ports

TI Digital Motor Control (DMC) Library

– written by TI in C-callable assembler – hand-written, tested and optimized by TI – available in VisSim/ECD in easy-to-use block set – supports simulation mode (pure PC based simulation with 16-bit truncation effects) – supports code generation mode

Custom Block Creation

• VisSim DLL Wizard for MSVC • Automatically creates project with code for creating block, naming block, pin count and pin names, data types, dialog for parameters • VisSim exported function vissimRequest() allows query of VisSim properties: current time, time step, current block handle, block properties.

– DLL exported function: Event(eventCode, p1, p2) is called by VisSim on interesting events like sim start, end, step, code gen, mouse click