VisSim for Embedded Control System Development Visual Solutions, Inc. 487 Groton Road, Westford MA 01886 USA (800) VISSIM-1 www.vissim.com Agenda • Morning – VisSim ECD Overview • • • • • On-chip peripherals Scheduling Interrupt Handling Integrating User Code Afternoon – VisSim hands-on instruction – Sensorless FOC demo – MCU-in-loop hands on instruction – DMC and Motion block set review What is Model Based Development? • Simply stated, a development methodology where you create a model of your application, simulate it, then generate code from the validated simulation. • VisSim lets you: – – – – Run plant and controller in single sim Run plant as sim against embedded control Run simulated control against real plant Run embedded control against real plant What is an Embedded System? • CPU+nonvolatile memory (flash [optional HD]) – Flash memory is “burned” with control application – Boots into application on power up – Uses sensors (ADC,QEP,CAP,SPI…) and actuators (PWM, DAC, SPI…) • Characteristics of embedded systems – More RAM and flash => $$ – Faster CPU clock =>$$ – MMU? = memory mapping unit – runs Linux, cell phone, PDA etc. Motor controllers don’t have MMU, don’t run Linux • Still want to talk to supervisor or monitor (serial,CAN etc.) What is VisSim/Embedded Controls Developer? • Bundle of VisSim, C-Code, target support, TI DMC block-set , fixed-point block set, TI Code Composer Studio plug-in – Target support includes JTAG download and Hotlink, peripheral support, stack and heap probe • Supports C2000 and MSP430 on-chip peripherals: ADC, PWM, CAN, encoder, event capture, serial, SPI, I2C, watch dog The VisSim RTOS • VisSim provides a simple RTOS environment – Main low jitter (submicrosecond) control thread runs at time step as set in diagram “System Properties…” – Unlimited number of preemptable (high jitter) background threads – (option in Compound block) • Jitter = variation in actual time step from specification – Schedule synchronous tasks from main thread – Efficient device drivers for on-chip peripherals – Handle interrupts directly in VisSim (option in Compound block) – Interrupt based soft queued I/O for serial, SPI and I2C Task Scheduling • Ctrl+Right-Mouse on Compound to edit subsystem properties – “Enabled Execution” controls whether subsystem runs – “Local Time Step” runs subsystem at custom synchronous decimated rate from main clock. – “Codegen as Separate Thread” runs subsystem at custom rate but as preempted background thread. Good for lowering load on main control task Pre-emptive Multi tasking • Base diagram runs at System Properties Rate – VisSim generates code to set “RTOS” Timer 2 to fire interrupts at spec’ed rate, and sets diagram code as interrupt handler • Idle loop runs between interrupts – Background tasks scheduled from idle loop Interrupt Handling • “Execute on Interrupt“ Compound block property causes subsystem to execute on occurrance of selected interrupt. Subsystem can read diagram data or hardware registers and send data via global variables or output pins. The Code gen Dialog • • • From Tools > Code gen… Result file Select Target – Device below on right • • • • • • Include Compound names as comments On-Chip RAM (no external RAM) Target Flash (put code in flash memory) Minimize RAM Usage (uses no numerical integration) Call from Foreign RTOS (generate 3 functions, init, idle loop schedule and rate, to be called from custom application or RTOS) Include VisSim Communication Interface (add PC communication task to target. Boot waits for PC handshake before starting controller) Linking VisSim to Compiler • Codegen dialog “Compile” button runs batch script • VisSim runs \vissim80\cg\<tgt>cl.bat calls dsp<dev Class>cl.bat calls setdsp<dc>.bat – for F280x: f280xcl.bat, dsp28xcl.bat,setdsp2x.bat – CCS path must be set in dosrun28.bat – Custom .obj’s must be listed in f280xcl.bat under “set USER_OBJS=“ • VisSim install links to cgtools in existing CCS install – CCS v5 supported – If CCS is updated, edit file “\vissim80\cg\dosrun28.bat “ and change the line “set CG5DIR=C:\Program Files (x86)\Texas Instruments\ccsv4\tools\compiler\C2000 Code Generation Tools 5.2.6” to new install path The C2000 Family • Cost from $1 to $20/part • Speed from 40Mhz (Piccolo) to 300 MHz (Delfino) • RAM from 6k to 1 Meg • Flash from 32k to 512K (High end 200+ MHz parts have no flash) • On-chip ADC, PWM, QEP, I2C, SPI, Serial, CAN, USB Memory Map on C2000 • On-chip RAM (zero wait-state) • On-chip flash (1 wait state) – Boot and execute directly from flash • Off-chip RAM – Only available for EMIF parts (Defino) • Off-chip flash – used for boot, copy to RAM – Access via SPI or I2C Flash wait cycles • To synchronize with slower flash memory, CPU must wait a certain number of cycles: – – – – 5 on a 150 MHz device 3 on a 100 MHz device 2 on a 60 MHz device 1 on a 40 MHz device • Caching helps but TI performance estimates are: – – – – 90 - 95 MIPS at 150 MHz 80 - 85 MIPS at 100 MHz 50 - 55 MIPS at 60 MHz 37 - 39 MIPS at 40 MHz Speedup Options • Since RAM so much faster on 150 MHz parts, TI provides option to copy flash based functions to RAM on boot • Move noncritical functions to background thread • Schedule synchronous functions to run at slower rate (integer multiple of base time step) C2000 Memory Layout F2808 Memory Map Peripheral Frame contains device control registers, RAM and flash used for code or data. VisSim uses M0M1 as stack, L0L1H0 as code/data. Mechanics of .out file creation • Generated .c file is automatically compiled to .obj • Linker creates .out file by combining .obj with TI support library, VisSim support libraries • Linker .cmd file controls memory allocation. – VisSim supplies 4 .cmd files. One for running with VisSim communication, one for running standalone from on-chip RAM, one for running standalone FLASH, and one for running with code composer – You can control location of data and program memory. Default for prototyping is on-chip RAM for program and external RAM for data Memory Layout Control • VisSim provides .cmd files customized to device. – Memory descriptors are found in \vissim80\cg\lib\<dev><x>lnk.cmd – Where <x>: f=>flash, s=>stand alone, c=>Code Composer, “”=>JTAG Hotlink • You can alter if need be. – When debugging in pure RAM, may need to change allocation of code vs data. – Linker gives error if not enough RAM is allocated to code or data ADC • • • • • • Insert digital/Analog Input Up to 16 ADC channels 12 bit sampling Up to 6 MHz operation Channels 0-7 on bank A, 8-15 on bank B Triggered from software, SOCA/SOCB, GPIO ADC Config • • • • Delfino/280x dumber than Piccolo Set ADCCLK Sample duration Full scale = 1 avoids 3v scaling, inline ADCRESULT ref • Set bank A/B sample trigger. – SOC is sent from PWM unit • Channel order spec allows arbitrary mapping of ADC input pins to ADCRESULT reg Piccolo ADC • Each chan has own trigger src • Each chan has sample duration setting • Pairs of channels can be sampled simultaneously 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. Fixed point toolbox • Diagrams > Toolbox > Fixed Point • • • • • • • 3PhaseSin-variable freq 3PhaseSinSrc cascadeable counter Count Down Count Up Detect Falling Edge Detect Rising Edge Integ16 Integ32 OneShot PI16 PI32 PI32test PID16 PID16test PID32 Ramp16 ramp32-variable freq Ramp32 Resettable Counter Resettable Max Resettable One Shot SpeedCalc32 Toggle State on Pulse triangle16 triangle32 VariableFrequencyRamp32 Exercise: Create Blink program • Insert MCU Config… – Set to target to F28027 and JTAG link xds100v2 • Insert and wire: Blocks > Signal Producer > Square Wave Embedded > Piccolo > Digital/Analog Output – – Configure block as Digital, bit width 1, LED connected to GPIO 0 & 1 • Save As…: test28027.vsm • Select Tools > Codegen > Compile – Then Download > Download Exercise: change Blink pattern • Modify to blink on 10 millisec, off 990 millisec – Hint – Launchpad LED is active low – Hint – set time step to .01, use pulseTrain with 1 sec period to drive GPIO Exercize: Add ADC to blink • Add ADC0 block to blink.vsm and create subsystem • Select all blocks, right click on selected block • Choose “create compound”, give name “blink” – “blink” should have 1 output: ADC0 • Configure ADC0 • File > Save As: test28027.vsm • Tools > Codegen… Compile with “Include VisSim Communication” to read ADC values to PC via JTAG Create Debug Diagram • File > Save As: test28027-d.vsm • Select “blink” compound and hit delete key • Insert Embedded > Piccolo > targetInterface block – It will be configured with previously compiled .out file • Wire to plot • Select System > System Properties… > Run in Real Time Run Debug Diagram • Click Go to download test28027.out file from targetInterface block and read ADC0 values from target – Put finger on ADC0 pin to generate 60 Hz signal – Notice LED blinking Exercise: Add Output to Source • Go back to test28027 source diagram – Add square wave output to “blink” – and recompile. • Go back to test28027-d debug diagram – Right mouse targetInterface and add 1 to output – Connect new pin to plot • Run Exercise: Create Multi-Rate Sys • To Create Multi-rate System – Set System > System Properties… > Time Step to .001 – Compile, switch to debug diagram and run • Right Click Target Interface and set rate to 1000 Hz • Notice blink is dim at 1ms blink interval – Inside “blink” compound, select all blocks except ADC and create 100Hz compound • Ctrl+Right click compound • Set local step to .01 and Codegen as Separate Thread – Compile, switch to debug diagram and run • Notice blink is brighter at 10ms blink interval Exercise: Create Digital Scope • In Source diagram, add Monitor Buffer Write inside “blink” compound – Set monitor buffer to 200 elements – Wire to ADC0 – Recompile top level “blink” • In Debug Diagram add Monitor Buffer Read and Plot – Insert 2nd plot, configure with external trigger and fixed bounds (0-1) – Connect Monitor “Trig” to plot trigger, “Buffer” to plot pin • Click Go to see ADC readings in digital scope Run Multi-rate sys • In newly saved diagram multiRate-d – Insert targetInterface block and wire to plot. • It will be set to .out file from previous compile. – Insert monitorBufferRead and wire to 2nd plot – Click Go to see ADC readings and blink Exercize: Save Scope Data to File • In Debug diagram, add export block – Connect to Monitor Buffer Read – Rt click and add file name • Run • Create new file ePWM Config • Time Base – Allows sync w/previous unit – Dynamic period change – Fixed/dynamic phase change • Action Qualifier – Shapes waveform for A&B • Deadband – Overrides AQ for B • ADC conversion pulse syncs ADC w/PWM waveform • Trip Zone allows PWM reset from external pin Exercize: Trigger ADC from PWM • Open last ADC diagram with PWM • Choose “ADC Config…” • Under ADCRESULT0 Choose Trigger:EPWM1 SOCA • Right click EPWM1 block, select CTR = PRD under “Send start ADC conversion pulse A (SOCA) • Compile and run Drive Demo from Quick Start Guide • Open Embedded > Examples > Piccolo > Chip Temp on F28069 • Select Tools > Code Gen… – Check “Include Vissim Communication Interface” – Click “Compile…”, Dismiss DOS window, Quit • Open Embedded > Examples > Piccolo > Chip Temp on F28069-d (Companion Debug Diagram) – Right click “MCU Config…”. Verify JTAG is XDS100v2 – Click Go ( ) button Drive Demo from Quick Start Guide • Open Embedded > Examples > Piccolo > FFT28069 • Select Tools > Code Gen… – Check “Include Vissim Communication Interface” – Click “Compile…”, Dismiss DOS window, Quit • Open Embedded > Examples > Piccolo > FFT28069d (Companion Debug Diagram) – Right click “MCU Config…”. Verify JTAG is XDS100 – Click Go ( ) button eQEP Configuration • Quadrature Encoder – – – – – – Unit select Count mode Counter reset event Rev Count Signal inversion Set mux pin assignments eCap • Captures up to 4 TTL edge events • Set max events • Choose edge direction and reset for each event • Allows measurement of PWM width or encoder pulse CAN Config • • • • • • • Unit select Prescale TSeg1/2 (up to 1 MHz) Sample Point Sync Jump Width Sync Edge Byte Order CAN Block Receive • • • • CAN is Ether net for control Msg flag pin Data Pins Dialog to set: Unit select Output Count Message ID Masking Register (allows receipt of addr range) Mux Pin Extended (29 bit) addresses Dynamic address CAN Block Transmit • • • Enable pin to start Tx Up to 4 16-bit data pins Dialog to set: Unit Input Count Mailbox number (32 available) - Each active Tx/Rx must have unique mailbox Message ID Mux Pin Extended (29 bit) addresses Remote Trans Req (poll address) Auto Answer Mode (reply to RTR poll) Dynamic address Dynamic data length CAN Transmit Ready Block • Produces true value when mailbox is ready to transmit. Used to gate CAN Transmit block. • Works with one of the 32 CAN “mailboxes” Serial (SCI) Configuration • Port, Bit rate, Data Bits, Parity, Stop bits • Tx/Rx Queue Length – Uses FIFO register to minimize interrupt rate – Handles FIFO differences between devices • Mux Pin Assignment Handling Serial Queue • Serial Port Write puts byte in queue • Serial Port Read can read: – Data from queue – Current bytes in Rx/Tx queue – Rx/Tx max length – Rx Empty/Tx Full – Port Hardware Status Bits Handling Serial Packets • Sent packet bytes must be written in proper order. VisSim orders parallel flows top down. – Packets are decoded in enabled compounds – Compound is enabled when enough bytes have arrived to fill packet or there is room in TX queue for write packet • Received packets must be decoded, typically through state machine. V7 has StateTransition block, V8 provides State Chart addon. SPI – Serial Peripheral Interface • Simple 4 wire master/ slave serial connection – – – – SCLK — Serial Clock (output from master) MOSI/SIMO — Master Output, Slave Input (master) MISO/SOMI — Master Input, Slave Output (slave) SS — Slave Select (active low, output from master) • Cheap, no transceiver required • Can daisy chain large number • Up to 25 MHz operation I2C = Inter Integrated Chip • Low cost 2 wire interface • Speeds from 10 kHz – 1MHz • “CAN bus” like w/128 unique addresses • Data packet can be of any length. • Master or slave mode • Build packet then send Start Tx • Often used to read/write EEPROM I2C EEProm Example • See Embedded > Examples > Delfino > eepromF28435 • Uses StateTransition block to control timing of address write/data read transaction • Read EEProm has 2 stages: write of address, followed by read of data • Write has 1 stage: address followed by data in single packet Watchdog • Watchdog causes reboot if not “fed” proper binary key within set interval • Just insert Watchdog block and configure interval to enable. VisSim will feed at sample rate. • Can force reboot by putting watchdog in enable block and “withholding food” Task Scheduling • Ctrl+Right-Mouse on Compound to edit subsystem properties – “Enabled Execution” controls whether subsystem runs – “Local Time Step” runs subsystem at custom synchronous decimated rate from main clock. – “Codegen as Separate Thread” runs subsystem at custom rate but as preempted background thread. Good for lowering load on main control task Interrupt Handling • “Execute on Interrupt“ Compound block property causes subsystem to execute on occurrance of selected interrupt. Subsystem can read diagram data or hardware registers and send data via global variables or output pins. Exercize: Create Interrupt Handler • Create new diagram, save as “intHandler” • Add “Diagrams > Toolbox > Fixedpoint > countUp” – Connect const 1 to input clk – Connect output cnt to variable “InterruptCount” • Select all and create compound “Int on GPIO12” – Double click output pin, label as “intCnt” • Ctrl+Right click on compound – Check “Execute on Interrupt” – Select “XINT1”, GPIO12, Interrupt on rising edge • Insert “InterruptCount” var and GPIO12 read • Select all and create top compound “Interrupt Count” Exercize: Test Interrupt Handler • Select “Interrupt Count” compound • Tools > Codegen… – Check Include VisSim Interface – Click Compile • Insert Embedded > Piccolo > targetInterface block • Connect intCnt output of targetInterface block to plot • Run • On launchpad, press button, or jumper GPIO12 from +V3 to Gnd 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. Variable Access • VisSim variable names are retained in the generated code. Globals and definition scoped variables are C “static” file scope. Locals (“:” prefix) are stack based function locals. • The Extern Read and Extern Write blocks allow reading and writing of external C variables or hardware registers. VisSim Digital Power Block Set • This is a VisSim addon that includes blocks and tools for embedded digital power simulation and code generations • Applications from sub 1-watt to megawatt: – AC-DC converters with three-phase PFC – DC-AC inverters – DC-DC converters • Release date Q3 2011 Simulation Vout Iout Vin Vpr Ipr Vs • • • • • Average Converter Models Switching Converter Models Controllers Sensors Sources, power filters and loads • MCU Peripheral Emulators SW Flyback Converter iC Vsw Isw Vd Id Load (%) Iin iCin Vfb Imeas Peak Current Control PWM Ith Voltage Mode Control Vfb Verr Imeas Iin Hall Sensor PWM1 PWM2 Verr L1 Vo 3-phase Supply L2 L3 Freq Ain (Volts) ADC Aout (4.16) DC1(1.16) GPI (Volts) GPIO GPIout TZx TZy SYNCI Ain (Volts) Ref (Volts) / DACin(6.16) PWM1 DC2(1.16) Comparator DAC PWM2 Piccolo ePWM SOCA SOCB SYNCO COMPout (Volts) DACout (Volts) DPBS Simulation Environment Familiar Analog Environment Control Design with Average Models and VisSim Analyze Products from an ECD customer Complete and highly flexible digital control of: • high-power isolated AC-DC converters (30kW parallelable modules) with three-phase PFC • Control of high-power DC-AC inverters • Control of high-power DC-DC converters • Rugged protocols using the SPI interface • Complex serial protocols using the SCI interface • EEPROM communication using I2C Products cont. • Real-time reliable communication between converters using the CAN bus interface • Realization of all practical measurements – rms voltage, rms current, real power, reactive power, PF, CF, THD etc. • Simultaneous control of high-power 3-phase PFC, isolated full-bridge converter and DC/DC regulator, all in current mode, using a single MCU at 20kHz ISR sample rate. Build 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 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 Q&A - Lunch • 45 min Sensorless PMSM Motor Control • Runs on TI DRV8312EVM Dev Kit with 3-1/2 HBridge power MOSFET chips. – Chip handles complementary PWM mode, so only drive upper half H-Bridge with single PWM signal. • controller samples at 10 KHz on F28035. • 100 Hz background task to stage motor startup, open loop/closed loop operation and blink LEDs • Uses 5.3k flash, 2.7k RAM (800 words of debug buffering) Debug, Test, and Validate • Minimize time spent in debug and test • Use high-level, predebugged 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 Validate • Rapid diagram edit-compile-download-debug cycle (under 10 secs) * Code automatically generated, compiled, linked, and downloaded VisSim on PC Plant Under Control C2000 Peripherals Control Application Code* C2000 DSP JTAG VisSim Interface block downloads and monitors code running on 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 MIL test • Open AC induction motor speed control system – C:\visSim80\Embed_Controls_Developer\F280x\Qui ckStart\acim_spd_control_qs32.vsm • Run and observe pure simulation results • Select MCU, click Tools/Codegen…, click “Include VisSim Comm Interface” • Click “Compile” button 7 Create Debug Diagram • Save diagram as <filename>-d.vsm – This will be our “debug” diagram. This step is only done once, then the edit debug cycle moves between the original diagram and the debug until desired system performance is attained. • Insert VisSim/DSP>F280x>DSPinterface block – It is automatically populated with the .out file created in previous slide • Replace ACI Controller with DSPinterface block • Run diagram. The embedded controller is now running the virtual motor. – Due to JTAG latency (1-10ms) response will not be as good as pure simulation Burn FLASH • Compile blink program with “Target Flash” enabled • And burn to flash. – Note that you must use CCS flash plugin Break • 15 min 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 bit true truncation effects) – supports code generation mode VisSim Motion Block Set • Motion Block Set - Preconstructed block set for motion control – – – – – Includes AC Induction Brush and brushless DC Stepper motors Controllers Rotational and translational loads. 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 Questions • ??