Home
Fixed-Point Blockset User's Guide
Contents
1. 1 ET ey l Original fixed point signal 0 4 an l E D a 1 Dead Zone signal 1 Js Input Ports Any data type supported by the blockset Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Yes of parameters 10 59 Dead Zone Dynamic Purpose Library Description Parameters and Dialog Box Characteristics See Also 10 60 Set inputs within the bounds to zero Nonlinear The Dead Zone Dynamic block is a masked block that dynamically bounds the range of theinput signal providing a region of zero output The bounds change according to the upper and lower limit input signals where e The input within the bounds is set to zero e The input below the lower limit is shifted down by the lower limit e The input above the upper limit is shifted down by the upper limit The input for the upper limit is the up port and the input for the lower limit is the lo port Block Parameters Dead Zone Dynamic Output zero for inputs within deadzone Offset input signals by either the Fixed Point Dead Zone Dynamic mask link Es or End value when outside of the deadzone E Cancel Help Apply Input Port Any data type supported by the b
2. 10 27 BitClear seor mare Oo iones 10 29 Bit Sebit a a A AE A SG A 10 30 Bitwise Operator 0 0 cece nanana 10 31 Compare To Constant 0 0 cece eee 10 35 Compare To Zero 2 eee 10 36 CONnStANE jini A Ba ee ea ae eer 10 37 CONVERSION arica atar vaa baad Peek eaten 10 40 Conversion Inherited o oooooooooommmmm o o 10 42 COSINE rumana arta EA de nee a GA RENE a te 10 44 Counter Free iis alates Soe cated atada aaa 10 45 Counter Limited usa a RA I AS a 10 46 Data Type Duplicate 0 cee ee 10 47 Data Type Propagation 0 0 00 c eee eee 10 49 DCA ZOMG 5s oye E EN tainted oa S 10 58 Dead Zone Dynamic 00 cee 10 60 Decrement Real World 0 00 cece eee eee eee 10 61 Decrement Stored Integer 0 06 e eee eee 10 62 Decrement Time TO Zero 1 eee 10 63 Decrement TO Zero ce ete eee 10 64 Den iVatiIVE azi Tata Se a es ca ar Baw Bese a RR a 10 65 Detect Change sa AA e ak ad 10 67 Detect Decrease 1 0 cee cette nees 10 68 Detect Fall Negative 0 0c eee eee 10 69 Detect Fall Nonpositive 0 0 0 c eee eee eee eee 10 70 Detect INCreaS 6 eet teens 10 71 Detect Rise Nonnegative sssusa sasaaa rarnana 10 72 Detect Rise Positive iui ptor OOE eee 10 73 DIANA Ce iiss a o ew als Od ia Meta a 10 74 Dot PRODUCE vasta ee wen eaten Wee cta a 10 76 Filter Direct Form oo cc ee eee 10 78 vii viii Contents Filter Direct
3. r Fixed Point Switch mask link Input 2 is used to evaluate a logical expression If the expression is true pass input 1 otherwise pass through input 3 m Parameters Criteria for passing first input Threshold Threshold fi Output data type and scaling Inherit via internal rule y Round toward Floor ha I Saturate to max or min when overflows occur Y Log minimums and maximums Cancel Help Apply Threshold Switch threshold that determines which input is passed to the output 10 195 Switch Conversions Characteristics See Also 10 196 Output data type and scaling Inherit the output data type and scaling from the driving block or by back propagation Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Log minimums and maximums If checked minimum and maximum simulation values are logged tothe workspace The Threshold parameter is converted offline to the second input s data type using round to nearest and saturation Refer to Parameter Conversions on page 4 27 for more information about parameter conversions Input Ports Any data type supported by the blockset Output Port Same as input port one Direct Feedthrough Yes Scalar Expansion Yes MultiPort Switch Tapped Delay Purpose Library Description 4 Delays P P
4. 5 f 10 10 10 10 10 Freq rad sec 100 F 7 200 Ni Phase 300 F 7 400 107 10 10 10 10 Freq rad sec 6 6 Digital Controller Realization Digital Controller Realization The digital controller is implemented using a fixed point direct form realization The target is a 16 bit processor Variables and coefficients are generally represented using 16 bits especially if these quantities are stored in ROM or global RAM Use of 32 bit numbers is limited to temporary variables that exist briefly in CPU registers or in astack Therealization is shown below F Convert Int E FE Up Cast Numerator Terms Convert from Multiply and accumulate Out1 A2D Type most recent inputs and Lp F to BaseType numerator coefficients Convert in the accumulator gt E E Combine Terms Down Cast Reduce output from accumulator size to base memory size Combine numerator and denominator contributions to TF in accumulator fae ZE E Prev Out Denominator Terms Store most recent output in memory for one sample time Multiply and accumulate most recent outputs and denominator coefficients in accumulator The realization consists of these blocks Conversion The Up Cast block connects the A D hardware with the digital controller It pads the output word of the A D hardware with trailing zeros to a 16 bit number the base
5. Operator Specify how the input is compared to zero Input Port Any data type supported by the blockset Output Port An 8 bit unsigned integer Direct Feedthrough Yes Scalar Expansion N A Compare To Constant Constant Purpose Library Description Generate a constant value Sources The Constant block is a masked S function that generates a constant value Y ou specify constants with the Constant value parameter A constant can be a scalar or a vector Y ou specify the output scaling with the Output scaling parameter Note that there are two dialog box parameters that control the output scaling one associated with an edit field and one associated with a parameter list If Output data type is a generalized fixed point number such as sfix 16 the Output scaling parameter list provides you with these scaling modes e Use Specified Scaling This mode uses the slope bias or radix point only scaling specified for the editable Output scaling parameter for example 2 10 e Best Precision Vector wise This mode produces a common radix point for each element of the Constant value vector based on the best precision for the largest value of the vector For a detailed description of all other block parameters refer to Block Parameters on page 10 4 10 37 Constant Parameters and Dialog Box 10 38 Block Parameters Constant m Fixed Point Constant mask link Generate a consta
6. Generating Pure Integer Code Example Generating Pure Integer Code Using the Simulink Accelerator Using External Mode or rsim Target External Mode Rapid Simulation Target Customizing Generated Code Macros Versus Functions SENE Bit Sizes for Target C Compiler A 2 A 3 A 3 A 3 AB A 3 A 4 A 4 A 4 A 5 A 5 A 11 A 12 A 12 A 12 A 13 A 13 A 13 A Code Generation Overview With the Real Time Workshop the Fixed Point Blockset can generate C code The code generated from fixed point blocks uses only integer types and automatically includes all operations such as shifts needed to account for differences in fixed point locations You can use the generated code on embedded fixed point processors or rapid prototyping systems even if they contain a floating point processor The codeis structured sothat key operations can be readily replaced by optimized target specific libraries that you supply You can also use the Target Language Compiler to customize the generated code For more information about code generation refer to the Real Time Workshop User s Guide and the Target Language Compiler Reference Guide Y ou can also generate code for testing on a rapid prototyping system such as xPC the Real Time Windows Target or SPACE The target compiler and processor may support floating point operations in software or in hardware In any case the fixed point
7. gt negative negative positive positive overflow underflow underflow overflow Floating Point N umbers where e Normalized positive numbers are defined within the range 217 Plas to 2 2 2bias e Normalized negative numbers are defined within the range 21 7 Pias to 2 bias e Positive numbers greater than 2 2 f 2P 35 and negative numbers greater than 2 27f 29135 are overflows e Positivenumbers less than 2 Pias and negative numbers less than 21 bias are either underflows or denormalized numbers e Zerois given by a special bit pattern where e 0 and f 0 Overflows and underflows result from exceptional arithmetic conditions Floating point numbers outside the defined range are always mapped to inf Note You can usethe MATLAB commands realmin and realmax to determine the dynamic range of double precision floating point values for your computer Precision Due toa finite word size a floating point number is only an approximation of the true value Therefore it is important to have an understanding of the precision or accuracy of a floating point result In general a value v with an accuracy q is specified by v q For IEEE floating point numbers v D 2 amp P S Lf and q 2 28 b as Thus the precision is associated with the number of bits in the fraction field Note In MATLAB floating point relative accuracy is given by the command eps which returns th
8. NaNs A NaN not a number is a symbolic entity encoded in floating point format There are two types of NaNs signaling and quiet A signaling NaN signals an invalid operation exception A quiet NaN propagates through almost every arithmetic operation without signaling an exception NaNs are produced by these operations co Ox 0 0 and o o Both types of NaNs are represented by the largest biased exponent allowed by the format and a fraction that is nonzero The bit pattern for a quiet NaN is given by 0 f where the most significant number in f must bea one while the bit pattern for a signaling NaN is given by 0 f where the most significant number in f must be zero and at least one of the remaining numbers must be nonzero 3 23 3 Data Types and Scaling 3 24 Arithmetic Operations Overview Limitations on Precision Rounding Padding with Trailing Zeros Example Limitations on Precision and Errors Example Maximizing Precision Limitations on Range Saturation and ees Guard Bits Example Limitations on Range Recommendations for Arithmetic and Scaling Addition bg a we Accumulation Multiplication Gain Division Summary Parameter and Signal Conversions Parameter Conversions Signal Conversions Rules for Arithmetic Operations Computational Units ae Addition and Subtraction Multiplication Division Shifts Example Conversions and Arithmetic Operations
9. Output a discrete time sequence and repeat interpolating between data points Output a discrete time sequence and repeat 10 21 Abs Purpose Library Description Parameters and Dialog Box Characteristics 10 22 Output the absolute value of the input Math The Abs block is a masked S function that outputs the absolute value of the input For signed data types the absolute value of the most negative value is problematic since it is not representable by the data type In this case the behavior of the block is controlled by the Saturate to max or min when overflows occur check box If checked the absolute value of the data type saturates to the most positive value If not checked the absolute value of the most negative value has no effect For example suppose the block input is an 8 bit signed integer The range of this data type is from 128 to 127 and the absolute value of 128 is not representable If the Saturate to max or min when overflows occur check box is checked then the absolute value of 128 is 127 If it is not checked then the absolute value of 128 remains at 128 Block Parameters Abs Fixed Point Absolute Value mask link ott Value of a Signal Parameters Cancel Help Apply Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Input Port Any data type supported by the blockset Output Port Same
10. Parameters and Dialog Box Characteristics See Also Block Parameters Unit Delay With Preview Resettable r Fixed Point State Resettable mask link Unit Delays With Preview have two outputs instead of just one Normally the first output equals the signal u and the second output is a unit delayed version of the first output Having both signals is useful for implementing recursive calculations where the result should include the most recent inputs The second output of a Unit Delay With Preview can be safely feedback into calculations of the block s inputs without causing an algebraic loop Meanwhile the first output will show the most up to date calculations The external reset signal R works with the internal initial condition When the reset signal R is true the first output signal is forced to equal the initial condition The second output signal is not affected until one time step later The internal initial condition is also used to initialize the state when the model starts or when a parent enabled subsystem is reset This reset action is vectorized and supports scalar expansion m Parameters Initial condition ee Sample time fe Cancel Help Apply Initial condition Initial condition Sample time Sample time Input Port u Any data type supported by the blockset Input Port R Any data type supported by the blockset Output Ports Same as the input u Direct Feedthrough Y
11. e The output is true not 0 when the input signal is greater than or equal to zero and its previous value was less than zero e The output is false equal to 0 when the input signal is less than zero or if nonnegative its previous value was greater than or equal to zero Block Parameters Detect Rise Nonnegative m Fixed Point Detect Rise Nonnegative mask flink If the input is nonnegative and its previous value was strictly negative then output TRUE otherwise output false E Cancel Help Apply Input Port Any data type supported by the blockset Output Port An 8 bit unsigned integer Direct Feedthrough Yes Scalar Expansion Yes Vectorized Yes Detect Change and related blocks Detect Rise Positive Purpose Library Description U gt O amp NOT Pp Ux gt 0 Parameters and Dialog Box Characteristics See Also Detect a rising edge when a signal s value increases to a strictly positive value and its previous value was nonpositive Edge Detect The Detect Rise Positive block is a masked block that determines if the input is strictly positive and its previous value was nonpositive where e The output is true not 0 when the input signal is greater than zero and its previous value was less than zero e The output is false equal to 0 when the input is negative or zero or if the input is positive its previous value was also positive Block Parameters Detect Rise Positive
12. 4 3 43 4 9 4 10 4 11 4 12 4 13 415 4 15 4 16 4 16 4 19 4 20 4 21 4 23 4 25 4 26 4 27 4 27 4 30 4 30 4 30 4 35 4 39 4 41 4 46 4 Arithmetic O perations Overview When developing a dynamic system using floating point arithmetic you generally don t have to worry about numerical limitations since floating point data types have high precision and range Conversely when working with fixed point arithmetic you must consider these factors when developing dynamic systems e Overflow Adding two sufficiently large negative or positive values can producea result that does not fit into the representation This will have an adverse effect on the control system Quantization Fixed point values are rounded Therefore the output signal tothe plant and the input signal to the control system do not have the same characteristics as the ideal discrete time signal Computational noise The accumulated errors that result from the rounding of individual terms within the realization introduces noise into the control signal Limit cycles In the ideal system the output of a stable transfer function digital filter approaches some constant for a constant input With quantization limit cycles occur where the output oscillates between two values in steady state This chapter describes the limitations involved when arithmetic operations are performed using encoded fi
13. Example code Function names syntax Keys Literal strings in syntax descriptions in reference chapters Mathematical expressions MATLAB output Menu titles menu items dialog boxes and controls New terms Omitted input arguments String variables froma finite list Monospace font Monospace font Boldface with an initial capital letter Monospace bold for literals Italics for variables Standard text font for functions operators and constants Monospace font Boldface with an initial capital letter Italics ellipsis denotes all of the input output arguments from preceding syntaxes Monospace italics To assign the value 5 toA enter A 5 The cos function finds the cosine of each array element Syntax line example is MLGetVar ML_var_name Press the Return key f freqspace n whole This vector represents the polynomial p X 2x 3 MATLAB responds with A 5 Choose the File menu An array is an ordered collection of information c ia ib union sysc d2c sysd method xviii Introduction Physical Quantities and Measurement Scales Selecting a Measurement Scale i Example Selecting a Measurement Scale Why Use Fixed Point Hardware Why Use the Fixed Point Blockset The Development Cycle Compatibility with Simulink Blocks Frame based Signals D es Matrix Signals How to Get Online Help 1 11 1 13
14. Fixed Point Rate Limiter Dynamic mask link im rising and falling rates of signals E Cancel Help Apply Characteristics Input Ports Any data type supported by the blockset Output Port Same data type as input u Direct Feedthrough Yes Scalar Expansion Yes See Also Rate Limiter 10 170 Relational Operator Purpose Library Description Perform the specified relational operation on the inputs Logic Comparison The Relational Operator block is a masked S function that performs a comparison of its two inputs The first top input is converted to the data type of the second bottom input prior to comparison The operator connecting the two inputs is selected with the Operator parameter list The supported relational operators are given below Operation Description TRUE if the first input is equal to the second input TRUE if the first input is not equal to the second input lt TRUE if the first input is less than the second input lt TRUE if the first input is less than or equal to the second input gt TRUE if the first input is greater than or equal to the second input gt TRUE if the first input is greater than the second input The output is specified with the Logical output data type parameter The output equals 1 for TRUE and O for FALSE Note The output data type selected should represent zero exactly Data types that satisfy this condition include signed and unsigned inte
15. For a detailed description of all other block parameters refer to Block Parameters on page 10 4 10 97 Gain Parameters and Dialog Box 10 98 Block Parameters Gain r Fixed Point Gain mask link Multiply the input by a constant gain m Parameters Gain value fi q Gain data type and scaling Specify via dialog y Parameter data type ex sfix 16 uint 8 float single sti 16 Parameter scaling Slope er 29 E 14 Parameter scaling Best Precision Matrix wise x Output data type and scaling Specity via dialog Output data type ex sfix 16 uint 8 float single fet 6 Dutput scaling Slope or Slope Bias ex 2 9 2710 FF Lock output scaling so autoscaling tool can t change it Round toward Floor y FF Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Multiplication Element wise K u 5d coa i a Gain value Specify as a vector or scalar Parameter data type Any data type supported by the Fixed Point Blockset Parameter scaling Radix point only or slope bias scaling Additionally if Gain value is specified as a vector it can be scaled using the constant vector scaling modes for maximizing precision These scaling modes are available only for generalized fixed point data types Output data type and scaling Specify the output data type and scaling via the dialog box o
16. Overflows Fixed point values that overflow will saturate to the maximum or minimum value represented by the word The resulting real world and fixed point simulation results are shown below The simulation clearly demonstrates the quantization effects of fixed point arithmetic The combination of using a 5 bit word with a precision of 1 2 0 25 produces a discretized output that does not span the full range of the input signal If you want to span the complete range of the input signal with 5 bits using radix point only scaling then your only option is to sacrifice precision Hence the output scaling would be given by 27 1 which puts the radix point one place to the left of the rightmost bit This scaling gives a maximum value of 0111 1 7 5 a minimum value of 1000 0 8 0 and a precision of 1 2 0 5 2 12 Example Converting from Doubles to Fixed Point Trial 2 Slope Bias Scaling When using slope bias scaling your goal is to find the optimal fractional slope F and fixed power of two exponent E as defined in Selecting the Output Scaling on page 2 5 No bias is required for this example since the sine wave is defined on the interval 5 5 The Gateway In block configuration is the same as that of the previous trial except for the scaling To arrive at a value for the slope you can begin by assuming a fixed power of two exponent of 2 In the previous trial this value defined the radix point
17. Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Same as the input u Direct Feedthrough Yes of the input and reset source ports Scalar Expansion Of inputs and gain Integrator Backward and related blocks 10 135 Interval Test Purpose Library Description Parameters and Dialog Box 10 136 Determine if a signal is in a specified interval Logic amp Comparison The nterval Test block outputs TRUE if the input is between the values specified by the Lower limit and Upper limit parameters The block outputs FALSE if the input is outside those values The output of the block when the input is equal tothe Lower limit or the Upper limit is determined by whether the boxes next to Interval closed on left and Interval closed on right are checked in the dialog box Block Parameters Interval Test r Fixed Point Interval Test mask link If the input is in the interval between the lower limit and the upper limit then the output is TRUE otherwise it is FALSE Parameters Upp A IV Interval closed on left Lower limit jos Cancel Help Epp Interval closed on
18. 1 0 15625 19 20 84375 1 40 84375 1 0 078125 9 10 921875 1 20 921875 1 0 0390625 4 5 9609375 1 10 9609375 1 0 01953125 1 5 3 48046875 1 5 98046875 1 0 009765625 0 25 2 240234375 1 3 490234375 1 0 0048828125 0 375 1 6201171875 1 2 2451171875 3 11 3 Data Types and Scaling 3 12 Example Constant Scaling for Best Precision The Fixed Point Blockset provides you with block specific modes for scaling constant vectors and constant matrices These scaling modes are based on radix point only scaling and are described below Constant Vector Scaling Using this mode you can scale a constant vector such that its precision is maximized element by element or a common radix point is found based on the best precision for the largest value of the vector Constant Matrix Scaling Using this mode you can scale a constant matrix such that its precision is maximized element by element or a common radix point is found based on the best precision for the largest value of each row each column or the whole matrix Constant matrix and constant vector scaling are available only for generalized fixed point data types All other fixed point data types use their default scaling The available constant matrix scaling modes are shown below for the Matrix Gain block Fixed Point N umbers Block Parameters Matrix Gain r Fixed Point Matrix Gain mask link Multiply the input by a constant gain m Parameters
19. 1 17 1 17 1 18 1 Introduction Physical Quantities and Measurement Scales A measurement of a physical quantity can take many numerical forms For example the boiling point of water is 100 degrees Celsius 212 degrees Fahrenheit 373 degrees Kelvin or 671 4 degrees Rankine No matter what number is given the physical quantity is exactly the same The numbers are different because four different scales are used Well known standard scales like Celsius are very convenient for the exchange of information However there are situations where it makes sense to create and use unique nonstandard scales These situations usually involve making the most of a limited resource For example nonstandard scales allow map makers to get the maximum detail on a fixed size sheet of paper A typical road atlas of the USA will show each state on a two page display The scale of inches to miles will be unique for most states By usinga largeratio of miles toinches all of Texas can fit on two pages Using the same scale for Rhode sland would make poor use of the page Using a much smaller ratio of miles to inches would allow Rhode Island to be shown with the maximum possible detail Fitting measurements of a variable inside an embedded processor is similar to fitting a state map on a piece of paper The map scale should allow all the boundaries of the state to fit on the page Similarly the binary scale for a measurement should allow the m
20. 9 10 converting from doubles to fixed point 2 10 division process 4 40 fixed point format 3 7 fixed point scaling 3 10 FixPt Bitwise Operator 10 34 FixPt FIR 10 96 FixPt Gateway In 10 102 FixPt Look Up Table 10 144 FixPt Look Up Table 2D 10 153 generating pure integer code A 5 limitations on precision and errors 4 10 limitations on range 4 15 maximizing precision 4 11 multiplication process 4 37 saturation and wrapping 4 13 selecting a measurement scale 1 4 shifting bits and the radix point 4 42 shifting bits but not the radix point 4 44 summation process 4 32 exceptional arithmetic 3 22 exponent for IEEE numbers 3 18 external mode A 12 F feedback design 6 3 filter digital 5 2 fix 4 4 fixed point interface tool 9 28 and feedback controller demo 6 9 fixed point numbers general format 3 3 scaling 3 5 fixpt_convert 9 8 fixpt_convert_prep 9 13 fixptbestexp 9 6 fixptbestprec 9 7 FixPtSimRanges 10 9 float 9 24 9 25 floating point numbers 3 18 floor 4 8 fpupdate 9 26 fraction for IEEE numbers 3 18 fractional numbers 2 4 and guard bits 4 15 fractional slope 3 5 frame based signals 1 17 fxptdlg 9 28 G gain 10 97 matrix gain 10 155 scaling recommendations 4 22 4 23 using slope bias encoding 4 21 gateway fixed point to Simulink 10 107 Simulink to fixed point 10 100 Simulink to fixed point inherited 10 105 generalized fixed point numbers 2 4 Generic Real Time Target A 5 global override with doubles 6 12 gua
21. Cancel Help Apply State Matrix A M atrix of states Input Matrix B Column vector of inputs Output Matrix C Column vector of outputs Direct Feedthrough Matrix D Matrix for direct feedthrough State Space Characteristics Initial condition for state Initial condition for the state Data type for internal calculations Data type for internal calculations Some examples are sfix 16 unit 8 and float single Scaling for State Equation AX BU Scaling for state equations Scaling for Output Equation CX DU Scaling for output equations Lock output scaling so autoscaling tool can t change it If the box is checked the output scaling is locked Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset it must be a scalar Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of initial conditions Vectorized No 10 191 Sum Purpose Library Description 10 192 Add or subtract inputs Math TheSum block is a masked S function that performs addition or subtraction on its inputs Y ou spec
22. Description ve Parameters and Dialog Box Characteristics 10 110 Increase the real world value of the signal by one Math The Increment Real World block is a masked block that increases the real world value of the signal by one Overflows always wrap Block Parameters Increment Real World Fixed Point Real World Value Increment mask Increase the Real World Value of Signal by 1 0 Dverflows will always wrap y La Cancel Help Apply Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion No Increment Stored Integer Purpose Library Description EN Parameters and Dialog Box Characteristics See Also Increase the stored integer value of a signal by one Math Thelncrement Stored Integer block is a masked block that increases the stored integer value of a signal by one Floating point signals are also increased by one and overflows always wrap Block Parameters Increment Stored Integer Fixed Point Stored Integer Value Increment mask Increase the Stored Value of Signal by 1 Floating Point signals are increased by 1 0 Overflows will always wrap E Cancel Help So i Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion No Increment Real World 10 111 Integer Delay Purpose Library Description 4 gt
23. Treat mask as Stored Integer Cancel Help Apply Operator The bitwise logical operator associated with the specified operands Use bit mask Specify if the bit mask is used single input only Number of input ports The number of inputs Bit mask The bit mask to associate with a single input Treat mask as Treat the mask as a real world value or as an integer The Bit mask parameter is converted from a double to the input data type offline using round to nearest and saturation Refer to Parameter Conversions on page 4 27 for more information about parameter conversions 10 33 Bitwise Operator Example Characteristics 10 34 To help you understand the Bitwise Operator block logic operations consider the fixed point model shown below 10111100 Constanti Constant2 The Constant blocks are configured to output an 8 bit unsigned integer uint 8 The results for all logic operations are shown below Operation Binary Value Decimal Value AND 00101000 40 OR 11111101 253 NAND 11010111 215 NOR 00000010 2 XOR 11111000 248 NOT N A N A Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough No Scalar Expansion Of inputs Compare To Constant Purpose Library Description Parameters and Dialog Box Characteristics Determine if a signal is equal to the specified constant Logic Comparison The Compare To Consta
24. fixpt_restore_links res fixpt_restore_links SystemName res fixpt_restore_links SystemName AutoSave res fixpt_restore_links restores broken links for the fixed point blocks contained in the model or subsystem specified by bdroot By default the models and libraries containing restored block links areleft open and unsaved res contains the names of the blocks that had broken links restored res fixpt_restore_links SystemName restores links for thefixed point blocks contained in the model or subsystem specified by SystemName res fixpt_restore_links SystemName AutoSave determines the state of the models or subsystems containing restored block links If AutoSave is on the models or subsystems are saved and closed If AutoSave is off the models or subsystems are unsaved and left open Breaking library links to fixed point blocks will almost certainly produce an error when you attempt to run the model If broken links exist you will likely uncover them when upgrading to the latest release of the Fixed Point Blockset float Purpose Syntax Description Example See Also Create a MATLAB structure describing a floating point data type a float single a float double a float TotalBits ExpBits float single returns a MATLAB structure that describes the data type of an IEEE single 32 total bits 8 exponent bits float double returns a MATLAB structure that describes the data type o
25. lt lt 3 sum in2 lt lt 1 Characteristics Input Port Any built in Simulink data type Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion No 10 104 Gateway In Inherited Purpose Convert a Simulink data type to a Fixed Point Blockset data type and inherit the data type and scaling Library Data Type Description The Gateway In Inherited block is a masked S function that converts a built in J Simulink data type to a Fixed Point Blockset data type yP The block requires two inputs The first top input provides the data type and scaling information The second bottom input passes through to the output and inherits the data type and scaling of thefirst input If you want to explicitly specify the output data type and scaling use the Gateway In block The Input and Output to have equal parameter list controls how the input is processed The possible values are Real World Value and Stored Integer n terms of the general encoding scheme described in Scaling on page 3 5 Real World Value treats the input as V SQ B whereS is the slope and B is the bias Stored Integer treats the input as a stored integer Q For more information about this parameter list refer to the Gateway In block For a detailed description of all other block parameters refer to Block Parameters on page 10 4 Remarks Inheriting the data type and scaling provides these advantages e It makes reusi
26. Conversions are discussed in Signal Conversions on page 4 27 Note that a loss in precision of one bit occurs with the resulting value of Qt emp determined by the rounding mode For this example round to floor is used Furthermore overflow did not occur but is possible for this operation 3 Theresult of step 2 and the third number 1 8125 are multiplied QrawProduct 01101 1010 x 1 1101 1101 1010 24 1101 1010 2 1101 1010 27 1101 1010 2 0011000 10110010 24 6953125 Note that the radix point of the product is given by the sum of the radix points of the multiplied numbers 4 The product is converted to the output data type Rules for Arithmetic O perations Qa convert Qr awProduct 011000 1011 24 6875 Conversions are discussed in Signal Conversions on page 4 27 Note that a loss in precision of four bits occurred with the resulting value of Qr emp determined by the rounding mode For this example round to floor is used Furthermore overflow did not occur but is possible for this operation Blocks that perform multiplication include the Product FIR Gain and Matrix Gain blocks Division As with multiplication division with mismatched scaling is complicated Mismatched division is permitted for simulation only F or code generation and bit true simulation the signals must all have zero biases and matched fractional slopes Fixed Point Blockset Division Process Consider the divisi
27. Direct Feedthrough Yes Conversion 10 43 Cosine Purpose Library Description cosi2 pfu P Parameters and Dialog Box Characteristics 10 44 Implement a cosine function in fixed point using a lookup table approach that exploits quarter wave symmetry LookUp The Cosine block implements a cosine function using a lookup table that exploits quarter wave symmetry The output is normally a signed 16 bit number with 14 bits to the right of the binary point Block Parameters Cosine r Fixed Point Cosine mask link Implement a Cosine function in Fixed Point using a lookup table approach that exploits quarter wave symmetry The output is normally a signed 16 bit number with 14 bits to the right of the binary point The most efficient implementation is obtained when the number of data points is a power of 2 plus 1 For example 2 5 1 m Parameters Number of data points for lookup table eo TT Cancel Help Apply Number of data points for lookup table The number of data points in the lookup table Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion N A Counter Free Purpose Library Description VI Parameters and Dialog Box Characteristics Count up and overflow back to zero after the maximum value possible is reached for the specified number of bits Sources The Free Counter block
28. If checked fixed point overflows saturate Otherwise they wrap Difference Characteristics Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of inputs and gain 10 75 Dot Product Purpose Generate the dot product Library Math Description The Dot Product block is a masked S function that generates the dot product of its two input vectors The scalar output y is equal to the MATLAB operation y sum conj u1 u2 where u1 and u2 represent the inputs If both inputs are vectors they must be the same length For a detailed description of all block parameters refer to Block Parameters on page 10 4 For more information about converting from one Fixed Point Blockset data type to another refer to Signal Conversions on page 4 27 Parameters Block Paranee Det Piadual and Dia log Box Fixed Point Dot Product mask link Inner dot product y sum conj u1 u2 m Parameters Dutput data type and scaling Specify via dialog Output data type ex sfix 16 uint 8 float single sfix 16 Output scaling Slope or Slope Bias ex 2 9 27 10 I Lock output scaling so autoscaling
29. Stair sequence sf 6_En14 a yUneven wl sfx 6_En14 yEven sfix16_En14 Fl yPow2 Poni Sine hppeos Scope Ready 100 FixedStepDiscrete Data ROM Required This section looks at the data ROM required by each of the three spacing options Uneven Case Uneven spacing requires both Y data points and breakpoints inti6_T yuneven 8 uint16_T xuneven 8 Thetotal bytes used is 32 Even Case Even spacing requires only Y data points int16_T yeven 10 Thetotal bytes used is 20 The breakpoints are not explicitly required The code will use the spacing between the breakpoints and may use the smallest and largest breakpoint At most three values related tothe breakpoints are needed 8 21 8 Producing Lookup Table Data 8 22 Power of Two Case Power of two spacing requires only Y data points int16_T ypow2 17 Thetotal bytes used is 34 The breakpoints are not explicitly required The code will use the spacing between the breakpoints and may use the smallest and largest breakpoint At most three values related to the breakpoints are needed Determining Out of Range Inputs In all three cases you haveto guard against the possibility that theinput is less than the smallest breakpoint or greater than the biggest breakpoint There may be differences in how occurrences of these possibilities are handled However the differences are generally minor and arenormally not a key facto
30. Switch on point A Switch off point D Output when on xi A 2 Output when off 0 Output data type and scaling Specify via dialog y Output data type ex sfix 16 uint 8 float single uint 8 FT Override data type s with doubles Cancel Help Apply Switch on point The on threshold for the relay Switch off point The off threshold for the relay Output when on The output when the relay is on Output when off The output when the relay is off Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling by back propagation Output data type Any data type supported by the Fixed Point Blockset If you specify ufix the Output Scaling field appears in the dialog box If you then select Use Specified Scaling in the Output Scaling field you can enter the scaling for the output in the Output Scaling Slope or Slope Bias field 10 174 Relay Override data type s with doubles If checked the Output data type is overridden with doubles Conversions Both the Switch on point and Switch off point parameters are converted to the input data type offline using round to nearest and saturation Characteristics Input Port Any data type supported by the blockset Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Yes 10 175 Repeating Sequence Interpolated Purpose Out
31. The Detect Decrease block is a masked block that determines if an input is strictly less than its previous value where e The output is true not 0 when the input signal is less than its previous value e The output is false equal to 0 when the input signal is greater than or equal to its previous value Block Parameters Detect Decrease Fixed Point Detect Decrease mask link If the input is strictly less than its previous value then output TRUE otherwise output false Y Cancel Help p Input Port Any data type supported by the blockset Output Port An 8 bit unsigned integer Direct Feedthrough Yes Scalar Expansion Yes Vectorized Yes Detect Change and related blocks Detect Fall Negative Purpose Library Description U lt 0 amp NOT P Uz 0 Parameters and Dialog Box Characteristics See Also Detect a falling edge when the signal s value decreases to a strictly negative value and its previous value was nonnegative Edge Detect The Detect Fall Negative block is a masked block that determines if the input is less than zero and its previous value was greater than or equal to zero where e The output is true not 0 when the input signal is less than zero and its previous value was greater than or equal to zero e Theoutput is false equal to 0 when the input signal is greater than or equal to zero or if the input signal is nonnegative its previous value was positive
32. a collection of demos is provided Y ou can explore specific blockset features by changing block parameters and observing the effects of those changes The demos are divided into two groups basic demos that illustrate the basic functionality of the Fixed Point Blockset and advanced demos that illustrate the functionality of systems and filters built with fixed point blocks All demos are located in the fxpdemos directory Y ou can access the demos through MATLAB s Demo browser Y ou launch the Demo browser by opening the Demos block found in the Fixed Point Blockset library or by typing demo blockset Fixed Point at the command line Y ou can also type the name of a particular demo at the command line Basic Demos The basic demos are listed below Table 2 1 Basic Fixed Point Blockset Demos Demo Name Description Double to Fixed Point Conversion Fixed PointtoFixed Point Conversion Fixed PointtoFixed Point Inherited Conversion Fixed Point Sine Convert a double precision value to a fixed point value Convert a fixed point value to another fixed point value Convert a fixed point value to an inherited fixed point value Add and multiply two fixed point sine wave signals 2 15 2 G etting Started 2 16 Table 2 1 Basic Fixed Point Blockset Demos Continued Demo Name Description Scaling a Fixed Point Simulate a fixed point feedback design Control Design Generating Only G
33. also has floating point support The Development C ycle The Development Cycle The Fixed Point Blockset provides tools that aid in the development and testing of fixed point dynamic systems Y ou directly design dynamic system models in Simulink which are ready for implementation on fixed point hardware The development cycle is illustrated below Model plant or signal source Simulink Model fixed point controller or filter Design requirements met Use the model as a specification for creating production code 1 11 1 Introduction 1 12 Using MATLAB Simulink and the Fixed Point Blockset the development cycle follows these steps 1 Model the system plant or signal source within Simulink using the built in blocks and double precision numbers Typically the model will contain nonlinear elements 2 Design and simulate a fixed point dynamic system for example a control system or digital filter with the Fixed Point Blockset that meets the design performance and other constraints 3 Analyzethe results and go back to 1 if needed When the design requirements have been met you can use the model as a specification for creating production code using the Real Time Workshop The above steps interact strongly In steps 1 and 2 there is a significant amount of freedom to select different solutions Generally the model is fine tuned based upon feedback from the r
34. and the simulation results are shown below Fixed Point Blockset Interface fxp_feedback el Es Log Min Max fuse block params Autoscale Safety Margin 0 0 Log Mode Overwitelog Datatype Override Use block params Block Name MIN MAX Data Scaling Type 375 Y 0 2 4 Up Cast SATURATION occurred 23 time s Numerator Terms 2 2 S16 V Q 2 14 Denominator Terns 2 85 2 85 S32 V 0 2 12 Combine Terms 3 079 4 859 S32 V 0 2 12 Down Cast 2 439 3 506 532 V Q 2 12 2 469 0 6563 S16 V Q 2 S Block path fxp_feedback Run Stop Autoscale Plot Help Close o Launch the Plot System 1 Run the simulation 2 interface The display shows that the Up Cast block saturated 23 times indicating a poor guess for the scaling Refer to Logging Simulation Results on page 10 9 to learn about logging overflow information to the workspace ThePlot System interface is shown below This interface displays all MATLAB variable names that contain Scope block data for the current model Y ou configure the variable name with the Scope block s Properties dialog box which you launch by choosing the Properties toolbar button Simulation Results To plot the simulation results select one or more variable names and then select the appropriate plot button This simulation plots thefixed point signals for the plant input and the plant output 1 Suie boti the plent input signal and the Plan
35. floating point data type The size of the output depends on the number of inputs their vector size and the selected operator e The NOT operator accepts only one input which can bea scalar or a vector If the input is a vector the output is a vector of the same size containing the logical complements of the input vector elements 10 139 Logical Operator Parameters and Dialog Box Characteristics 10 140 e For a single vector input the block applies the operation except the NOT operator to all elements of the vector The output is always a scalar e For two or more inputs the block performs the operation between all of the inputs Ifthe inputs are vectors the operation is performed between corresponding elements of the vectors to produce a vector output When configured as a multi input XOR gate this block performs an addition modulo two operation as mandated by the IEEE Standard for Logic Elements Block Parameters Logical Operator r Fixed Point Logical Operator mask link Perform the specified logical operation on the inputs The output data type should represent zero exactly Parameters Number of input ports A Logical output data type ex uint 8 sint 32 uint 8 Cancel Help Apply Operator Logical operator used to connec the inputs Number of input ports Number of inputs Logical output data type Output data type You should only use data types that represen
36. have many fixed point blocks whose scaling must be optimized you should use this tool Refer to Chapter 6 Tutorial Feedback Controller Simulation for more information Note As described in Compatibility with Simulink Blocks on page 1 13 you can eliminate the gateway blocks from your fixed point model if all signals use built in data types Simulation Results The results of two simulation trials are given below The first trial uses radix point only scaling while the second trial uses slope bias scaling Trial 1 Radix Point Only Scaling When using radix point only scaling your goal is to find the optimal power of two exponent E as defined in Selecting the Output Scaling on page 2 5 For this scaling mode the fractional slope F is set to 1 and no bias is required The Gateway In block is configured in this way e Output data type The output data type is given by sfix 5 This creates a MATLAB structure that is a 5 bit signed generalized fixed point number Output scaling The output scaling is given by 2 2 which puts the radix point two places to the left of the rightmost bit This gives a maximum value of 011 11 3 75 a minimum value of 100 00 4 00 and a precision of 1 2 0 25 2 11 2 G etting Started e Rounding The rounding mode is given by Nearest This rounds the fixed point result to thenearest representable number with the exact midpoint rounded towards positive infinity
37. the maximum absolute error occurs at 0625 The error at the breakpoints is 0 Creating Lookup Tables for a Sine Function Creating Lookup Tables for a Sine Function This section explains how to usethe function fixpt_look1_func_approx to create lookup tables It gives examples that show how to create lookup tables for the function sin 21x on the interval from 0 to 25 The section covers Parameters for fixpt_look1_func_approx on page 8 5 Setting Function Parameters for the Lookup Table on page 8 6 Example 1 Using errmax with Unrestricted Spacing on page 8 7 Example 2 Using nptsmax with Unrestricted Spacing on page 8 9 Restricting the Spacing on page 8 10 Example 3 Using errmax with Even Spacing on page 8 11 Example 4 Using nptsmax with Even Spacing on page 8 12 Example 5 Using errmax with Power of Two Spacing on page 8 13 Example 6 Using nptsmax with Power of Two Spacing on page 8 15 Specifying Both errmax and nptsmax on page 8 16 Comparing the Examples on page 8 17 Parameters for fixpt look1_func_approx To use the function fixpt_look1_func_approx you must first define its parameters The required parameters for the function are funcstr The ideal function xmin The minimum input of interest xmax The maximum input of interest xdt Thex data type xscale The x data scaling ydt The y data type yscale The y data scaling rndmeth The rounding
38. triggered subsystem Parameters Gain value mooo Initial condition for previous output 0 0 Output data type and scaling Inherit via intemalule y Round toward Floor e I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Gain value Specify the weight by which the sample time is multiplied 10 115 Integrator Backward Resetta ble Characteristics See Also 10 116 Initial condition for previous output Set the initial condition for the previous output Output data type and scaling The options are e Specify via dialog e Inherit via internal rule e Inherit via back propagation When Specify via dialog is selected you can specify the Output data type and Output scaling parameters Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Same as the input u Direct Feedthrough Yes of the input and reset source ports Scalar Expansion Of inputs and gain Integrator Backward and related blocks Integrator Backward Resetta ble Limi
39. where if all signals do not have the same data type the block returns an error message Y ou set the number of input ports with the Number of input ports parameter Block Parameters Data Type Duplicate Fixed Point Data Type Duplicate mask link Face all inputs to have the exact same data type Parameters Number of input ports hans Cancel Help Appl Number of input ports Number of input ports Input Port Any data type supported by the blockset Scalar Expansion Yes States 0 Vectorized Yes The Data Type Duplicate block is typically used such that one signal to the block controls the data type for all other blocks The other blocks are set to inherit their data types via back propagation The block is also used in a user created library These library blocks can be placed in any model and the data type for all library blocks are configured 10 47 Data Type Duplicate according tothe usage in the model To create a library block with more complex data type rules than duplication usethe Data Type Propagation block 10 48 Data Type Propagation Purpose Library Description Configure the data type and scaling of the propagated signal based on information from the reference signals Data Type The Data Type Propagation block allows you to control the data type and scaling of signals in your model You can use this block in conjunction with fixed point blocks that have their Specif
40. workspace The Sum block first converts the input data type s to the output data type using the specified rounding and overflow modes and then performs the specified operations Refer to Rules for Arithmetic Operations on page 4 30 for more information about the rules this block adheres to when performing operations Input Ports Any data type supported by the blockset Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Yes Switch Purpose Library Description Parameters and Dialog Box Switch output between the first input and the third input based on the value of the second input Select The Switch block is a masked S function that passes through the first top input or the third bottom input based on the value of the second middle input The second input is called the control input The first input is passed through when the second input is greater than or equal to the value of the Threshold parameter Otherwise it passes the third input through Thethreshold valueis converted to the second input s data type For a detailed description of all other block parameters refer to Block Parameters on page 10 4 Note The output data type is determined by the input with the largest positive range If the first input has a larger positive range than the third input then it specifies the output data type Otherwise the third input specifies the output data type
41. 1 0 feos 0 6 Initial condition for previous output a Initial condition for previous input fo D Round toward Floor X I Saturate to max or min when overflows occur TF Override data type s with doubles Y Log minimums and maximums Cancel Hep 4w Numerator coefficients Coefficients for the numerator of the filter Denominator coefficients excluding lead Coefficients for the denominator of the filter excluding the leading coefficient which must be 1 0 Initial condition for previous output Set the initial condition for the previous output 10 79 Filter Direct Form Characteristics See Also 10 80 Initial condition for previous input Set the initial condition for the previous input Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset it must be a scalar Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of initial conditions Vectorized No FIR and related blocks Filter Direct Form Time Varying Purpose Library Description Parameters and Dialo
42. 252 227 7013 and DFARS Part 252 227 7014 Theterms and conditions of The MathWorks Inc Software License Agreement shall pertain to the government s use and disclosure of the Program and Documentation and shall supersede any conflicting contractual terms or conditions If this license fails to meet the government s minimum needs or is inconsistent in any respect with federal procurement law the government agrees to return the Program and Documentation unused to MathWorks MATLAB Simulink Stateflow Handle Graphics and Real Time Workshop are registered trademarks and Target Language Compiler is a trademark of The MathWorks Inc Other product or brand names are trademarks or registered trademarks of their respective holders Printing History March 1995 First printing April 1997 Second printing Revised for MATLAB 5 January 1999 Third printing Revised for MATLAB 5 3 Release 11 September 2000 Fourth printing New for Version 3 Release 12 J une 2001 Online only Revised for Version 3 1 Release 12 1 1 Preface What Is the Fixed Point Blockset xiv Exploring the Blockset 000s eee eee eee xiv Related Products ococccocccoc eee xv System Requirements 0000 cece eee eee xv Associated Products s s s anaana xv Using This Guide ua xvii Expected Background ooococccccccc eee eee xvii Learning the Fixed Point Blockset oo oococoooo xvii How This Book Is
43. Description Parameters and Dialog Box Characteristics 10 202 Delay a signal one sample period Delays amp Holds The Unit Delay Enabled block is a masked block that delays a signal by one sample period when the external enable signal E is on While the enable is off the block is disabled It holds the current state at the same value and outputs that value The enable signal is on when E is not 0 and off when E is 0 Y ou specify the block output for the first sampling period with the value nitial condition parameter The output data type is the same as the input u data type The data type of the input u and the enable E can be any data type Y ou input the sample time with the Sample time parameter A setting of 1 means the Sample time is inherited Block Parameters Unit Delay Enabled gt Fixed Point Unit Delay Enabled mask link Normally the output is the signal u delayed by one sample period When the enable signal is false the block is disabled and the state and output values do not change except for resets The enable action is vectorized and supports scalar expansion Parameters Initial condition fa TTT Sample time E Cancel Help Apply Initial condition Initial condition Sample time Sample time Input Port u Any data type supported by the blockset Input Port E Any data type supported by the blockset Unit Delay Enabled Output Port Same as the input
44. Ey E should be used with even greater reluctance Division of signals with nonzero biases or mismatched slopes is not supported Example The Division Process Suppose you want to divide two numbers Each of these numbers is represented by an 8 bit word and each has a radix point only scaling of 2 Additionally the output is restricted to an 8 bit word with radix point only scaling of 24 The division of 9 1875 by 1 5000 is shown below FixPt Qa Constant ufix8 Ena rf ou so vV FixPt Display Gateway Out FixPt Product1 FixPt Constanti For this example 4 4 6529 QQ 204 00 Rules for Arithmetic O perations Assuming a large data type was available this could be implemented as _ 2 Qp a Qe where the numerator uses the larger date type If a larger data type was not available integer division combined with four repeated subtractions would be used Both approaches produce the same result with the former being more efficient Shifts Nearly all microprocessors and digital signal processors support well defined bit shift or simply shift operations for integers For example consider the 8 bit unsigned integer 00110101 The results of a 2 bit shift tothe left and a 2 bit shift to the right are shown below Shift Operation Binary Value Decimal Value No shift original number 00110101 53 Shift left by 2 bits 11010100 212 Shift right by 2 bits 00001101 13 Y ou can perf
45. Form TimeVarying 0 0005 10 81 Filter Direct Form Ul 2 2 0 eee 10 83 Filter Direct Formll Time Varying 05 10 85 Filter FIRstiOrden uti a See 10 87 Filter Lead or Lag cece eet ee 10 89 Filt Real Zer O ai eee ae ee eee 10 91 FIRS tach tee a dor bee Aho de Gant bode ak bee db Lees 10 93 Gal 2 eee Gain seine ees Gea Os Pea A 10 97 Gateway IN 2 0 0 eee 10 100 Gateway In Inherited 0 00 e eee eee 10 105 Gateway QU 2 dearer aros RA ad 10 107 Increment Real World ococcccccccoc 10 110 Increment Stored Integer 00 0 e eee eee ee 10 111 Integer Delay 0 0 0c cece tees 10 112 Integrator Backward oocococococcoccc 10 113 Integrator Backward Resettable ooo ooo oo o o 10 115 Integrator Backward Resettable Limited 10 117 Integrator Forward 0000 c cece eee eee 10 120 Integrator Forward Resettable 0 0005 10 122 Integrator Forward Resettable Limited 10 124 Integrator Trapezoidal 2 0 0 cece ee 10 127 Integrator Trapezoidal Resettable 10 130 Integrator Trapezoidal Resettable Limited 10 133 interval Test o a it SAA eee a ak 10 136 Interval Test Dynamic oooccoccccccc ee 10 138 Logical Operator piena te n anad aa aa 10 139 Look Up Table ocococcocococoo eee 10 141 Look Up Table Dynamic 000 0 cee eee eee 10 146
46. If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion Of inputs and gain Integrator Backward Resetta ble Purpose Library Description Y kTsz R z 1 Remarks Parameters and Dialog Box Perform discrete time integration of a signal using the backward method with external Boolean reset Calculus The Integrator Backward Resettable block performs a discrete time integration of a signal using the backward method The block can reset its state based on an external reset signal R When the reset signal R is false the block multiplies the input by the weighted sample time and adds the result to the cumulative sum since time zero When the reset signal R is true the block outputs the Initial condition for previous output parameter The output of the Integrator Backward Resettable block differs from the output of the Integrator F orward Resettable block only by the first and last terms in the cumulative sum Block Parameters Integrator Backward Resettable r Fixed Point Integrator Backward Resettable mask link Discrete time integration of the input u using backward method with external boolean reset This block only works with fixed sample rates so it will not work inside a
47. Organized 0 0c eee eee xviii Installation Information 00000005 xix Typographical Conventions 0000000 xx Introduction Physical Quantities and Measurement Scales 1 2 Selecting a Measurement Scale oooooocoooomoooo 1 2 Example Selecting a Measurement Scale 1 4 Why Use Fixed Point Hardware 1 9 Why Use the Fixed Point Blockset 1 10 The Development Cycle 1 11 Contents Compatibility with Simulink Blocks 1 13 Frame based Signals ocococcccococo 1 17 Matrix SignalS dra aa iai ea a a a a a A 1 17 How to Get Online Help 000 eee ee 1 18 Getting Started An Overview of Blockset Features 2 2 Configuring Fixed Point BlockS ooooooococcoooo 2 2 Additional Features and Capabilities 2 8 Example Converting from Doubles to Fixed Point 2 10 Block Descriptions 0 0 00 cece eee 2 10 Simulation Results 0 0 0 cece ee 2 11 DEMOS ooa ii PE eae Pe a ie POM ea a A 2 15 Basic DEMOS i oaran eA a da dd 2 15 Advanced Demos Filters and Systems 2 0 5 2 16 Data Types and Scaling 3 Overview och ie debe de bein She bed ene eee oS 3 2 Fixed Point Numbers 0 000 0 cee ee eee 3 3 Signed Fixed Point Numbers 0000c eee eens 3 3 Radix Point Interpret
48. Resettable Limited mask link Discrete time limited integration of the input u using trapezoidal method with external boolean reset This block only works with fixed sample rates so it will not work inside a triggered subsystem m Parameters Gain value CE Initial condition for previous output 0 Initial condition for previous weighted input K T s u 2 a o Upper limit jos Lower limit fas Output data type and scaling Inherit via internal rule Round toward Floor y I Saturate to max or min when overflows occur TF Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Gain value Specify the weight by which the sample time is multiplied Initial condition for previous output Set the initial condition for the previous output Initial condition for previous weighted input K Ts u 2 Set the initial condition for the previous weighted input Upper limit The upper limit for saturation of the cumulative sum Lower limit The lower limit for saturation of the cumulative sum 10 134 Integrator Trapezoidal Resettable Limited Characteristics See Also Output data type and scaling The options are e Specify via dialog e Inherit via internal rule e Inherit via back propagation When Specify via dialog is selected you can specify the Output data type and Output scaling parameters Round toward Rounding mode for the fixed point output
49. Scaling When scaling by slope and bias the slope S and bias B of the quantized real world number can take on any value Scaling by slope and bias is specified with the syntax slope bias which creates a MATLAB structure with the given slope and bias For example a slope bias scaling specified by 5 9 10 defines a slope of 5 9 and a bias of 10 The slope must be a positive number Quantization The quantization Q of a real world value V is represented by a weighted sum of bits Within the context of the general slope bias encoding scheme the value of an unsigned fixed point quantity is given by S ws 1 V S b 21 B i 0 while the value of a signed fixed point quantity is given by Fixed Point N umbers ws 2 Dye 1215 14 Y b 21 B i 0 lt r Il WN where e bj are binary digits with b 1 0 e The word size in bits is given by ws with ws 1 2 3 128 e S isgiven by F 2E wherethescalingis unrestricted since the radix point does not have to be contiguous with the word b are called bit multipliers and 2 are called the weights Example Fixed Point Format The formats for 8 bit signed and unsigned fixed point values are given below 0 0 1 1 0 1 0 1 Unsigned data type lol l lo 1 0 1 Signed datatype Note that you cannot discern whether these numbers are signed or unsigned data types merely by inspection since this information is not explicitly encoded wi
50. Up Table 2D 10 152 Row Input row vector It must be strictly monotonically increasing Col Input column vector It must be strictly monotonically increasing Table Output vector It must match the size defined by the Row and Col parameters Look up method Look up method Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling by back propagation Output data type Any data type supported by the Fixed Point Blockset Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generalized fixed point output Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Look Up Table 2D Conversions Example The Row parameter is converted from doubles to the first input s data type The Col parameter is converted from doubles to the second input s data type The Table parameter is converted from doubles to the output data type
51. Using nptsmax with Unrestricted apang Restricting the Spacing 5 s Example 3 Using errmax with Even Spaci ng Example 4 Using nptsmax with Even Spacing Example 5 Using errmax with Power of Two Spacing Example 6 Using nptsmax with Power of Two Spacing Specifying Both errmax and nptsmax Lite E Comparing the Examples Summary of the Lookup Table Functions Effect of Spacing on Speed Error and DEON T Data ROM Required Determining Out of Range nputs Determining the Location of the Input Performing Interpolation a Condusion 2 8 2 8 3 8 5 8 6 8 7 8 9 8 10 8 11 8 12 8 13 8 15 8 16 8 17 8 20 8 21 8 22 8 22 8 24 8 26 8 Producing Lookup Table Data 8 2 Overview A function lookup table is a method of approximating a function by a table with a finite number of points X Y Function lookup tables are essential to many fixed point applications The function you want to approximate is called the ideal function The X values of the lookup table are called the breakpoints Y ou approximate the value of the ideal function at a point by linearly interpolating between the two adjacent breakpoints closest to the point In creating the points for a function lookup table you generally want to achieve one or both of the following goals e Minimize the worst case error for a specified maximum number of breakpoints e Minimize the number of breakpoints for a specified ma
52. What Is the Fixed Point Blockset Exploring the Blockset Related Products System Requirements Associated Products Using This Guide Expected Background Learning the Fixed Point Blockset How This Book Is Organized Installation Information Typographical Conventions xii xii xiii xiii xiii XV XV XV xvi xvii Xviii Preface What Is the Fixed Point Blockset xii The Fixed Point Blockset includes a collection of blocks that extend the standard Simulink block library With these blocks you can create discrete time dynamic systems that use fixed point arithmetic As a result Simulink can simulate effects commonly encountered in fixed point systems for applications such as control systems and time domain filtering The Fixed Point Blockset includes these major features e Integer fractional and generalized fixed point data types Unsigned and two s complement formats Word size from 1 to 128 bits e Floating point data types EEE style singles and doubles A nonstandard IEEE style data type where the fraction mantissa can range from 1 to 52 bits and the exponent can range from 1 to 11 bits e Methods for overflow handling scaling and rounding of fixed point data types e Tools are provided to facilitate The collection of minimum and maximum simulation values The optimization of scaling parameters The display of input and output signals e With the Real Ti
53. an Embedded Processor Targeting an Embedded Processor This section describes issues that often arise when targeting a fixed point design for use on an embedded processor Rather than describe a specific microprocessor micro or digital signal processor DSP this section describes some general assumptions about integer sizes and operations available on embedded processors These assumptions lead to design issues and design rules that may be useful for your specific fixed point design Size Assumptions Embedded processors are typically characterized by a particular bit size For example the terms 8 bit micro 32 bit micro or 16 bit DSP are common It is generally safe to assume that the processor is predominantly geared to processing integers of the specified bit size Integers of the specified bit size are referred to as the base data type Additionally the processor typically provides some support for integers that are twice as wideas the base data type Integers consisting of double bits are referred to as the accumulator data type F or example a 16 bit micro has a 16 bit base data type and a 32 bit accumulator data type Although other data types may be supported by the embedded processor this section describes only the base and accumulator data types Operation Assumptions The embedded processor operations discussed in this section are limited to the needs of a basic simulation diagram Basic simulations use
54. and Dialog Box Implement a discrete time filter that has a real zero and no pole Filters TheFilter Real Zero block implements a discrete ti mefilter that has a real zero and effectively has no pole Block Parameters Filter Real Zero m Fixed Point Filter Real Zero mask link Discrete time filter that has a real zero and effectively has no pole m Parameters Zero of filter in Z plane 0 73 Initial condition for previous input PA Round toward Floor o I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Zero of filter in Z plane Set the zero of the filter Initial condition for previous input Set the initial condition for the previous input Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap 10 91 Filter Real Zero Characteristics See Also 10 92 Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged tothe workspace Input Ports Any data type supported by the blockset it must be a scalar Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of initial conditions Vectorized No FIR and related bloc
55. and provide support for arithmetic computations of varying precision TheALU performs a standard set of arithmetic and logic operations as well as division The MAC performs multiply multiply add and multiply subtract operations The shifter performs logical and arithmetic shifts normalization denormalization and other operations Addition and Subtraction Addition is the most common arithmetic operation a processor performs When two n bit numbers are added together it is always possible to produce a result with n 1 nonzero digits due to a carry from the leftmost digit For two s complement addition of two numbers there are three cases to consider e f both numbers are positive and the result of their addition has a sign bit of 1 then overflow has occurred otherwise the result is correct e If both numbers are negative and the sign of the result is 0 then overflow has occurred otherwise the result is correct e If the numbers are of unlike sign overflow cannot occur and the result is always correct Rules for Arithmetic O perations Fixed Point Blockset Summation Process Consider the summation of two numbers deally the real world values obey the equation Va IVE Ve where Vp and V arethe input values and V is the output value To see how the summation is actually implemented the three ideal values should be replaced by the general slope bias encoding scheme described in Scaling on page 3 5 Thesoluti
56. as the input Direct Feedthrough Yes Scalar Expansion N A Accumulator Purpose Library Description Parameters and Dialog Box Compute a cumulative sum Calculus At timestep n the Accumulator block computes a cumulative sum of all input values u up to time n and outputs the sum Running sum of all input values u Parameters Initial condition for previous output jod Output data type and scaling Inherit via internal rule y Round toward Floor l I Saturate to max or min when overflows occur I Override data type s with doubles V Log minimums and maximums Cancel Help Apply Initial condition for previous output Set the initial condition for the previous output Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling from the driving block or by back propagation Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles 10 23 Accumulator Characteristics 10 24 Log minimums and maximums If checked minimum and maximum simulation values are logged tothe workspace Input Port Any data type supported by the blockset Output Port Same data type as the input Direct Feedthrough Yes
57. below The Sign Bit While two s complement is the preferred representation for signed fixed point numbers IEEE floating point numbers use a sign magnitude representation where the sign bit is explicitly included in the word Using this representation a sign bit of O represents a positive number and a sign bit of 1 represents a negative number The Fraction Field In general floating point numbers can be represented in many different ways by shifting the number to the left or right of the radix point and decreasing or increasing the exponent of the radix by a corresponding amount To simplify operations on these numbers they are normalized in the IEEE format A normalized binary number has a fraction of the form 1 f where f has a fixed size for a given data type Since the leftmost fraction bit is always a 1 it is unnecessary to store this bit and is therefore implicit or hidden Thus an n bit fraction stores an n 1 bit number The IEEE format also supports denormalized numbers which have a fraction of the form 0 f Normalized and denormalized formats are discussed in more detail in next section The Exponent Field In the IEEE format exponent representations are biased This means a fixed value the bias is subtracted from the field to get the true exponent value F or example if the exponent field is 8 bits then the numbers O through 255 are represented and there is a bias of 127 Note that some values of the exponent are res
58. block input signals and output signals have the same slopes and biases but not mismatched slope bias scaling The Product block supports mismatched slope but not mismatched bias F or more information about matched and mismatched slope bias scaling refer to Signal Conversions on page 4 27 It is generally recommended that signals with slope bias scaling such as a sensor input areimmediatel y converted to radix point only scaling This will typically produce more efficient code Generating Pure Integer Code Generating Pure Integer Code All blocks generate pure integer code except for the Gateway In Gateway In Inherited and Gateway Out blocks These blocks must generate floating point code when handling floating point input or output However if the input or output is an integer and the block is configured to treat the input or output as a stored integer then these blocks will also generate pure integer code Example Generating Pure Integer Code This example outlines the steps you should take when generating pure integer code for your Fixed Point Blockset model The steps follow the description in the fxpdemo_code_only demo which includes the model shown below Controller Root level FixPt CES FixPt Gateway Root level n Out Inport Outport Digital controller software on fixed point processor Note This example generates code using the Embedded C Real Time Target ERT whch is available with the RTW Productio
59. blocks will generate pure integer code and will not use floating point operations This allows valid bit true testing even on a floating point processor Y ou can also generate code for non real time testing For example code can be generated to run in non real time on computers running any supported operating system Even though the processors have floating point hardware the code generated by fixed point blocks is pure integer code The Generic Real Time Target GRT and the Simulink Accelerator are examples of where non real time code is generated and run Code Generation Support Code Generation Support All fixed point blocks support code generation but not every simulation feature is supported The code generation support is described below Languages e C support only e No Ada support Storage Class of Variables e Fixed Point Blockset code generation handles variables that do not match the target compiler s sizes for char short int or long Code generation supports any variable having a width less than or equal to a long either signed or unsigned For example the C40 compiler defines a long to be 32 bits Therefore the allowable sizes for variables range between 1 and 32 bits This capability is particularly useful if you want to Prototype on onetarget chip but use a different target chip for production Provide bit true simulation in a rapid prototyping environment for odd data type sizes used by FPGA s ASIC
60. by y k 13 u k 11 u k 1 7 u k 2 and the second output is given by y gt k 6 u k 5 u k 1 Additionally the initial values of u k 1 and u k 2 are given by 0 8 and 1 1 respectively and all inputs parameters and outputs have radix poi nt onl y scaling Example Conversions and Arithmetic O perations To configure the FIR block for this situation you must specify the FIR coefficient parameter as 13 11 7 6 5 0 and the Initial condition parameter as 0 8 1 1 as shown below in the dialog box below Block Parameters FIR m Fixed Point FIR mask link Implement a finite impulse response FIR filter m Parameters FIR coefficients 0 1 1 0 9 0 1 0 1 Initial condition PI Sample time j Gain data type and scaling Specity via dialog y Parameter data type ex sfix 16 uint 8 float single sti 16 Parameter scaling Slope ex 29 p 14 Parameter scaling Best Precision Matrix wise y Dutput data type and scaling Specity via dialog y Output data type ex sfix 16 uint 8 float single sf 6 Dutput scaling Slope or Slope Bias ex 2 9 21 D I Lock output scaling so autoscaling tool can t change it Round toward Floor v I Saturate to max or min when overflows occur I Override data typefs with doubles V Log minimums and maximums Cancel Help Apply Parameter conversions and block operations are given below in the order in which t
61. by sinh 5 5 Using the model shown below 7 U Display Constant Gateway In Look Up Gateway Out Double Table Double the following results were generated Look Up Method Input Output Comment Interpolation 1 4 2 153 N A Extrapolation 5 2 83 59 N A Interpolation 1 4 2 153 N A Use End Values 5 2 74 2 The value for sinh 5 0 was used Use Input 1 4 1 175 The value for sinh 1 0 was used Nearest Use Input 1 4 1 175 The value for sinh 1 0 was used Below 5 2 74 2 The value for sinh 5 0 was used Use Input 1 4 3 627 The value for sinh 2 0 was used Above 5 2 74 2 The value for sinh 5 0 was used Input Port s Any data type supported by the blockset Output Port Any data type supported by the blockset Look Up Table Direct Feedthrough Yes Scalar Expansion No 10 145 Look Up Table Dynamic Purpose Library Description x xdat ydat 10 146 yP Approximate a one dimensional function using a selected look up method and a dynamically specified table LookU p The Look Up Table Dynamic block is a masked S function that computes an approximation to some function y f x given x y data vectors The look up method can useinterpolation extrapolation or the original values of the input The x data vector must be strictly monotonically increasing after conversion to the input s fixed point data type Note that due to quantization the x data vector may be strictly monotonic in doubles for
62. conventions xviii typographical conventions table xviii U ufix 9 35 ufrac 9 36 uint 9 37 unary minus 10 199 underflow 3 21 unit delay 10 200 updating old models 9 26 WwW wrapping 4 13 Z zero order hold 10 227
63. data type The Down Cast block represents taking the number from the CPU and storing it in RAM The word size and precision are reduced to half that of the accumulator when converted back to the base data type e FIR These blocks represent a weighted sum carried out in the CPU target The word size and precision used in the calculations reflect those of the accumulator The Numerator Terms block multiplies and accumulates the 6 7 6 Tutorial Feedback Controller Simulation 6 8 most recent inputs with the FIR numerator coefficients The Denominator Terms block multiples and accumulates the most recent delayed inputs with the FIR denominator coefficients The coefficients are stored in ROM using the base data type The most recent inputs are stored in global RAM using the base data type e Sum The Combine Terms block represents the accumulator in the CPU Its word size and precision are twice that of the RAM double bits e Unit Delay The Prev Out block delays the feedback signal in memory by one sample period The signals are stored in global RAM using the base data type Direct Form Realization The controller directly implements this equation N N y k y b u k 1 y a y k 1 i 0 1 where e u k 1 represents the input from the previous ti me step e y k represents the current output and y k 1 represents the output from the previous time step e bj represents the FIR numerator coefficients e a repr
64. data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Port u Any data type supported by the blockset it must be a scalar Input Port Num Any data type supported by the blockset it must be a scalar Input Port Den No Any data type supported by the blockset it must be Lead a scalar Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of initial conditions Vectorized No FIR and related blocks Filter First Order Purpose Library Description Parameters and Dialog Box Implement a discrete time first order filter Filters TheFilter First Order block implements a discrete time first order filter of the input The filter has a unity DC gain Block Parameters Filter First Order r Fixed Point Filter First Order mask link Discrete time first order filter of the input The filter has a unity DC gain m Parameters Pole of filter in Z plane 0 99 Initial condition for previous output PA Round toward Floor o I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Pole of filter in Z plane Set the pole of the filter Initial condition for previous output Set the initial condition for the previous out
65. data type s stored integer value Qa F B B aby E Es b aE F 2 Qp F 2 a a Qa E E F2 Qb Bnet where F is the adjusted fractional slope and Bhe is the net bias The offline conversions and online conversions and operations are discussed below Offline Conversions Both F and Bng are computed offline using round to nearest and saturation Bhe is then stored using the output data type and F is stored using an automatically selected data type Online Conversions and Operations The remaining conversions and operations are performed online by the fixed point processor and depend on the slopes and biases for the input and output data types The conversions and operations are given by these steps 1 Theinitial value for Q is given by the net bias Bre Qa Bret 2 Theinput integer value Qp is multiplied by the adjusted slope F OrawProduct FsQp 3 Theresult of step 2 is converted to the modified output data type where the slope is one and bias is zero Parameter and Signal C onversions Qtemp convert Qp awProduct This conversion includes any necessary bit shifting rounding or overflow handling 4 Thesummation operation is performed Q Qtemp Qa This summation includes any necessary overflow handling Streamlining Simulations and Generated Code Note that the maximum number of conversions and operations is performed when the slopes and biases of the input signal and output signal differ ar
66. follows xNum uAngle xuneven iLeft xDen xuneven iRght xuneven iLeft yDiff yuneven iRght yuneven iLeft Effect of Spacing on Speed Error and Memory Usage MUL_S32 516 U16 bigProd yDiff xNum DIV_NZP_S16_S32 U16_FLOOR yDiff bigProd xDen yUneven yuneven iLeft yDiff The multiplication and division routines are not shown here These can be somewhat involved and depend on the target processor For example these routines look quite different for a 16 bit processor than for a 32 bit processor Even Case Evenly spaced breakpoints implement interpolation using just slightly different calculations than the uneven case The key difference is that the calculations do not directly use the breakpoints This means the breakpoints are not required in ROM which can bea very significant savings xNum uAngle iLeft 455U yDiff yeven iLeft 1 yeven iLeft MUL_S32_S16_U16 bigProd yDiff xNum DIV_NZP_S16_S32 U16_FLOOR yDiff bigProd 455U yEven yeven iLeft yDiff Power of Two Case Power of two spaced breakpoints implement interpolation using very different calculations than the other two cases Like the uneven case breakpoints are not used in the generated code and therefore not required in ROM lambda uAngle amp OxOOFFU yPow2 ypow2 iLeft 1 ypow2 iLeft MUL_S16_U16_S16_SR8 yPow2 lambda yPow2 yPow2 ypow2 iLeft 8 25 8 Producing Lookup Table Data
67. fractional number via the block dialog box you specify the Output data type parameter to be ufrac 16 Toconfigurea 16 bit signed fractional number you specify Output data type to be sfrac 16 Fractional numbers are distinguished from integers by their default scaling Whereas signed and unsigned integer data types have a default radix point to the right of all bits unsigned fractional data types have a default radix point to the left of all bits while signed fractional data types have a default radix point to the right of the sign bit Both unsigned and signed fractional data types support guard bits which act to guard against overflow For example sfrac 16 4 Specifies a 16 bit signed fractional number with 4 guard bits The guard bits lieto the left of the default radix point Generalized Fixed Point Numbers You specify unsigned and signed generalized fixed point numbers with the ufix and sfix functions respectively For example to configure the output as a 16 bit unsigned generalized fixed point number via the block dialog box you specify the Output data type parameter to be ufix 16 Toconfigurea 16 bit signed generalized fixed point number you specify Output data type to be sfix 16 Generalized fixed point numbers are distinguished from integers and fractionals by the absence of a default scaling For these data types you must explicitly specify the scaling with the Output scaling dialog box parameter or inherit th
68. input exceeds the value of the Switch on point parameter The block accepts one input and generates one output The Switch on point value must be greater than or equal to the Switch off point Specifying a Switch on point value greater than the Switch off point value models hysteresis whereas specifying equal values models a switch with a threshold at that value Y ou specify the output scaling with the Output scaling parameter Note that there are two dialog box parameters that control the output scaling one associated with an edit field and one associated with a parameter list If Output data type is a generalized fixed point number such as sfix 16 the Output scaling parameter list provides you with these scaling modes e Use Specified Scaling This mode uses the slope bias or radix point only scaling specified for the editable Output scaling parameter for example 2 10 e Best Precision Vector wise This mode produces the best precision based on the Output when on and Output when off parameters For a detailed description of all other block parameters refer to Block Parameters on page 10 4 10 173 Relay Pa ra meters Block Parameters Relay and Dialog Box __ FikedPoint Relay mask ink Output the specified on or off value by comparing the input to the specified thresholds The on off state of the relay is not affected by the input between the upper and lower limits Parameters
69. integer values are scaled 1 9 1 Introduction 1 10 Why Use the Fixed Point Blockset The Fixed Point Blockset bridges the gap between designing a dynamic system and implementing it on fixed point digital hardware To do this the blockset provides basic fixed point Simulink building blocks that are used to design and simulate dynamic systems using fixed point arithmetic With the Fixed Point Blockset you can Use fixed point arithmetic to develop and simulate fixed point Simulink models Change the fixed point data type scaling rounding mode or overflow handling mode while the model is simulating This allows you to explore issues related tonumerical overflow quantization errors and computational noise Generate fixed point model code ready for execution on a floating point processor This allows you to emulate the effects of fixed point arithmetic in a floating point rapid prototyping system Generate fixed point model code ready for execution on a fixed point processor Modify or add new fixed point blocks Source code is provided for all fixed point blocks you will need one of the C compilers supported by the mex utility The Fixed Point Blockset addresses the issues related to using fixed point single instruction single data stream processors Extensions to multiple instruction multiple data stream processing units can be made However hardware consisting of multipleinstruction or multiple data streams generally
70. is O the default you will not be prompted If blkprompt is 1 you will have these three options e y default replaces the block e n does not replace the block e a replaces all blocks without further prompting fpupdate model blkprompt varprompt gives you the option of updating variables which appear in each block s dialog box with their actual numerical values Note that such an update is possible only if the variables can be evaluated in the MATLAB workspace If varprompt is 1 the default you are prompted for each variable found in the block diagram If varprompt is 0 all variables are automatically updated without prompting fpupdate model blkprompt varprompt muxprompt allows you to update the input size parameters of the Mux and Demux blocks found in model The input sizes of these blocks may need to be updated to account for the mismatch between the old and new fixed point data representations In the old representation each number had a width of 2 In the new representation each number has a width of 1 To update Mux and Demux blocks that have only fixed point inputs the vector that specifies the input size should be divided by 2 If muxprompt is 1 the default each Mux and Demux block found in model is updated If muxprompt is 0 the Mux and Demux blocks are automatically updated without prompting fpupdate fpupdate model blkprompt varprompt muxprompt message allows you to show or suppress any warning or u
71. is treated The possible values are Real World Value and Stored Integer In terms of the general encoding scheme described in Scaling on page 3 5 Real World Value treats the mask as V SQ B whereS is the slope and B is the bias Stored Integer treats the mask as a stored integer Q For more information about this parameter list refer to the Gateway In block You can use the bit mask to perform a bit set or a bit clear on the input To perform a bit set you configure the Operator parameter list to OR and create a bit mask with a 1 for each corresponding input bit that you want to set to1 To perform a bit clear you configure the Operator parameter list to AND and create a bit mask with a 0 for each corresponding input bit that you want to set to 0 For example suppose you want to perform a bit set on the fourth bit of an 8 bit input vector The bit mask would be 00010000 which you can specify as 2 4 in Bitwise Operator Parameters and Dialog Box Conversions the Bit mask parameter To perform a bit clear the bit mask would be 11101111 which you can specify as 277 2 6 2 5 2 3 2 2 2 1 2 0 in the Bit mask parameter Block Parameters Bitwise Operator r Fixed Point Bitwise Operator mask link Perform the specified bitwise operation on the inputs The output data type should represent zero exactly Parameters Operator M Use bit mask Number oF Input ps fe Bit Mask bin2dec 11011001
72. method In addition there are three optional parameters errmax The maximum allowed error of the lookup table nptsmax The maximum number of points of the lookup table 8 5 8 Producing Lookup Table Data 8 6 e spacing The allowed spacing between breakpoints You must use at least one of the parameters errmax and nptsmax Typical settings for these parameters are given in the next section Setting Function Parameters for the Lookup Table on page 8 6 Using Only errmax If you use only the errmax parameter without nptsmax the function creates a lookup table with the fewest points for which the worst case error is at most errmax See Example 1 Using errmax with Unrestricted Spacing on page 8 7 Using Only nptsmax If you use only the nptsmax parameter without errmax the function creates a lookup table with at most nptsmax points which has the smallest worse case error See Example 2 Using nptsmax with Unrestricted Spacing on page 8 9 Thesection Specifying Both errmax and nptsmax on page 8 16 describes how the function behaves when you specify both errmax and nptsmax Spacing You can use the optional spacing parameter to restrict the spacing between breakpoints of the lookup table The options are e unrestricted The default e even The distance between any two adjacent breakpoints is the same e pow2 Thedistance between any two adjacent breakpoints is the sameand the distance
73. mode supported by the blockset Toward Zero Nearest Floor default value Ceiling e xmin and xmax specify the range over which the breakpoints are approximated e xdt xscale ydt yscale and rndmeth follow conventions used by the Fixed Point Blockset e rndmeth has a default value listed in the input table In addition to the required parameters there are three optional inputs as follows Input Value errmax Maximum acceptable error nptsmax Maximum number of points spacing Spacing even pow2 even power of 2 unrestricted default value Of these you must use at least one of the parameters errmax and nptsmax If you omit one of these use brackets in place of the omitted parameter The function will then ignore that requirement for the lookup table 9 15 fixpt_look1_func_approx 9 16 The outputs of the function are as follows Output Value xdata The breakpoints for the lookup table ydata The ideal function applied to the breakpoints errworst The worst case error which is the maximum absolute error between the ideal function and the approximation given by the lookup table Criteria For Optimizing the Breakpoints errmax nptsmax and spacing The approximation produced from the lookup table must satisfy the requirements for the maximum acceptable error errmax the maximum number of points notsmax and the spacing spacing The requirements are e The maxim
74. multiplication addition subtraction and delays Fixed point models also need shifts to do scaling conversions For all these operations the embedded processor should have native instructions that allow the base data type as inputs F or accumulator type inputs the processor typically supports addition subtraction and delay storage retrieval from memory but not multiplication Multiplication is typically not supported for accumulator type inputs due to complexity and size issues A difficulty with multiplication is that the output needs to be twice as big as the inputs for full precision For example multiplying two 16 bit numbers requires a 32 bit output for full precision The need to handle the outputs from a multiply operation is one of the reasons embedded processors include accumulator type support However if multiplication of accumulator type inputs is also supported then thereis a 7 3 7 Building Systems and Filters need to support a data type that is twice as big as the accumulator type To restrict this additional complexity multiplication is typically not supported for inputs of the accumulator type Design Rules The important design rules that you should be aware of when modeling dynamic systems with fixed point math are given below Design Rule 1 Only Multiply Base Data Types It is best to multiply only inputs of the base data type Embedded processors typically provide an instruction for the multiplication
75. of base type inputs but not for the multiplication of accumulator type inputs If necessary a multiplication of accumulator type inputs could be handled by combining several instructions However this can lead to large slow embedded code Blocks to convert inputs from the accumul ator type to the base type can be inserted prior to multiply or gain blocks if needed Design Rule 2 Delays Should Use the Base Data Type There are two general reasons why a unit delay should use only base type numbers First the unit delay essentially stores a variable s valuetoRAM and one time step later retrieves that value from RAM Because the value must be in memory from one time step to the next the RAM must be exclusively dedicated to the variable and can t be shared or used for another purpose Using accumulator type numbers instead of the base data type doubles the RAM requirements which can significantly increase the cost of the embedded system The second reason is that the unit delay typically feeds into a gain block The multiplication design rule requires that the input the unit delay signal use the base data type Design Rule 3 Temporary Variables Can Use the Accumulator Data Type Except for unit delay signals most signals are not needed from one time step to the next This means that the signal values can be temporarily stored in memory that is shared and reused This shared and reused memory can be RAM or it can simply be registers in t
76. of these as they apply to the block Input Port s the data type s accepted by the block and whether the inputs can bea scalar or vector Output Port the data type s produced by the block and whether the outputs can be a scalar or vector Direct Feedthrough whether the block or any of its ports has direct feedthrough Sample Time how the block s sample time is determined whether by the block itself or inherited from the block that drives it or is driven by it Scalar Expansion whether or not scalars are expanded to vectors States the number of discrete states Vectorized whether or not the block accepts and or generates vector signals The Block Dialog Box The Block Dialog Box Y ou configure Fixed Point Blockset blocks with a parameter dialog box The parameter dialog box provides you with e The name and block type at the top of the dialog box e A brief description of the block s behavior below the title e Zeroor moreeditable parameter fields check boxes or parameter lists below the description You specify the parameter values using valid MATLAB expressions A row of four buttons labeled OK Cancel Help and Apply at the bottom of the dialog box The OK button sets the current parameter values and closes the dialog box The Cancel button reverts all the parameter values back to their values at the time the dialog box was opened losing any changes you made The Help button displays the HTML based refere
77. only scaling and resulted in a precision of 0 25 To find the fractional slope you dividethe maximum value of the sine wave by the maximum value of the scaled 5 bit number The result is 5 00 3 75 1 3333 The slope and precision is 1 3333 0 25 0 3333 You specify this value as 0 3333 for the Output scaling parameter Of course you could have specified a fixed power of two exponent of 1 and a corresponding fractional slope of 0 6667 Naturally the resulting slope is the same since E was reduced by one bit but F was increased by one bit In this case the blockset would automatically store F as 1 3332 and E as 2 due tothe normalization condition of 1 lt F lt 2 2 13 2 G etting Started The resulting real world and fixed point simulation results are shown below This somewhat cumbersome process used to find the slope is not really necessary All that is required is the range of the data you are simulating and the size of the fixed point word used in the simulation In general you can achieve reasonable simulation results by selecting your scaling based on the formula max min 2 5_1 where e maxis the maximum value to be simulated e min is the minimum value to be simulated e ws is the word size in bits e 2S _ 1 is the largest value of a word with whose size is given by ws For this example the formula produces a slope of 0 32258 Demos Demos To help you learn the Fixed Point Blockset
78. or example if you are multiplying two signed 16 bit signals the Product block produces the natural output of a signed 32 bit data type An unnatural output is produced if the inputs have different signs and different sizes In this case some trial and error may be required to achieve satisfactory results If you are adding signals two natural choices for the output data type and scaling are possible to preserve the precision or to prevent overflow However blocks only support one rule For example the Sum block preserves precision If your goal is to prevent overflow then you should manually configure the data type and scaling If you select Inherit via back propagation the output data type is inherited by back propagation In many cases you will find that the Data Type Propagation block provides you with the most flexibility when back propagating the data type The supported data types and default scaling are shown below Table 10 1 Output Data Types and Default Scaling Data Type Description Default Scaling float Floating point number None uf ix Unsigned generalized fixed point None number 10 5 10 Block Reference Table 10 1 Output Data Types and Default Scaling Continued Data Type Description Default Scaling sfix Signed generalized fixed point number None uint Unsigned integer Right of the least significant bit sint Signed integer Right of the least significant bit ufrac Unsigned fractiona
79. or zero Block Parameters Detect Fall Negative Fixed Point Detect Fall Negative mask link If the input is strictly negative and its previous value was nonnegative then output TRUE otherwise output false Cancel Help Bool Input Port Any data type supported by the blockset Output Port An 8 bit unsigned integer Direct Feedthrough Yes Scalar Expansion Yes Vectorized Yes Detect Change and related blocks 10 69 Detect Fall Nonpositive Purpose Library Description Parameters and Dialog Box Characteristics See Also 10 70 Detect a falling edge when the signal s value decreases to a nonpositive value and its previous value was strictly positive Edge Detect The Detect Fall Nonpositive block is a masked block that determines if the input is less than or equal to zero and its previous value was positive where e The output is true not 0 when the input signal is less than or equal to zero and its previous value was greater than zero e The output is false equal to 0 when the input signal is greater than zero or if it is nonpositive its previous value was nonpositive Block Parameters Detect Fall Nonpositive Fixed Point Detect Fall Nonpositive mask link If the input is nonpositive and its previous value was strictly positive then output TRUE otherwise output false Y Cancel Help Ep Input Port Any data type supported by the blockset Output Port An 8 bit
80. processing a digital filter is a computational algorithm that converts a sequence of input numbers to a sequence of output numbers The algorithm is designed such that the output signal meets frequency domain or time domain constraints desirable frequency components are passed undesirable components are rejected In general terms a discrete transfer function controller is a form of a digital filter However a digital controller may contain nonlinear functions such as look up tables in addition toa discretetransfer function In this guide theterm digital filter is used when referring to discrete transfer functions The Fixed Point Blockset does not attempt to standardize on one particular fixed point digital filter design method For example a design can be done in continuous time and an equivalent discrete time digital filter can be obtained using one of many transformation methods Alternatively digital filters can be directly designed in discrete time After the digital filter is obtained it can be realized for fixed point hardware using any number of canonical forms Typical canonical forms arethe direct form series form and parallel form all of which are outlined in this chapter For a given digital filter the canonical forms describe a set of fundamental operations for the processor Since there are an infinite number of ways to realize a given digital filter the best realization must be made on a per system basis The
81. radix 3 13 3 Data Types and Scaling point is located seven places to the left of the rightmost bit With this data format M becomes 0 0 0 0 0 0 0 0 0 0 0 0 3 1250e 002 0 0 0 3 3594e 001 3 1250e 002 0 0 Notethat many of the matrix elements are zero and for the nonzero entries the scaled values differ from the original values This is because a double is converted to a binary word of fixed size and limited precision for each element The larger and more precise the conversion data type the more closely the scaled values match the original values Best Precision Element wise If M is scaled such that the precision is maximized for each matrix element 3 14 you obtain 3 3379e 005 3 3379e 004 3 3340e 003 3 3325e 002 3 3301e 001 3 3304e 006 3 3379e 005 3 3379e 004 3 3340e 003 3 3325e 002 Best Precision Row wise If M is scaled based on the largest value for each row you obtain 3 3379e 005 3 3379e 004 3 3340e 003 3 3325 002 3 3301e 001 3 3379e 006 3 3379e 005 3 3569e 004 3 2959e 003 3 3203e 002 Best Precision Column wise If M is scaled based on the largest value for each column you obtain 0 0 2 9297e 003 3 3203e 002 3 3301e 001 0 0 3 6621e 004 3 2959e 003 3 3325e 002 3 3341e 007 3 3304e 006 3 3379e 005 3 3379e 004 3 3340e 003 3 5763e 007 2 8610e 006 3 0518e 005 3 6621e 004 2 9297e 003 0 0 3 0518e 005 3 3569e 004 3 3340e 003 0 0
82. resulting formula is By 5 So he E E Be _ Qa gt Qt A 2 Q c Recommendations for Arithmetic and Scaling Inherited Scaling for Maximum Precision The maximum precision scaling can be determined if the range of the variable is known As shown in Example Maximizing Precision on page 4 11 the range of a fixed point operation can be determined from max V and min V For multiplication the range can be determined from where Vit min V min V Vin min V max V VaL max V min V Vin max V max V Radix Point O nly Scaling For radix point only scaling finding Q results in this simple expression E E E Q 2 QUO Gain Consider the multiplication of a constant and a variable V K V where K is a constant called the gain Since Va results from the multiplication of a constant and a variable finding Qa is a simplified version of the general fixed point multiply formula 4 21 4 Arithmetic O perations 4 22 E KF 2 KB B Qa E op Ee F 42 2 a Note that the terms in the parentheses can be calculated offline Therefore there is only one multiplication of a constant and a variable and one addition To implement the above equation without changing it to a more complicated form the constants need to be encoded using a radix point only format For each of these constants the range is the trivial case of only one value Despite the trivial range the radix p
83. round 4 6 rounding modes 4 3 10 8 and code generation A 3 toward ceiling 4 6 toward floor 4 7 toward nearest 4 5 toward zero 4 4 rsim A 12 RTW Production Coder A 5 S saturation 4 13 10 184 and feedback controller demo 6 10 scaling 2 5 10 6 and accumulation 4 19 and addition 4 16 and code generation A 4 and division 4 23 and gain 4 21 and multiplication 4 20 constant scaling for best precision 3 12 inherited 10 7 locking 10 8 radix point only 2 6 3 6 slope bias 2 6 3 6 scientific notation 3 16 series cascade form realization 5 7 setting bits 10 32 sfix 9 31 sfrac 9 32 shifts 4 41 using the FixPt Conversion block 4 42 using the FixPt Gain block 4 43 showfixptsimranges 9 33 10 9 sign extension 4 15 of input signal 10 187 sign bit for IEEE numbers 3 18 signal conversions 4 27 Simulink built in data types 1 13 converting built in data types to fixed point 10 100 converting built in models to fixed point 9 8 converting fixed point data types to built in 10 107 Simulink Accelerator A 11 single precision format 3 19 sint 9 34 slope bias scaling 3 6 stored integer 2 3 as block input 10 100 as block output 10 107 subtraction 10 192 See also addition switch 10 195 multiport 10 163 T tapped delay 10 197 Target Language Compiler A 13 targeting an embedded processor 7 3 design rules 7 4 operation assumptions 7 3 size assumptions 7 3 Index TLC file A 13 truncation 4 9 two s complement 3 3 typographical
84. s 24 bit DSP s and so on e Nofloating point support except for the fixed point gateway blocks Storage Class of Parameters e The Real Time Workshop external mode support requires that parameters be 1 to 32 bits either signed or unsigned The parameter size must also be compatible with the target C compiler e Nofloating point support Rounding Modes e All four rounding modes are supported e Rounding to floor generates the most efficient code for most cases A 3 A Code Generation A 4 Overflow Handling e Saturation mode is supported e Wrapping mode is supported and generates the most efficient code e Automatic exclusion of saturation code when hardware saturation is available is currently not supported Wrapping must be selected for the Real Time Workshop to exclude saturation code Blocks All blocks generate code for all operations with a few exceptions e TheLook Up Table Look Up Table 2D and Dynamic Look U p Table blocks generate code for all look up methods except extrapolation e A few combinations of scaling and operations lead to highly inefficient code These few cases are described in the next section Scaling e Radix point only scaling is supported e Slope bias scaling is supported for all blocks except when it leads to highly inefficient code All blocks except four support all cases of slope bias scaling The Gain Matrix Gain and FIR blocks support matched slope bias scaling where the
85. slope bias scaling is performed To find out a data type s class refer to its reference page in this chapter fxptdlg showfixptsimranges 9 5 fix ptbestex p Purpose Syntax Description Example See Also 9 6 Determine the exponent that gives the best precision fixed point representation of a value out fixptbestexp RealWorldValue TotalBits IsSigned out fixptbestexp RealWorldValue FixPtDataType out fixptbestexp RealWorldValue TotalBits IsSigned determinesthe exponent that gives the best precision for the fixed point representation of the real world value specified by RealWorldvValue You specify the number of bits for the fixed point number with TotalBits and you specify whether the fixed point number is signed with IsSigned If IsSigned is 1 the number is signed If IsSigned is 0 the number is not signed The exponent is returned to out out fixptbestexp RealWorldValue FixPtDataType determines the exponent that gives the best precision based on the data type specified by FixPtDataType The following command returns the exponent that gives the best precision for the real world value 4 3 using a signed 16 bit number out fixptbestexp 4 3 16 1 out 14 Alternatively you can specify the fixed point data type out fixptbestexp 4 3 sfix 16 out 14 This value means that the maximum precision representation of 4 3 is obtained by placing 14 bits to the right of the binary point 0
86. supported by the blockset Input Port RV Same as the input u Output Ports Same as the input u 10 220 Unit Delay With Preview Enabled Resettable External RV Direct Feedthrough Yes to upper output port No to lower output port Scalar Expansion Yes See Also Unit Delay and related blocks 10 221 Unit Delay With Preview Resettable Purpose Library Description 10 222 Support calculations that have feedback and depend on the current input Delays Holds The Unit Delay With Preview Resettable block supports calculations that have feedback and depend on the current input The block can reset its state based on an external reset signal R The block has two output ports When the reset R is false the upper port outputs the signal and the lower port outputs the signal delayed by one sample period When the reset R is true the block resets the current state to the initial condition given by the Initial condition parameter The block outputs that state delayed by one sample time through the lower output port and outputs the state without a delay through the upper output port Theinput u and initial condition IC must be the same data type but can be any data type The output is the same data type as the inputs u and IC The reset R can be any data type Y ou specify the time between samples with the Sample time parameter A setting of 1 means the Sample time is inherited Unit Delay With Preview Resetta ble
87. supported by the blockset except a true floating point data type Output Port Same as the input Direct Feedthrough Yes Scalar Expansion Yes 10 29 Bit Set Purpose Library Description Set bitO Parameters and Dialog Box Example Characteristics See Also 10 30 Set the specified bit of the stored integer to one Bits The Bit Set block is a masked block that sets the specified bit of the stored integer to one Scaling is ignored Y ou can specify the bit to be set to one with the Index of bit parameter where bit zero is the least significant bit True floating point data types are not supported Block Parameters Bit Set Fixed Point Bit Set mask link se ith bit of the stored integer to 1 Scaling is ignored Index of bit 0 is least significant ooo Cancel Help Apply Parameters Index of bit Index of bit where bit 0 is the least significant bit If the Bit Set is turned on for bit 2 bit 2 is set to 1 A vector of constants 2 0 1 2 3 4 s represented in binary as 00001 00010 00100 01000 10000 With bit 2 set to 1 the result is 00101 00110 00100 01100 10100 which is represented in decimal as 5 6 4 12 20 Input Port Any data type supported by the blockset except a true floating point data type Output Port Same as the input Direct Feedthrough Yes Scalar Expansion Yes Bit Clear Bitwise Operator Purpose Library Description Bitwise A
88. the radix point Radix point only scaling does not require the radix point to be contiguous with the data word The advantage of this scaling mode is the number of processor arithmetic operations is minimized You specify radix point only scaling with the syntax 2 E where E is unrestricted This creates a MATLAB structure with a bias B O anda fractional slope F 1 0 For example if you specify the value 2 10 for the Output scaling parameter then the generalized fixed point number has a power of two exponent E 10 This value defines the radix point location to be 10 places to the left of the least significant bit Slope Bias Scaling With this scaling mode you can provide a slope and a bias The advantage of slope bias scaling is that it typically provides more efficient use of a finite number of bits You specify slope bias scaling with the syntax slope bias which creates a MATLAB structure with the given slope and bias For example if you specify the value 5 9 10 for the Output scaling parameter then the generalized fixed point number has a slope of 5 9 and a bias of 10 The blockset would automatically store F as 1 1111 and E as 1 due to the normalization condition 1 lt F lt 2 An O verview of Blockset Features Rounding Y ou specify how fixed point numbers are rounded with the Round toward parameter list These rounding modes are supported e Zero This mode rounds toward zero and is equivalent to MATLAB s
89. the right Qg 100 11011 QTemp onvert Qg Qtemp 00100 110 Note that a loss in precision of two bit occurs with the resulting value of QT emp determined by the rounding mode For this example round to floor is used Overflow cannot occur in this case since the bits and radix point are both shifted tothe right 7 Thesummation operation is performed Rules for Arithmetic O perations O o l Q Qtemp 11001 010 _ 00100 110 11110 000 30 000 Note that overflow did not occur but it is possible for this operation As shown below the result of step 7 differs from the ideal sum 10011 111 0101 0111 100 11011 11110 001 30 125 Blocks that perform addition and subtraction include the Sum Matrix Gain and FIR blocks Multiplication The multiplication of an n bit binary number with an m bit binary number results in a product that is up tom n bits in length for both signed and unsigned words Most processors perform n bit by n bit multiplication and produce a 2n bit result double bits assuming there is no overflow condition For example the Texas Instruments TM S320C2x family of processors performs two s complement 16 bit by 16 bit multiplication and produces a 32 bit double bit result Fixed Point Blockset Multiplication Process Consider the multiplication of two numbers Ideally the real world values obey the equation Va Vox Ve where Vp and V are the input values and V is the output valu
90. to use this script read the comments included in the M file The data types for fixed point outputs taking Boolean values are specified by the variable LogicType The data types of all other fixed point outputs and parameters are specified by the variable BaseType You can change these variables to any data type For example in the MATLAB workspace you can type BaseType sfix 16 LogicType uint 8 The converted model will not work if these variables are not defined Best precision mode is used when available Otherwise the precision is set to 2 which means that the binary point istotheright of all bits To automatically 9 9 fixpt_convert Example 9 10 set the scaling run a simulation with doubles override on and then invoke the automatic scaling script autofixexp You can run autofixexp directly or in conjunction with the Fixed Point Blockset Interface fxptdlg This example uses fixpoint_convert to convert a Simulink model of a direct form I realization to its fixed point equivalent This realization is discussed in Direct Form I1 on page 5 4 The simulink model shown below fxpdemo_preconvet is included as a demo with the blockset bo 2 2 Gain 1 85 b1 Gain1 b2 p pooo gt gt l p gt 1 1 1 i Outpu Input Zero Order gt gt gt 0
91. true the block outputs the Initial condition for previous output parameter The output of the ntegrator Forward Resettable block differs from the output of the Integrator Backward Resettable block only by the first and last terms in the cumulative sum Block Parameters Integrator Forward Resettable m Fixed Point Integrator Forward Resettable mask link Discrete time integration of the input u using forward method with external boolean reset This block only works with fixed sample rates so it will not work inside a triggered subsystem m Parameters Gain value ic Initial condition for previous output bo Output data type and scaling Inherit viaintemalule Round toward Floor z I Saturate to max or min when overflows occur TF Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Gain value Specify the weight by which the sample time is multiplied Integrator Forward Resettable Characteristics See Also Initial condition for previous output Set the initial condition for the previous output Output data type and scaling The options are e Specify via dialog e Inherit via internal rule e Inherit via back propagation When Specify via dialog is selected you can specify the Output data type and Output scaling parameters Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked f
92. type and scaling from the driving block or by back propagation Round toward Rounding mode for the fixed point output This parameter does not apply toan integer control input Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap This parameter does not apply to an integer control input Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Any data type supported by the blockset MultiPort Switch Direct Feedthrough Yes Scalar Expansion Yes 10 165 Product Purpose Library Description x A gt x 10 166 Multiply or divide inputs Math The Product block is a masked S function that performs multiplication or division of its inputs You specify the operations with the Enter characters or the number of inputs parameter Multiply divide characters indicate which operations areto be performed e f there are two or more inputs then the number of multiply divide characters must equal the number of inputs For example requires three inputs and configures the block to divide the first top input by the second middle input and then and multiply the third bottom input If the first character is then thefirst input is inverted e f only multiplication of inputs is required then a numeric parameter value equal tothe numb
93. zero The block outputs the sum up tothe nth time step at time n The output of the Integrator Backward block differs from the output of the Integrator Forward block only by the first and last terms in the cumulative sum Block Parameters Integrator Backward r Fixed Point Integrator Backward mask link Discrete time integration of the input using backward method This block only works with fixed sample rates so it will not work inside a triggered subsystem Parameters Gain value fi 0 Initial condition for previous output joo Dutput data type and scaling Inherit via internal rule y Round toward Floor X PF Saturate to max or min when overflows occur TF Override data type s with doubles V Log minimums and maximums Cancel Help Apply Gain value Specify the weight by which the sample time is multiplied Initial condition for previous output Set the initial condition for the previous output 10 113 Integrator Backward Characteristics 10 114 Output data type and scaling The options are e Specify via dialog e Inherit via internal rule e Inherit via back propagation When Specify via dialog is selected you can specify the Output data type and Output scaling parameters Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles
94. 0 0 0 3 3295e 008 3 3341e 007 3 3304e 006 3 3379e 005 3 3379e 004 0 0 2 8610e 006 3 3379e 005 3 3379e 004 Fixed Point N umbers e Best Precision Matrix wise If M is scaled based on its largest matrix value you obtain 0 0 0 0 0 0 0 0 2 9297e 003 0 0 0 3 3203e 002 2 9297e 003 0 0 3 3301e 001 3 3203e 002 2 9297e 003 0 The disadvantage of scaling the matrix column wise row wise or matrix wise is reduced precision resulting from the use of a common radix point The advantage of using a common radix point is reduced code size and possibly increased processor speed 3 15 3 Data Types and Scaling Floating Point Numbers 3 16 Fixed point numbers are limited in that they cannot simultaneously represent very large or very small numbers using a reasonable word size This limitation is overcome by using scientific notation With scientific notation you can dynamically place the radix point at a convenient location and use powers of the radix to keep track of that location Thus a range of very large and very small numbers can be represented with only a few digits Any binary floating point number can be represented in scientific notation formas fx 2 wheref is the fraction or mantissa 2 is the radix or base binary in this case and eis the exponent of the radix The radix is always a positive number while f and ecan be positive or negative When performing arithmetic operations floating point hardwa
95. 0 0 0c eee eee 7 2 Targeting an Embedded Processor 7 3 Size Assumptions oooococccc eee 7 3 Operation Assumptions ooooccococooco eee 7 3 Design RU 8S s iira issa soie aia tee 7 4 8 OVErvieW os it la la td Baty 8 2 Worst Case Error for a Lookup Table 8 3 Example Square Root FUNCION o ooocooccooocooo o 8 3 Creating Lookup Tables for a Sine Function 8 5 Parameters for fixpt_look1_func_approx o ooooomooo 8 5 Setting Function Parameters for the Lookup Table 8 6 Example 1 Using errmax with Unrestricted Spacing 8 7 Example 2 Using nptsmax with Unrestricted Spacing 8 9 Restricting the Spacing cocccocccccococ 8 10 Example 3 Using errmax with Even Spacing 8 11 Example 4 Using nptsmax with Even Spacing 8 12 Example 5 Using errmax with Power of Two Spacing 8 13 Example 6 Using nptsmax with Power of Two Spacing 8 15 Specifying Both errmax and nptsmax 0e eee eee 8 16 Comparing the Examples 6 0 cece eee 8 17 Summary of the Lookup Table Functions 8 19 Effect of Spacing on Speed Error and Memory Usage 8 20 Data ROM Required oocococccccoccoco 8 21 Determining Out of Rangelnputs o oooocococcccoo 8 22 Determining the Location of the Input 8 22 Performing Interpolation 0 0 00 cece eee 8 24 CONGCIUSIO
96. 1 01010101010101 You would specify the precision of this representation in fixed point blocks by setting the scaling to 2 14 or 2 fixptbestexp 4 3 16 1 fixptbestprec sfix ufix fixptbestprec Purpose Syntax Description Example See Also Determine the maximum precision available for the fixed point representation of a value out fixptbestprec RealWorldValue TotalBits IsSigned out fixptbestprec RealWorldValue FixPtDataType out fixptbestprec RealWorldValue TotalBits IsSigned determines the maximum precision for the fixed point representation of the real world value specified by RealWor1dValue Y ou specify the number of bits for the fixed point number with TotalBits and you specify whether the fixed point number is signed with IsSigned If IsSigned is 1 the number is signed If IsSigned is o the number is not signed The maximum precision is returned to out out fixptbestprec RealWorldValue FixPtDataType determines the maximum precision based on the data type specified by FixPtDataType The following command returns the maximum precision available for the real world value 4 3 using a signed 8 bit number out fixptbestprec 4 3 8 1 out 0 015625 Alternatively you can specify the fixed point data type out fixptbestprec 4 3 sfix 8 out 0 015625 This value means that the maximum precision available for 4 3 is obtained by placing six bits to the right of the binary point since 2 equa
97. 10 places the radix point at a location 10 places tothe left of the least significant bit Slope bias Specify slope bias scaling For example a scaling of 5 9 10 specifies a slope of 5 9 and a bias of 10 When using this mode you must specify a positive slope Note that some blocks provide a form of radix point only scaling for constant vectors and constant matrices Refer to Example Constant Scaling for Best Precision on page 3 12 for more information Locking the O utput Scaling If the Lock output scaling so autoscaling tool can t change it check box is checked then the automatic scaling tool autofixexp will not changethe Output scaling parameter value Otherwise the automatic scaling tool is free to adjust the scaling You can run autofixexp directly from the command line or through the Fixed Point Blockset Interface tool fxptdlg Rounding You can choose the rounding mode for the block operation with the Round toward parameter list The available rounding modes are shown below Table 10 3 Rounding Modes Rounding Mode Description Zero Round the output towards zero Nearest Round the output towards the nearest representable number with the exact midpoint rounded towards positive infinity 10 8 Common Block Features Table 10 3 Rounding Modes Continued Rounding Mode Description Ceiling Round the output towards positive infinity Floor Round the output towards negative infinity Ha
98. 3 Unit Delay With Preview Enabled 10 215 Unit Delay With Preview Enabled Resettable 10 217 Unit Delay With Preview Enabled Resettable External RV 10 219 Unit Delay With Preview Resettable 10 222 Unit Delay With Preview Resettable External RV 10 224 Wrap TOZO cuicos Geis a A we bla a 10 226 Zero Order HO shai Sede Cena e Pewee eau 10 227 A OVERVIEW iis foie eh ake Bh eee eA Se Oh eal ae oe A 2 Code Generation Support 00 0 eee aee A 3 LANQUAGES ita aR dora Pe ee eared A 3 Storage Class of Variables 0 cece eee eee A 3 Storage Class of Parameters 0 cece eee e eee A 3 Rounding Modes 00 0 cece tte eee A 3 x Contents Overflow Handling 20 00 cee eee eee A 4 BIOCKS testes cta lo o ky Bee Sma A 4 SCAN ta da Rowand Sahat tt dat es dela My dah A A 4 Generating Pure Integer Code 4 A 5 Example Generating Pure Integer Code A 5 Using the Simulink Accelerator A 11 Using External Mode or rsim Target A 12 External MOd 3 26 5 wee aa Shee E eee nda ae ee A 12 Rapid Simulation Target 0 0 0 cece eee ee A 12 Customizing Generated Code o o A 13 Macros Versus FunctionS 0 cece eee eee A 13 Bit Sizes for Target C Compiler 000 eee eee A 13 Selected Bibliography B Preface
99. 5 gt Comparison Hold gt z Z z m Unit Delay Unit Delay1 Unit Delay2 Gain2 b3 0 5 Gain5 1 2 70 84 Gain4 a2 0 09 Gain3 a3 The following command converts this model to its fixed point equivalent suppresses the display of detailed block information and does not save the model after conversion res fixpt_convert fxpdemo_preconvert off off The built in blocks that are replaced by fixed point equivalent blocks are given by the replaced field res replaced ans UnitDelay 3x1 cell ZeroOrderHold 1x40 char Gain 6x1 cell fixpt_ convert Sum 2x1 cell The built in blocks that are skipped since they are compatible with the Fixed Point Blockset are given by the skipped field res skipped ans Mux fxpdemo_preconvert_fixpt Mux The built in blocks that are encapsulated by fixed point gateway blocks so that they are made compatible with the Fixed Point Blockset are given by the encapsulated field res encapsulated ans Scope 1x42 char SignalGenerator fxpdemo_preconvert_fixpt Input Note that the initial class of the base data type is double BaseType Class DOUBLE You can now run the simulation for the converted model sim fxpdemo_preconvert_fixpt 9 11 fixpt_convert See Also 9 12 The output from the simulation is shown below Y ou should compare this output to the output produced by the fixed point direct from model fxpdemo_d
100. 5 8 The first order diagram for H z is given below x Z Ape Jo CD Ya x Z gt 1l a z The second order diagram for H z is given below x Z les E 7 Es y 2 y Z _ 1 8z1 fz2 X Z 1 0z1 d z The series cascade form example transfer function is given by 14 0 5z 1 14 1 721 z 2 H Z A 3 A ex 2 1 0 1z 1 1 0 6z 1 0 9z 2 Series Cascade Form nooo 00 The realization of H z using the Fixed Point Blockset is shown below Y ou can display this model by typing fxpdemo_series cascade_form at the MATLAB command line nput it e gt gt gt it gt out Output 4 FixPtGain4 From FixPt Mux3 Comparison In gt 1 f To FixPi que gt dl 1 1 o FixPt p ze F A i gt der FixPtUnit FixPtGaint Pt Z F Z F F ixPtSum Delay b pli FixPtUnit FixPtUnit FixPtGain5 El F Delay1 Delay2 FixPtSum2 FixPtSum1 FixPtGain FixPtGain2 a Cc lt a FixPtGain3 d 5 9 5 Realization Structures Parallel Form In the canonical parallel form the transfer function H z is expanded into partial fractions H z is then realized as a sum of a constant first order and second order transfer functions as shown below _ U Z _ H Z a
101. 656 log2 MAE 10 MAE yBit 16 The least sianificant 4 bits of the output can be inaccurate The upper plot shows the ideal function sin 27x and the fixed point lookup approximation between the breakpoints In this example the ideal function 8 8 Creating Lookup Tables for a Sine Function and the approximation are so close together that the two graphs appear to coincide The lower plot displays the errors In this example the Y data points returned by the function fixpt_look1_func_approx as ydata are equal tothe ideal function applied to the points in xdata However you can define a different set of values for ydata after running fixpt_look1_func_plot This can sometimes reduce the maximum error Y ou can also changethe values of xmin and xmax in order to evaluate the lookup table on a subset of the original interval Tofind the new maximum error after changing ydata xmin or xmax type errworst fixpt_look1_func_plot xdata ydata funcstr xmin xmax xdt xscale ydt yscale rndmeth Example 2 Using nptsmax with Unrestricted Spacing The next example shows how to create a lookup table that minimizes the worst case error for a specified maximum number of data points with unrestricted spacing Before starting the example enter the same parameter values given in thesection Setting Function Parameters for the Lookup Table on page 8 6 if you have not already done soin this MATLAB session Setting the Number of Breakpoi
102. 8 26 This implementation has very significant advantages over the uneven and even implementations The key difference is that a subtraction and a division are replaced by a bitwise AND combined with a shift right at the end of the multiply Another advantage is that the term u xData iLeft xData iRght xData iLeft is computed with no loss of precision because the spacing is a power of two In contrast the uneven and even cases usually introduce rounding error in this calculation Conclusion The number of Y data points follows the expected pattern For the same worst case error unrestricted spacing uneven requires the fewest data points and power of two spaced breakpoints requires the most However the implementation for the evenly spaced and the power of two cases does not need the breakpoints in the generated code This reduces their data ROM requirements by a half As a result the evenly spaced case actually uses less data ROM than the unevenly spaced case Also the power of two case requires only slightly more ROM than the uneven case Changing the worst case error can change these rankings Nonetheless when you compare data ROM usage you should always take into account the fact that the evenly spaced and power of two spaced cases do not require their breakpoints in ROM Theeffort of determining where the current input is relativetothe breakpoints strongly favors the evenly spaced and power of two spaced cases With unev
103. All conversion are performed offline using round to nearest and saturation Refer to Parameter Conversions on page 4 27 for more information about parameter conversions Suppose the Look Up Table 2D block is configured to use input row and column vectors given by 1 3 and a look up table given by 4 5 6 16 19 20 10 18 23 Using the model shown below Gonstant Gateway In Double Gateway Out Display Constant2 Gateway Int ub the following results were generated Look Up Method Input x y Output Comment Interpolation 1 6 2 5 13 9 N A Extrapolation 1 6 4 0 15 4 N A Interpolation 1 6 2 5 13 9 N A Use End Values 1 6 4 0 14 4 The value for 1 6 3 was used Use Input 1 6 2 3 19 The value for 2 2 was used Nearest 10 153 Look Up Table 2D Characteristics See Also 10 154 Look Up Method Input x y Output Comment Use Input 1 6 2 3 5 The value for 1 2 was used Below 1 6 0 5 4 Thevaluefor 1 1 was used Use Input 1 6 2 3 20 The value for 2 3 was used Above 1 6 3 5 20 The value for 2 3 was used Input Ports Any data type supported by the blockset Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of one input if the other is a vector Look Up Table and related blocks Matrix Gain Purpose Multiply the input by a constant matrix Library Math Description The Matrix Gain block is a masked S function that multi
104. B structurethat describes the data type of an unsigned integer with a word size given by TotalBits uint is automatically called when an unsigned integer is specified in a block dialog box The default radix point for this data type is assumed to lie to the right of all bits Define a 16 bit unsigned integer a uint 16 a Class INT IsSigned 0 MantBits 16 float sfix sfrac sint ufix ufrac 9 37 uint 9 38 Block Reference The Block Reference Pages The Block Dialog Box Common Block Features Block Parameters Block con Labels Port Data Type Display The Fixed Point Blockset Libraries 10 2 10 3 10 4 10 4 10 10 10 10 10 12 10 Block Reference 10 2 The Block Reference Pages Fixed Point Blockset block reference pages appear in alphabetical order and contain some or all of this information e The block name and icon e The purpose of the block e A description of the block e Additional remarks about block usage e The block parameters and dialog box including a brief description of each parameter e The rules for some or all of these topics as they apply to the block Converting block parameters from double precision numbers to Fixed Point Blockset data types Converting the input data type s to the output data type Performing block operations between inputs and parameters e An example using the block e The block characteristics including some or all
105. Box alse BEE riar Direct tom 11 Tire i ying r Fixed Point Filter Direct Form Il Time Varying mask link A Direct Form II realization of the specified filter is used Only single input single output filters are supported The data types and scalings of the output the coefficients and any temporary variables are automatically selected The automatic choices will be acceptable in many situations In situations where the automatic choices give unacceptable results manual layout of the filter is necessary For manual layout it is suggest that the blocks under this mask be used as a starting point Note 1 The full denominator should have a leading coefficient of 1 0 but this leading coefficient should be excluded when entering the parameter For example if the denominator is den 1 17 0 72 just enter den 2 end 1 7 0 72 Note 2 The numerator does NOT need to be the same size as the full denominator Parameters Initial condition pa Round toward Floor be TF Saturate to max or min when overflows occur T Override data type s with doubles V Log minimums and maximums Cancel Help Initial condition Set the initial condition 10 85 Filter Direct Form Il Time Varying Characteristics See Also 10 86 Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override
106. C operation is twice as wideastheinput signal Todothis you configurethis parameter tothe value2 The Number of bits Additive adjustment parameter allows you to adjust the number of bits used by Prop by including an additive adjustment For example if you are performing multiple additions during a MAC operation the result may overflow To prevent overflow you can associate guard bits with the propagated data type To associate four guard bits you specify the value 4 The Number of bits Allowable final values parameter allows you toforcethe computed number of bits used by Prop to a useful value For example if you are targeting a processor that supports only 8 16 and 32 bits then you configure this parameter to 8 16 32 The block always propagates the small est specified value that fits If you want to allow all fixed point data types you would specify the value 1 128 Inheriting Scaling Information Ifthe Propagated scaling parameter is Inherit via propagation rule then these dialog box parameters are available to you 2 1 1 Slope Base min Slopel Slope2 2 1 2 Slope Multiplicative adjustment e 2 1 3 Slope Additive adjustment 0 2 2 1 Bias Base Bias1 y 2 2 2 Bias Multiplicative adjustment 1 2 2 3 Bias Additive adjustment pe The Slope Base parameter list specifies the slope used by Prop for the base data type The parameter values are described below Parameter Value Description
107. D K H 2 H Z H 2 This expansion where K is a constant and the H z are thefirst and second order transfer functions is shown below 5 H z gt gt H 2 gt Asin theseries canonical form there is no unique description for the first order and second order transfer function Due to the nature of the Sum block the ordering of the individual filters doesn t matter However because of the constant K the first order and second order transfer functions can be chosen such that their forms are simpler than those for the series cascade form described in the preceding section This is done by expanding H z as 5 10 Parallel Form j p H z K Y H 2 y H 2 i 1 i j 1 i i j e fizt AA A A L l ajz 1 L 1 z1 d z i 1 i j 1 The first order diagram for H z is shown below b D y 2 Ls 7 eq yiz _ Bi x Z l azl x z The second order diagram for H z is shown below gt Lf x z Joa de y z G I lt d lt y Z k amp fi zi X Z 1 cz d z7 5 11 5 Realization Structures The parallel form example transfer function is given by 3 4639 1 0916 3 0086z 1 H z 5 5556 3 4639_ ext2 1 0 121 1 06z1 0 972 The realization of He z using the Fixed Point Blockset is shown below Y ou can display this model by typi
108. EZ Direct Form ll az h z The block diagrams for h z e z is shown below az h z h2 1 a 1 2 n e z l az aZ a nZ Combining these two block diagrams yields the direct form II diagram shown below Notice that the feedforward part top of block diagram contains the numerator coefficients and the feedback part bottom of block diagram contains the denominator coefficients b m m N u z u z e z N H N H NA N pun N H a lt 5 5 5 Realization Structures The direct form II example transfer function is given by H ex 2 1 2 271 1 8572 0 573 1 0 571 0 8422 0 09z 3 The realization of He z using the Fixed Point Blockset is shown below Y ou can display this model by typing fxpdemo_direct_form2 at the MATLAB command line 0000 00 In Input To FixPt 5 6 FixPtGain4 b1 gt 18 F FixPtGain5 A Pt a E Out gt Output i gt 1 gt 1 gt 1 ata From FixPt Mux3 Comparison m ZF ZF z Fl F LE gt FixPtUnit FixPtUnit FixPtUnit FixPtGain FixPtSum1 FixPtSum Delay Delay1 Delay2 b3 lt i FixPtGain3 al Kea FixPtGain2 a2 G
109. Enabled Resettable External IC Characteristics See Also Sample time Sample time Input Port u Any data type supported by the blockset Input Port E Any data type supported by the blockset Input Port R Any data type supported by the blockset Input Port IC Same as the input u Output Port Same as the input u Direct Feedthrough No of the input port No of the enable port Yes of the enable port Yes of the external IC port Scalar Expansion Yes Unit Delay and related blocks 10 209 Unit Delay External IC Purpose Delay a signal one sample period Library Delays amp Holds Description The Unit Delay block is a masked block that delays its input by one sample period This block is equivalent to the z discrete time operator The block accepts one input and generates one output both of which can be scalar or vector If the input is a vector all elements of the vector are delayed by the same sample period The block s output for the first sample period is equal to the signal IC Theinput u and initial condition Ic data types must be the same and are any data type Y ou specify the time between samples with the Sample time parameter A setting of 1 means the Sample time is inherited Parameters and Dialog Box Block Parameters Unit Delay External IC Fixed Point Unit Delay External Initial Condition mask link E initial condition is given by the signal IC Normally the output is the signa
110. Fixed Point Blockset For Use with SIMULINK Modeling Simulation Implementation WORKS User s Guide o Version 3 X OD How to Contact The MathWorks www mathworks com Web comp soft sys matlab Newsgroup support mathworks com Technical support suggest mathworks com Product enhancement suggestions bugs mathworks com Bug reports doc mathworks com Documentation error reports service mathworks com Order status license renewals passcodes info mathworks com Sales pricing and general information 508 647 7000 Phone 508 647 7001 Fax The MathWorks Inc Mail 3 Apple Hill Drive Natick MA 01760 2098 For contact information about worldwide offices see the MathWorks Web site Fixed Point Blockset User s Guide COPYRIGHT 1995 2001 by The MathWorks Inc The software described in this document is furnished under a license agreement The software may be used or copied only under the terms of the license agreement No part of this manual may be photocopied or repro duced in any form without prior written consent from The MathWorks Inc FEDERAL ACQUISITION This provision applies to all acquisitions of the Program and Documentation by or for the federal government of the United States By accepting delivery of the Program the government hereby agrees that this software qualifies as commercial computer software within the meaning of FAR Part 12 212 DFARS Part 227 7202 1 DFARS Part 227 7202 3 DFARS Part
111. Fixed Point Detect Rise Positive mask link If the input is strictly positive and its previous value was nonpositive then output TRUE otherwise output false Cancel Help Ep j Input Port Any data type supported by the blockset Output Port An 8 bit unsigned integer Direct Feedthrough Yes Scalar Expansion Yes Vectori zed Yes Detect Change and related blocks 10 73 Difference Purpose Library Description 1 1 I Parameters and Dialog Box 10 74 Calculate the change in a signal over one time step Calculus The Difference block outputs the current input value minus the previous input value Block Parameters Difference r Fixed Point Difference mask link Output the current input value minus the previous input value m Parameters Initial condition for previous input 0 0 Output data type and scaling Inherit via internal rule y Round toward Floor 7 I Saturate to max or min when overflows occur IF Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Initial condition for previous output Set the initial condition for the previous output Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling from the driving block or by back propagation Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur
112. Function sin 2 pi x Ideal red Fixed Point Lookup Approximation blue 1 N Table uses 33 power of 2 spaced data pointd Put The input is Unsigned 16 Bit with 16 bits right of binary point The output is Signed 16 Bit with 14 bits right of binary point Maximum Absolute Error 0 00037209 log2 MAE 11 3921 MAE yBit 6 0964 The least significant 3 bits of the output can be inacourate The most significant nonsign bit of the output is used The remaining 12 nonsign bits of the output are used and always acourate The sign bit of the output is not used The rounding mode is to Floor Example 6 Using nptsmax with Power of Two Spacing The next example shows how to create a lookup table that has power of two spacing and minimizes the worst case error for a specified maximum number of points To try the example you must first enter the enter the parameter values given in the section Setting Function Parameters for the Lookup Table on page 8 6 if you have not already done soin this MATLAB session Spacing pow2 xdata errworst fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth nptsmax spacing The result requires 17 points to achieve a maximum absolute error of 2 9 6267 To plot the lookup table along with the errors type 8 15 8 Producing Lookup Table Data 8 16 fixpt_look1_func_plot funcstr xdata xdt xscale ydt yscale rndmet h This produces the plo
113. Gain matrix value feve 3 3 Gain data type and scaling Specity via dialog Parameter data type ex sfix 16 uint 8 float single sti 16 Parameter scana Slope ey 29 2 14 Parameter scaling Best Precision Matrix wise y Use Specified Scaling Output data type a Best Precision Element wise Best Precision Row wise Output data type Best Precision Column wise Best Precision Matrix wise Output scaling Slope or Slope Bias ex 2 9 P00 T Lock output scaling so autoscaling tool can t change it Round toward Fo I Saturate to max or min when overflows occur I Override data typefs with doubles V Log minimums and maximums Multiplication Matris K u u vector ha a Tounderstand how you might usethese scaling modes consider a 5 by 4 matrix of doubles M defined as 3 3333e 005 3 3333e 004 3 3333e 003 3 3333 e 002 3 3333e 001 3 3333e 006 3 3333e 005 3 3333e 004 3 3333e 003 3 3333e 002 3 3333e 007 3 3333e 006 3 3333e 005 3 3333e 004 3 3333e 003 3 3333e 008 3 3333e 007 3 3333e 006 3 3333e 005 3 3333e 004 Now suppose M is input into the Matrix Gain block and you want to scale it using one of the constant matrix scaling modes The results of using these modes are described below e Use Specified Scaling Suppose the matrix elements are converted to a signed 10 bit generalized fixed point data type with radix point only scaling of 27 that is the
114. Help Apply Initial condition Initial condition Sample time Sample time Input Port u Any data type supported by the blockset Input Port R Any data type supported by the blockset Input Port RV Same as the input u Output Ports Same as the input u Direct Feedthrough Yes to upper output port No to lower output port Scalar Expansion Yes Unit Delay and related blocks 10 225 Wrap To Zero Purpose Library Description Parameters and Dialog Box Characteristics 10 226 Set output to zero if input is above threshold Nonlinear The Wrap To Zero block sets the output to zero if the input is above the value set by the Threshold parameter and outputs the input if theinput is less than or equal to the Threshold Block Parameters Wrap To Zero If the input is above the threshold the output is zero otherwise the output Fixed Point Wrap To Zero mask link E the input Threshold s Cancel Help Apply Parameters Threshold When the input exceeds the threshold the output is set to zero Input Port Any data type supported by the blockset Output Ports Same as the input Direct Feedthrough Yes Scalar Expansion Yes Zero Order Hold Purpose Library Description Tel Remarks Parameters and Dialog Box Characteristics Implement a zero order hold of one sample period Delays amp Holds The Zero Order Hold block is a masked
115. If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace 10 95 FIR Conversions and Operations Example Characteristics 10 96 TheFIR coefficients parameter is converted from doubles tothe specified data type offline using round to nearest and saturation The Initial condition parameter is converted from doubles to the input data type offline using round to nearest and saturation Refer to Parameter Conversions on page 4 27 for more information about parameter conversions The FIR block first multiplies its inputs by the FIR coefficients parameter converts those results to the output data type using the specified rounding and overflow modes and then carries out the summation Refer to Rules for Arithmetic Operations on page 4 30 for more information about the rules this block adheres to when performing operations Suppose you want to configure this block for two outputs SIMO mode where the first output is given by y k a u k by U k 1 Cc U k 2 the second output is given by and the initial values of u k 1 and u k 2 are given by ic1 and ic2 respectively To configure the FIR block for this situation you must specify the FIR coefficient parameter as a1 b1 c1 a2 b2 c2 wher
116. Input Ports Any data type supported by the blockset Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of inputs and gain 10 99 Gateway In Purpose Library Description Led 10 100 Convert a Simulink data type to a Fixed Point Blockset data type Data Type The Gateway In block is a masked S function that converts a built in Simulink data type to a Fixed Point Blockset data type The Input and Output to have equal parameter list controls how the input is processed The possible values are Real World Value and Stored Integer n terms of the general encoding scheme described in Scaling on page 3 5 Real World Value treats the input as V SQ B whereS is the slope and B is the bias V is used to produce Q V B S which is stored in the output Stored Integer treats the input as a stored integer Q The value of Q is directly used to produce the output In this mode the input and output are identical except that the input is a raw integer lacking proper scaling information In both modes the output data type includes the scaling information needed to correctly interpret the signal as a real world value For a detailed description of all other block parameters refer to Block Parameters on page 10 4 Gateway In Parameters and Dialog Box Block Parameters Gal r Fixed Point Gateway In mask link Convert the input to the data type and scaling of the ou
117. IsSigned2 data types TRUE Refl and Ref2 are ignored and Prop is always a signed data type FALSE Refl and Ref2 are ignored and Prop is always an unsigned data type For example if the Ref1 signal is ufix 16 the Ref2 signal is sfix 16 and the Is Signed parameter is sSigned1 or IsSigned2 then Prop is forced to be a signed data type The Number of bits base parameter list specifies the number of bits used by Prop for the base data type The parameter values are described below Parameter Value Description NumBits1 NumBits2 max NumBits1 NumBits2 min NumBits1 NumBits2 NumBits1 NumBits2 The number of bits for Prop is given by the number of bits for Refl The number of bits for Prop is given by the number of bits for Ref2 The number of bits for Prop is given by the reference signal with largest number of bits The number of bits for Prop is given by the reference signal with smallest number of bits The number of bits for Prop is given by the sum of the reference signal bits Refer to Targeting an Embedded Processor in Chapter 7 for more information about the base data type The Number of bits Multiplicative adjustment parameter allows you to adjust the number of bits used by Prop by including a multiplicative 10 53 Data Type Propagation 10 54 adjustment For example suppose you want to guarantee that the number of bits associated with a multiply and accumulate MA
118. Log minimums and maximums Cancel Help Apply 10 83 Filter Direct Form Il Characteristics See Also 10 84 Numerator coefficients Coefficients for the numerator of the filter Denominator coefficients excluding lead Coefficients for the denominator of the filter excluding the leading coefficient which must be 1 0 Initial condition Set the initial condition Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset it must be a scalar Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of initial conditions Vectorized No FIR and related blocks Filter Direct Form Il Time Varying Purpose Implement a time varying Direct Form II realization of a filter Library Filters Description The Filter Direct Form II Time Varying block implements a Direct Form realization of the specified filter The block only supports single input single output filters The block automatically selects the data types and scalings of the output the coefficients and any temporary variables Parameters a nd Dia log
119. Look Up Table 2D 0 0 ccc cee eee 10 150 Matrix Gain sia Peat pens ete 10 155 MIA MAC a wees aha ee es 10 159 MinMax Running Resettable 00 00 00 ee 10 162 MultiPort Switch 0 000 naa ae LEE 10 163 POGUGE yo ca Bal Oe a no Midd tl edad ye get 10 166 Rate Limiter sce i eu foes oia eee a 10 169 Rate Limiter Dynamic 0 000 e eee eee 10 170 Relational Operator 000 cece ee 10 171 Relay ocio a a eres ea eck hide ca de 10 173 Repeating Sequence Interpolated 10 176 Repeating Sequence Stair 00 00 cece ee 10 178 Sample Time Multiply o ooocccccccccrcco o 10 181 Saturation sea i asion ea aaa a at lela 10 184 Saturation Dynamic 0 000 10 185 Scaling Strip rs it SEE 10 186 SION seen eke a Peeve een Bebe ede Ee ad ee 10 187 SINE hiatal IA ta 10 188 StateSpace 0 eee 10 189 SUNN SET Gna aang Pestana boi ES Na 10 192 SWICK ofa aes a Dea i eae ae 10 195 Tapped Delay 0 cece 10 197 Unaty MINUS sra cata aed 10 199 UNIDAS contar a A 10 200 Unit Delay Enabled s sanaan aa 10 202 Unit Delay Enabled External IC ooo o o o o 10 204 Unit Delay Enabled Resettable oooo oo o oooo 10 206 Unit Delay Enabled Resettable External IC 10 208 Unit Delay External IC 2 2 2 2 02 10 210 Unit Delay Resettable 0 00 00 c eee eee 10 211 Unit Delay Resettable External IC o o o 10 21
120. N eretia AA eee ai 8 26 Function Reference 9 OVerview 20 2502 oni ale ec ns dd 9 2 AULOMXEXP sai ae ee a ek Be a bee See ea ee are are 9 4 fixptbestexp 2 iad wide ws Ad a wie eb Rae ee 9 6 fixptbestprecss ee tiene wine ee edna win a e ak thew ey whtS 9 7 fi Xpt convent caricia any a ri tay a caper ia ries 9 8 fixpt_convert_prep oooocoococooc ee 9 13 fixpt_lookl_func_approx eee es 9 14 fixpt l00KL fune Plot eeu ra 9 22 fixpt_restore lINKS oooooocoocoorrrrr es 9 24 floats east nna s o dyad ahs atcha esata tet aed ae icare eb a Peace i 9 25 fpupdate 0 eee 9 26 E 9 28 ME paa a e eN 9 31 A A A A eA te 9 32 Showfixptsimranges 0 0 0 0 cece eee ee 9 33 SINE ice A BAN See BI hee o irae 9 34 UNDG ta E ns teas eee AS 9 35 UITAC sive cased aE Oke Ee een deen Se Reet t 9 36 UNE occa ie Pee Sark ae oes Se Oe ean Pee ees 9 37 10 The Block Reference Pages 0ooococccccc 10 2 The Block Dialog BOX o cccccccccc 10 3 vi Contents Common Block Features ooooo o 10 4 Blod lt Parameters nnee anea it AA 10 4 Block Icon Labels 2 0 0 ccc cee ee ee eee 10 10 Port Data Type Display 00 00 e eee eee 10 10 The Fixed Point Blockset Libraries 10 12 PADS resect A cate AS eae ina ted aS ai cht A ante hee 10 22 Acumulator merai AA asa a Sa 10 23 Accumulator Resettable 0 0 eee 10 25 Accumulator Resettable Limited
121. ND Pf 0xDA Perform the specified bitwise operation on the inputs Bits The Bitwise Operator block is a masked S function that performs the specified bitwise operation on its operands Unlike the logic operations performed by the Logical Operator block bitwise operations treat the operands as a vector of bits rather than a single number You select the bitwise Boolean operation with the Operator parameter list The supported operations are given below Operation Description AND TRUE if the corresponding bits are all TRUE OR TRUE if at least one of the corresponding bits is TRUE NAND TRUE if at least one of the corresponding bits is FALSE NOR TRUE if no corresponding bits are TRUE XOR TRUE if an odd number of corresponding bits are TRUE NOT TRUE if the input is FALSE available only for single input Unlike Simulink s Bitwise Logical Operator block the Bitwise Operator block does not support shift operations Refer to Shifts on page 4 41 tolearn how to perform shift operations with the Fixed Point Blockset The size of the output depends on the number of inputs their vector size and the selected operator e The NOT operator accepts only one input which can be a scalar or a vector If the input is a vector the output is a vector of the same size containing the bitwise logical complements of the input vector elements e For a single vector input the block applies the operation except the NOT operator to all ele
122. OM but more data ROM Not significant Unevenly Spaced Data The execution speed is the slowest of the different spacings because the position search is slower and the interpolation requires more operations The error can be smaller because approximating a function with nonuniform curvature requires fewer points to achieve the same accuracy Uses more command ROM and less data ROM Not significant 9 19 fixpt_look1_func_approx Example The next example produces a lookup table for a sine function The inputs for the example are as follows funcstr sin 2 pi x xmin 0 xmax 0 25 xdt ufix 16 xscale 2 16 ydt sfix 16 yscale 2 14 rndmeth Floor errmax 2 10 spacing pow2 To create the lookup table type xdata ydata errWorst fixpt_look1 func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth errmax Sspacing The brackets area placeholder for the nptsmax parameter which is not used in this example Y ou can then plot the ideal function the approximation and the errors by typing fixpt_look1_func_plot xdata ydata funcstr xmin xmax xdt xscale ydt yscale rndmeth The fixpt_look1_func_plot function produces a plot of the fixed point sine function using these breakpoints and a plot of the error between the ideal function and the fixed point function The maximum absolute error and the number of points required are listed w
123. Qp and Qe 2 Theprevious product is converted to the output data type Rules for Arithmetic O perations Qa convert Qpawp roduct This conversion includes any necessary bit shifting rounding or overflow handling Conversions are discussed in Signal Conversions on page 4 27 3 Steps 1 and 2 are repeated for each additional number to be multiplied Example The Multiplication Process Suppose you want to multiply three numbers Each of these numbers is represented by a 5 bit word and each has a different radix point only scaling Additionally the output is restricted to a 10 bit word with radix point only scaling of 24 The multiplication is shown below for the input values 5 75 2 375 and 1 8125 ufix5 En2 E FixPt Constant 2 375 ufix5_En3 F FixPt Constant1 1 8125 ufix5 En4 E FixPt Constant2 Qa ufix10_En4 double Vv FixPt Display Gateway Out FixPt Product Applying the rules from the previous section the multiplication follows these steps 1 The first two numbers 5 75 and 2 375 are multiplied 4 37 4 Arithmetic O perations 4 38 QrawProduct 101 11 x 10 011 101 11 2 101 11 2 101 11 21 01101 10101 13 65625 Note that the radix point of the product is given by the sum of the radix points of the multiplied numbers 2 The result of step 1 is converted to the output data type Qtemp convert Qp awProduct 001101 1010 13 6250
124. S function that samples and holds its input for the specified sample period The block accepts one input and generates one output both of which can be scalar or vector If the input is a vector all elements of the vector are held for the same sample period Y ou specify the time between samples with the Sample time parameter A setting of 1 means the Sample time is inherited This block provides a mechanism for discretizing one or more signals in time or resampling the signal at a different rate If your model contains multirate transitions you must add Zero Order Hold blocks between the fast to slow transitions The sample rate of the Zero Order Hold must be set to that of the slower block For slow to fast transitions use the Unit Delay block For more information about multirate transitions refer to Using Simulink or the Real Time Workshop User s Guide Block Parameters Zero Order Hold Fixed Point Zero Order Hold mask link nee a zero order hold of one sample period Parameters Sample time fg Cancel Help Apply Sample time Sample time Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion No 10 227 Zero Order Hold 10 228 Code Generation Overview Code Generation Support Languages Storage Class of Variables Storage Class of Parameters Rounding Modes Overflow Handling Blocks Scaling
125. Scalar Expansion Of inputs and gain Accumulator Resettable Purpose Library Description Parameters and Dialog Box Compute a cumulative sum with external Boolean reset Calculus The Accumulator Resettable block computes a cumulative sum based on the values of an external Boolean reset signal The block can reset its state based on an external reset signal R The block has two input ports one for the input signal u and another for the reset signal R When the reset is false at time n the block adds the current value of the input signal u to the sum at time n 1 When the reset is true at time n the block resets the sum to the value of the Initial condition for previous output parameter and outputs the sum Block Parameters Accumulator Resettable r Fixed Point Accumulator Resettable mask link Running sum of all input u values with external boolean reset m Parameters Initial condition for previous output joo Output data type and scaling Inherit via internal rule y Round toward Floor zl I Saturate to max or min when overflows occur I Override data type s with doubles V Log minimums and maximums Cancel Help Apply Initial condition for previous output Set the initial condition for the previous output Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling from the driving block or by back propagati
126. Slope1 The slope of Prop is given by the slope of Refl Slope2 The slope of Prop is given by the slope of Ref2 Data Type Propagation Parameter Value Description max Slopet1 Slope2 min Slopet1 Slope2 Slope1 Slope2 Slope1 Slope2 PosRange1 PosRange2 max PosRange1 PosRange2 min PosRange1 PosRange2 PosRange1 PosRange2 PosRange1 PosRange2 The slope of Prop is given by the maximum slope of the reference signals The slope of Prop is given by the minimum slope of the reference signals The slope of Prop is given by the product of the reference signal slopes The slope of Prop is given by the ratio of the Refl slope to the Ref2 slope The range of Prop is given by the range of Refl The range of Prop is given by the range of Ref2 The range of Prop is given by the maximum range of the reference signals The range of Prop is given by the minimum range of the reference signals The range of Prop is given by the product of the reference signal ranges The range of Prop is given by the ratio of the Ref1 range to the Ref2 range Y ou control the precision of Prop with Slope1 and Slope2 and you control the range of Prop with PosRange1 and PosRange2 Additionally PosRange1 and PosRange2 are one bit higher than the maximum positive range of the associated reference signal The Slope Multiplicative adjustment parameter allows you to adjust the slope used by Prop by inclu
127. Subsystem Atomic subsystem Represent any block from a specified library Subsystem Enabled subsystem If block A conditionally executed subsystem that can be connected to an If block Triggered subsystem While subsystem Sinks Display Scope ToFile To Workspace Description Sample and hold with one sample period delay Implement zero order hold of one sample period Write data to a file Write data to the workspace In some cases fixed point signals that are not built in data types are converted to a real world value as it enters the block For example the To Workspace block will output a 32 bit signed integer with a scaling of 28 as a double Refer to the Using Simulink guide for detailed information about the data types handled by built in blocks Compatibility with Simulink Blocks Fra me based Signals Signals in Simulink can be processed as frame based signals M ost real time systems optimize throughput rates by processing data in batch or frame based mode where each batch or frame is a collection of consecutive signal samples that have been buffered nto a single unit The DSP Blockset that also supports frame based processing can use blocks from the Fixed Point Blockset in models that process frame based signals All Fixed Point Blockset blocks accept frame based signals for simulation and code generation except for the Dot Product and FIR blocks For further underst
128. T wo a o Quantized Value Q wo o 200 amp fi L fi fi f 240 260 280 300 320 340 360 380 Real World Value V K De wo E o o T Quantization Error K bit o o 240 260 280 300 320 340 360 380 Real World Value V K Clearly the general linear scale gives much better precision than the purely linear scale over the range of interest W hy Use Fixed Point Hardware Why Use Fixed Point Hardware Digital hardwareis becoming the primary means in which control systems and signal processingfilters areimplemented Digital hardware can be classified as either off the shelf hardware for example microcontrollers microprocessors general purpose processors and digital signal processors or custom hardware Within these two types of hardware there are many architecture designs These designs range from systems with a single instruction single data stream processing unit to systems with multiple instruction multiple data stream processing units Within digital hardware numbers are represented as either fixed point or floating point data types For both these data types word sizes are fixed at a set number of bits However the dynamic range of fixed point values is much less than floating point values with equivalent word sizes Therefore in order to avoid overflow or unreasonable quantization errors fixed point values must be scaled Since floating point processors can greatly simpli
129. Time Probe e Sample Rate Probe 10 181 Sample Time Multiply Parameters and Dialog Box 10 182 Block Parameters Sample Time Multiply m Fixed Point Sample Time Math mask link Add subtract multiply or divide the input signal by weighted sample time or just output weighted sample time or weighted sample rate This block only works with fixed sample rates so it will not work inside a triggered subsystem Parameters lt lt i Weight value Mo Implement using Online Calculations Dutput data type and scaling Inherit viaintemalule x Round toward For O I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Operation Specify operation to use Ts only 1 Ts only Weight value Enter weight of sample time Implement using Specify online calculations or offline scaling adjustment Output data type and scaling Specify whether the output data type and scaling are inherited by an internal rule or by back propagation Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the output data type is overridden with doubles Sample Time Multiply Log minimums and maximums If checked minimum and maximum simulat
130. When the enable signal E is on and the reset signal R is false the block outputs the input signal delayed by one sample period When the enable signal E is on and the reset signal R is true the block resets the current state to the initial condition given by the signal IC and outputs that state delayed by one sample period When the enable signal is off the block is disabled and the state and output do not change except for resets The enable signal is on when E is not 0 and off when E is 0 The output data type is the same as the input u and the initial condition IC data type which can be any data type but must be the same The enable E and reset R can be any data type Y ou specify the time between samples with the Sample time parameter A setting of 1 means the Sample time is inherited Block Parameters Unit Delay Enabled Resettable External IC r Fixed Point Unit Delay Enabled Resettable External Initial Condition mask Normally the output is the signal u delayed by one sample period When the reset signal R is true the state and the output are always set equal to the initial condition signal IC This reset action is vectorized and supports scalar expansion When the enable signal is false the block is disabled and the state and output values do not change except for resets The enable action is vectorized and supports scalar expansion Parameters Sample time a AAA Cancel Help Epp Unit Delay
131. a complex signal from real and imaginary Complex inputs Nonlinear Description Manual Switch Multiport Switch Switch between two inputs Data types must be the same Choose between block inputs The first port cannot be fixed point but all others accept fixed point Compatibility with Simulink Blocks Signals amp Systems Description Bus Creator Bus Selector Demux From Goto Goto Tag Visibility Ground Matrix Concatenation Merge Mux Probe Selector Signal Specification Terminator Width Group signals into a single bus signal Output selected input signals Separate a vector signal into output signals Accept input from a Goto block Pass block input to From blocks Define the scope of a Goto block tag Gound an unconnected input port Concatenate array inputs Combine several input lines into a scalar line Combine several input lines into a vector line Output an input signal s width sample time and or signal type Select or reorder the elements of the input vector Specify attributes of a signal The data type must be set to auto or use the data type propagation to force the signal to the data type Terminate an unconnected output port Output the width of the input vector 1 15 1 Introduction 1 16 Subsystems Description Atomic Subsystem Configurable Subsystem Subsystem Enabled If If Body Triggered While
132. a unit delayed version of the first output Having both signals is useful for implementing recursive calculations where the result should include the most recent inputs The second output of a Unit Delay With Preview can be safely feedback into calculations of the block s inputs without causing an algebraic loop Meanwhile the first output will show the most up to date calculations This block has both an extemal reset value and an internal initial condition The reset value signal RW is used only when the reset signal A is true When this occurs the first output signal is forced to equal RY The second output signal is not affected until one time step later The intemal initial condition is used only when the model starts or when a parent enabled subsystem is reset The internal initial condition only has direct effect on the second output The first output is only affected through feedback This reset action is vectorized and supports scalar expansion When the enable signal is false the block is disabled and the state and output values do not change except for resets The enable action is vectorized and supports scalar expansion m Parameters Initial condition A Sample time ay Cancel Help Initial condition Initial condition Sample time Sample time Characteristics Input Port u Any data type supported by the blockset Input Port E Any data type supported by the blockset Input Port R Any data type
133. acros Bit Sizes for Target C Compiler You can modify the TLC file to accommodate custom target sizes by explicitly specifying the number of bits defined for char short int or long data types If you do not manually override these sizes then the sizes for the MATLAB host computer are automatically selected For example if you are running MATLAB under the Windows operating system then char short int and long default to 8 16 32 and 32 bits respectively Most other supported operating systems use the same data type sizes However DEC Alpha for example defines a long as 64 bits A 13 A Code Generation Selected Bibliography B Selected Bibliography B 2 Burrus C S H McClellan A V Oppenheim T W Parks R W Schafer and H W Schuessler Computer Based E xercises for Signal Processing Using MATLAB Prentice Hall Englewood Cliffs New J ersey 1994 Franklin G F D Powell and M L Workman Digital Control of Dynamic Systems Second Edition Addison Wesley Publishing Company Reading Massachusetts 1990 Handbook For Digital Signal Processing edited by S K Mitra and F Kaiser J onn Wiley amp Sons Inc New York 1993 Hanselmann H Implementation of Digital Controllers A Survey Automatica vol 23 no 1 pp 7 32 1987 J ackson L B Digital Filters and Signal Processing Second Edition Kluwer Academic Publishers Seventh Printing Norwell Massachusetts 1993 Middle
134. ad zone parameter The block output depends on the input and dead zone e f the input is within the dead zone greater than the lower limit and less than the upper limit the output is zero e If theinputis greater than or equal tothe upper limit the output is theinput minus the upper limit e f the input is less than or equal to the lower limit the output is the input minus the lower limit Block Parameters Dead Zone m Fixed Point Dead Zone mask link Output zero for inputs within deadzone Offset input signals by either the Start or End value when outside of the deadzone Parameters End of dead zone 1 Start of dead zone 1 I Saturate to max or min when overflows occur Cancel Help Apply Start of dead zone The lower limit of the dead zone End of dead zone The upper limit of the dead zone Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Dead Zone Example Characteristics Consider the model shown below which compares a fixed point signal and the output generated by the Dead Zone block Thesignal sourceis a sine wave with unit amplitude The Start of dead zone parameter is configured to 0 5 and the End of dead zone parameter is configured to 0 5 Scope g Gateway Out Sine Wave Gateway In The resulting output is shown below
135. adding I O blocks to Simulink block diagrams and downloading the code generated by Real Time Workshop to a second PC that runs the xPC Target real time kernel for rapid prototyping and hardware in the loop testing of control and DSP systems xiv Using This G uide Using This Guide This guide describes how to use the F ixed P oint Blockset to emulate fixed point arithmetic when simulating discrete time dynamic systems using Simulink It contains tutorial information that describes how to use the blockset features as well as a reference entry for each block and function in the blockset Ex pected Background This guide assumes you are familiar with both MATLAB and Simulink If you are new to MATLAB you should read Getting Started with MATLAB If you are new to Simulink you should read Using Simulink You should also have a basic understanding of Boolean algebra and binary word representations Learning the Fixed Point Blockset If You Are a New User Start with Chapter 1 Introduction which describes how the Fixed Point Blockset can help you bridge the gap between designing a dynamic system and implementing it on fixed point digital hardware Then read Chapter 2 Getting Started which describes many Fixed Point Blockset features and provides a simple example After reading this chapter you should be able to create simple fixed point models If you want detailed information about a specific block refer to Chapte
136. ae ies Advanced Demos Filters and Systems 2 G etting Started An Overview of Blockset Features This section provides a brief overview of the most important Fixed Point Blockset features After reading this section and Example Converting from Doubles to Fixed Point on page 2 10 you should be able to configure simple fixed point models that suit your own application needs Configuring Fixed Point Blocks Y ou configure fixed point blocks with a parameter dialog box Block configuration consists of supplying values for parameters via editable text fields check boxes and parameter lists The dialog box for the Gateway In block is shown below Block Parameters Gateway In r Fixed Point Gateway In mask link Convert the input to the data type and scaling of the output The conversion has two possible goals One goal is to have the Real World Values of the input and the output be equal The other goal is to have the Stored Integer Values of the input and the output be equal Overflows and quantization errors can prevent the goal from being fully achieved The input and the output support all built in and fixed point data types Parameters Input and Output to have equal PEA Dutput data type and scaling Specity via dialog y Output data type ex sfix 16 uint 8 float single sf 6 Output scaling Slope or Slope Bias ex 2 9 2710 Lock output scaling so autoscaling too
137. also used to initialize the state when the model starts or when a parent enabled subsystem is reset This reset action is vectorized and supports scalar expansion When the enable signal is false the block is disabled and the state and output values do not change except for resets The enable action is vectorized and supports scalar expansion m Parameters Initial condition ee Sample time _ _ Cancel Help Initial condition Initial condition Sample time Sample time Characteristics Input Port u Any data type supported by the blockset Input Port E Any data type supported by the blockset Input Port R Any data type supported by the blockset Output Ports Same as the input u Direct Feedthrough Yes to upper output port No to lower output port Scalar Expansion Yes See Also Unit Delay and related blocks 10 218 Unit Delay With Preview Enabled Resettable External RV Purpose Support calculations that have feedback and depend on the current input Library Delays amp Holds Description The Unit Delay With Preview Enabled Resettable External RV block supports calculations that have feedback and depend on the current input The block can reset its state based on an external reset signal R The block has two output ports When the external enable signal E is on and the reset R is false the upper port outputs the signal and the lower port outputs the signal delayed by one sample period The bl
138. anding of frame based processing refer to Working with Signals in the DSP Blockset documentation Matrix Signals The Simulink documentation refers to two dimensional 2 D signals as matrices Simulink blocks can output two dimensional signals wherea two dimensional 2 D signal consists of a stream of two dimensional arrays emitted at a frequency of one 2 D array or matrix per sample time All Fixed Point Blockset blocks support matrix based signals for simulation and code generation except for the Dot Product and FIR blocks For further understanding of matrix based processing refer to Working with Signals in the Simulink documentation 1 17 1 Introduction How to Get Online Help The Fixed Point Blockset provides several ways to get online help Block System and Filter Help Press the Help button in any block system or filter dialog box to view ts HTML based documentation e Help Desk Type helpdesk or doc at the MATLAB command line to load the main MATLAB help page into the Help browser e Release Information Typewhatsnew fixpoint at the MATLAB command line to view information related tothe version of the Fixed Point Blockset that you re using 1 18 Getting Started An Overview of Blockset Features Configuring Fixed Point Blocks Additional Features and Capabilities Example Converting from Doubles to Fixed Point Block Descriptions ars Simulation Results Demos Basic Demos fie a
139. apolate Instead the elements in x and y nearest and above the current inputs are found The corresponding element in z is then used as the output If there are no elements in x or y above the current inputs then the nearest elements are found For a detailed description of all other block parameters refer to Block Parameters on page 10 4 To avoid parameter saturation errors the automatic scaling script autofixexp employs a special rule for the Look Up Table 2D block autofixexp modifies the scaling by using the output look up values in addition to the logged minimum and maximum simulation values This prevents the data from being saturated to different values The look up values are given by the Table parameter the TableDataPoints variable Block Parameters Look Up Table 2 D rm Fixed Point Look Up Table 2 D mask link Approximate a two dimensional function using a selected look up method Parameters Row i TTT Col TCS Table Look Up Method JinterpolationUseEndVaues E Output data type and scaling Specify viadiog Output data type ex sfix 16 uint 8 float single Output scaling Slope or Slope Bias ex 2 9 271 0 FF Lock output scaling so autoscaling tool can t change it Round toward For SOSOS S S SiSY FP Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Cancel Help Apply 10 151 Look
140. arameter list refer to the Gateway In block description The Output data type parameter list specifies the Simulink data type to use for the output All built in data types are supported as well as the boolean data type auto indicates the Fixed Point Blockset data type is converted to whatever data type Simulink back propagates MATLABSs built in integer data types are limited to 32 bits If you want to output fixed point numbers that range between 33 and 53 bits without loss of precision or range you should use the Gateway Out block to store the value inside a double 10 107 Gateway Out If you want to output fixed point numbers with more than 53 bits without loss of precision or range then you must break the number into pieces using the Gain block and then output the pieces using the Gateway Out block For example suppose the original signal is an unsigned 128 bit value with default scaling You can break this signal into four pieces using four parallel Gain blocks configured with the gain and output settings shown below Piece Gain Output Data Type 1 2 0 uint 32 Least significant 32 bits 2 2 32 uint 32 3 27 64 uint 32 4 2 96 uint 32 Most significant 32 bits For each Gain block you must also configurethe Round toward parameter to Floor and the Saturate to max or min when overflows occur check box must be unchecked Parameters and Dialog Box Block Parameters Gateway Out m Fixed Point Gat
141. arameters and Dialog Box Delay a scalar signal multiple sample periods and output all the delayed versions Delays amp Holds The Tapped Delay block delays its input by the specified number of sample periods and outputs all the delayed versions This block provides a mechanism for discretizing a signal in time or resampling the signal at a different rate Y ou specify the time between samples with the Sample time parameter Y ou specify the number of delays with the Number of delays parameter A value of 1 instructs the block to inherit the number of delays by back propagation Each delay is equivalent tothez discrete time operator which is represented by the Unit Delay block The block accepts one scalar input and generates an output for each delay The input must be a scalar You specify the order of the output vector with the Order output vector starting with parameter list Oldest orders the output vector starting with the oldest delay version and ending with the newest delay version Newest orders the output vector starting with the newest delay version and ending with the oldest delay version The block output for the first sampling period is specified by the Initial condition parameter Careful selection of this parameter can minimize unwanted output behavior Block Parameters Tapped Delay r Fixed Point Tapped Delay Line mask link Delay a signal N sample periods and output all the delay versions r Para
142. arameters dialog box is configured 10 9 10 Block Reference 10 10 Block Icon Labels Many blockset icons look like those of built in Simulink blocks For this reason all fixed point icons have an F for Fixed Point associated with them An F in the lower right upper left corner of the icon means the block output input is a Fixed Point Blockset data type The Gateway In Gateway In Inherited and Gateway Out blocks have additional labels which reflect how the input and output signals are treated If the block input or output is treated as a real world value then a V appears by the relevant port If the block input or output is treated as a stored integer then an I appears by the relevant port Many blocks have additional labels that indicate logical operations arithmetic operations numerical values and so on These labels will help you to quickly understand the behavior of fixed point models without examining individual block dialog boxes Port Data Type Display To display the data types of ports in your model select Port Data Types from Simulink s Format menu The port display for fixed point signals consists of three parts the data type the number of bits and the scaling The data type and number of bits reflect the block s Output data type parameter value or the data type that is inherited from the driving block The scaling reflects the block s Output scaling parameter value or
143. aring bits 10 32 code generation 2 8 A 2 and multiplication 4 36 and scaling 10 104 and signal conversions 4 29 and stored integer output 10 107 and summation 4 32 computational noise 4 2 and rounding 4 3 computational units 4 30 constant scaling for best precision 3 12 limitations for code generation A 12 contiguous bits 3 17 conversions parameter signal 4 27 Seealso online conversion offline conversion converting old models 9 26 D data types 2 3 3 10 built in 1 13 display 10 10 fractional numbers 2 4 generalized fixed point numbers 2 4 IEEE numbers 2 4 inherited 10 5 integers 2 3 overriding with doubles 10 9 propagation 10 49 selecting 10 4 dead zone 10 58 demos 2 15 denormalized numbers 3 22 development cycle 1 12 dialog box parameters 10 4 data type 10 4 lock output scaling 10 8 logging min max data 10 9 overflow handling 10 9 overriding with doubles 10 9 rounding 10 8 scaling 10 6 digital controller 6 7 digital filter 5 2 direct form realization 5 4 and feedback controller demo 6 8 division 10 166 blockset rules 4 39 scaling recommendations 4 23 4 24 using slope bias encoding 4 23 dot product 10 76 double bits 4 35 7 3 double precision format 3 19 doubles override 9 29 Index E E mbedded C Real Time Target A 8 encapsulation 9 9 encoding scheme 3 5 eps 3 21 examples constant scaling for best precision 3 12 conversions and arithmetic operations 4 46 converting a built in model to fixed point
144. ases generate the same code The comparison will focus on the amount of read only memory ROM used for data the amount of ROM used for commands and the speed with which the commands are executed As a specific example this comparison uses the demo fxpdemo_approx_sin There are three fixed point lookup tables in this model All three lookup tables approximate the function sin 2 pi u over the first quadrant All three achieve a worst case error of less than 2 8 However they have different restrictions on their breakpoint spacing You can use the model fxpdemo_approx which this demo opens to generate code with Real Time Workshop This section presents several segments of the generated code These segments of code were edited and arranged for clarity and to emphasize key differences This section covers the following topics Data ROM Required on page 8 21 Determining Out of Range nputs on page 8 22 e Determining the Location of the Input on page 8 22 Performing Interpolation on page 8 24 e Conclusion on page 8 26 To open the demo type at the MATLAB prompt fxpdemo_approx_sin This opens the model shown below Effect of Spacing on Speed Error and Memory Usage fxpdemo_approx olx Eile Edit View Simulation Format Tools Help DSa trel Scla mt gt m Normal dl ufix16_En14 double gt double _ double ttpi sin vAngle yldeal Gain Repeating Gateway Out Sine Ideal
145. ata type information in these ways e Parameters The numerical parameter values of some fixed point blocks inherit the data type of an input signal or the output signal Other blocks require that you specify the parameter data type explicitly with the Parameter data type parameter e Output The output of some fixed point blocks inherits the data type of the input signal Other blocks require that you specify the output data type with the Output data type parameter Still other blocks provide you with the option Common Block Features of inheriting the output data type and scaling information from a driving block or specifying the data type For the latter case you control how the output data type and scaling is specified with the Output data type and scaling parameter list This list supports three choices Specify via dialog Inherit via internal rule and Inherit via back propagation The parameter choices involving data type inheritance are designed to minimize specification burden Note that some fixed point blocks support only two of the three choices If you select Specify via dialog you must explicitly specify the output data type with the Output data type parameter If you select Inherit via internal rule the output data type is inherited from the input s The goal of the inheritance rule is to select the natural data type and scaling for the output The specific rule that is used depends on the block operation F
146. ation 00 00 c cece eee 3 4 e daak eh eid Wea Pew bel Ae a Bode sae 3 5 QUANtiZatiON ori 3 6 Range and Precision ooocococccccccoco 3 8 Example Fixed Point Scaling oococococcococo 3 10 Example Constant Scaling for Best Precision 3 12 ii Contents Floating Point Numbers sanaaa 3 16 Scientific Notation 0 0 2 eee 3 16 THLE E Es Format ss mausia te tee aden a Byte whee 8 3 18 Range and Precision 00 cece ee 3 20 Exceptional Arithmetic 0 00 cece eee 3 22 4 OVEPrVIOW oc ea shes Ge aoe Behe Gite a 2 OS ATRE R ees Dae 4 2 Limitations on Precision 0 0000 eee eeuee 4 3 ROUNGING mia ooo Be ES ee GE ie eh ee eae E 4 3 Padding with Trailing Zeros 00 00 c eee eee eee 4 9 Example Limitations on Precision and Errors 4 10 Example Maximizing Precision 000 cece eee 4 11 Limitations on Range 000 e eee eee 4 12 Saturation and Wrapping 0 e cece eee eee 4 13 Gard Bits curia eee SELIG ee oe lee RE ees 4 15 Example Limitations on Range 000eeeeeee 4 15 Recommendations for Arithmetic and Scaling 4 16 ACItION ceo e a bce dies Par ee i 4 16 ACCUMULALION Gia AO Pete aeons 4 19 Multiplication 0 0 0 cece 4 20 Gali eects eit cso eed oe ee ee ee 4 21 DIVISION 3 0265 claude ela eee a kd bee eo ee 4 23 SUNDAY Hira ia iode menaa da 4 25 Parameter and Signal C
147. ator Backward Resettable Limited block only by the first and last terms in the cumulative sum Integrator Forward Resettable Limited Parameters and Dialog Box Block Parameters Integrator Forward Resettable Limited r Fixed Point Integrator Forward Resettable Limited mask link Discrete time limited integration of the input u using forward method with external boolean reset This block only works with fixed sample rates so it will not work inside a triggered subsystem m Parameters Gain value fc TS Initial condition for previous output wo Upper limit pb Lower limit fo Output data type and scaling Inherit viaintemalule Round toward Floor na I Saturate to max or min when overflows occur T Override data type s with doubles Y Log minimums and maximums Cancel Help Apply Gain value Specify the weight by which the sample time is multiplied Initial condition for previous output Set the initial condition for the previous output Upper limit The upper limit for saturation of the cumulative sum Lower limit The lower limit for saturation of the cumulative sum Output data type and scaling The options are e Specify via dialog e Inherit via internal rule e Inherit via back propagation 10 125 Integrator Forward Resettable Limited When Specify via dialog is selected you can specify the Output data type and Output scaling parameters Round toward R
148. aximum and minimum possible values to fit The map scale should also make the most of the paper in order to get maximum detail Similarly the binary scale for a measurement should make the most of the processor in order to get maximum precision Use of standard scales for measurements has definite compatibility advantages However there are times when it is worthwhile to break convention and use a unique nonstandard scale There are also occasions when a mix of uniqueness and compatibility makes sense Selecting a Measurement Scale Suppose that measurements of liquid water are to be made and suppose that these measurements must be represented using 8 bit unsigned integers Fortunately the temperature range of liquid water is limited No matter what scale is used liquid water can only go from the freezing point to the boiling point Therefore this range of temperatures must be captured using just the 256 possible 8 bit values 0 1 2 255 Physical Q uantities and M easurement Scales One approach to representing the temperatures is to use a standard scale For example the units for the integers could be Celsius Hence the integers 0 and 100 represent water at the freezing point and at the boiling point respectively On the upside this scale gives a trivial conversion from the integers to degrees Celsius On the downside the numbers 101 to 255 are unused By using this standard scale more than 60 of the number range has bee
149. bit inversion translation into one s complement followed by the addition of a one For example the two s complement of 000101 is 111011 Whether a fixed point value is signed or unsigned is usually not encoded explicitly within the binary word i e there is no sign bit Instead the sign information is implicitly defined within the computer architecture Radix Point Interpretation The radix point is the means by which fixed point numbers are scaled It is usually the software that determines the radix point When performing basic math functions such as addition or subtraction the hardware uses the same logic circuits regardless of the value of the scale factor In essence the logic circuits have no knowledge of a scale factor They are performing signed or unsigned fixed point binary algebra as if the radix point is to the right of bo Within the Fixed Point Blockset the main difference between fixed point data types is the default radix point For integers and fractionals the radix point is fixed at the default value For generalized fixed point data types you must explicitly specify the scaling by configuring dialog box parameters or inherit the scaling from another block The supported fixed point data types are described below Integers The default radix point for signed and unsigned integer data types is assumed tobejust totheright of the LSB You specify unsigned and signed integers with the uint and sint functions respectiv
150. c O perations m Fixed Point Gateway In mask link Convert the input to the data type and scaling of the output The conversion has two possible goals One goal is to have the Real World Values of the input and the output be equal The other goal is to have the Stored Integer Values of the input and the output be equal Overflows and quantization errors can prevent the goal from being fully achieved The input and the output support all built in and fixed point data types Parameters Input and Output to have equal Real World Value x Output data type and scaling Specity via dialog y Output data type ex sfix 16 uint 8 float single fet 6 Output scaling Slope or Slope Bias ex 2 9 210 FF Lock output scaling so autoscaling tool can t change it Round toward Floor Y Log minimums and maximums Cancel Help The Fixed Point Blockset rounding modes are discussed below The data is generated using Simulink s Signal Generator block and doubles are converted to signed 8 bit numbers with radix point only scaling of 2 Round Toward Zero The computationally simplest rounding mode is to drop all digits beyond the number required This mode is referred to as rounding toward zero and it results in a number whose magnitude is always less than or equal to the more precise original value In MATLAB you can round to zero using the fix function Rounding toward zer
151. caling of the two inputs In other words the scaling is inherited e Scaling choices are based on Minimizing the number of arithmetic operations of the result Maximizing the precision of the result Additionally radix point only scaling is presented as a special case of the general encoding scheme In embedded systems the scaling of variables at the hardware interface the ADC or DAC is fixed However for most other variables the scaling is something you can choose to give the best design When scaling fixed point variables it is important to remember that e Your scaling choices depend on the particular design you are simulating e There is no best scaling approach All choices have associated advantages and disadvantages It is the goal of this section to expose these advantages and disadvantages to you Addition Consider the addition of two real world values Va VptVe These values are represented by the general slope bias encoding scheme described in Scaling on page 3 5 In a fixed point system the addition of values results in finding the variable Qa 4 16 Recommendations for Arithmetic and Scaling Fp E Qa 722 Qp B B Ba F a ES F a Ec EQ F F S a This formula shows e In general Qa is not computed through a simple addition of Qp and Q e In general there are two multiplies of a constant and a variable two additions and some additional bit shifting Inherit
152. canonical forms presented in this chapter optimize the implementation with respect to some factor such as minimum number of delay elements In general when choosing a realization method you must takethese factors into consideration e Cost The cost of the realization might rely on minimal code and data size e Timing constraints Real time systems must complete their compute cycle within a fixed amount of time Some realizations might yield faster execution speed on different processors O verview Output signal quality The limited range and precision of the binary words used to represent real world numbers will introduce errors Some realizations are more sensitive to these errors than others The Fixed Point Blockset allows you to evaluate various digital filter realization methods in a simulation environment Following the development cycle outlined in The Development Cycle in Chapter 1 you can fine tune the realizations with the goal of reducing the cost code and data size or increasing signal quality After the desired performance has been achieved you can use the Real Time Workshop to generate rapid prototyping C code and evaluate its performance with respect to your system s real time timing constraints Y ou can then modify the model based upon feedback from the rapid prototyping system The presentation of the various realization structures takes into account that a summing junction is a fundamental operator thus
153. check box as shown below as shown below Block Parameters 42D m Fixed Point Gateway In mask link Convert from a Simulink built in data type to a Fixed Point Blockset data type m Parameters Treat input as Real World Value x Output data type and scaling Specity via dialog y Output data type ex sfix 16 uint 8 float single stist8 Output scaling Slope or Slope Bias ex 2 9 274 IV Lock output scaling so autoscaling tool can t change it Round toward Nearest X IV Saturate to max or min when overflows occur IV Override data type s with doubles M Log minimums and maximums Cancel Help Override the output data type with doubles Note You can display the A2D dialog box by double clicking on the A2D entry in the interface The procedure and results for this simulation are shown below 6 18 Simulation Results Fixed Point Blockset Interface fxp_feedback or x Log Min Max fuse block params Autoscale Safety Margin 20 Log Mode overwrite log Datatype Override Use black params Data Scaling Type 1 S8 Y Qx2 4 AE gye N t Qx2 Denoninator Terns Q 2 27 Select the A2D Combine Terms V Qx2 28 Down Cast Y 0x2 12 block and override the output data type with doubles Block path fxp_feedback Run Stop Autoscale Plot Help Close 2 Run the simulation 3 Launch the Plot System A close up
154. cified with the Sample time parameter A setting of 1 means the Sample time is inherited Note The Unit Delay block accepts continuous sample times When it has a continuous sample time the block is equivalent to the built in Memory block This block provides a mechanism for discretizing one or more signals in time or resampling the signal at a different rate If your model contains multirate transitions then you must add Unit Delay blocks between the slow to fast transitions The sample rate of the Unit Delay must be set to that of the slower block For fast to slow transitions use the Zero Order Hold block For more information about multirate transitions refer to Using Simulink or the Real Time Workshop User s Guide Unit Delay Parameters a nd Dia log Box He SS Unit Delay r Fixed Point Unit Delay mask link Delay a signal one sample period m Parameters Initial condition ee A O O OSK Sample time IN Cancel Help Apply Initial condition The initial output of the simulation Sample time Sample time Conversions The Initial condition parameter is converted from a double to the input data type offline using round to nearest and saturation Characteristics Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough No Scalar Expansion Of input or initial conditions 10 201 Unit Delay Enabled Purpose Library
155. ckset specific data types Examples of blockset specific data types include 32 bit signed integers with a scaling of 28 and 18 bit unsigned integers with a scaling of 20 Note If you want to connect Simulink blocks to fixed point blocks that output blockset specific data types then you must use the fixed point gateway or data type conversion blocks to convert to a built in data type Most Simulink blocks that accept any Fixed Point Blockset data type have these characteristics e Their only function is to rearrange the signal for example the Selector or Mux blocks e They do not perform calculations such as addition or relational operations e They do not in general have initial conditions for example the Unit Delay block However if a Simulink block supports fixed point both the Simulink block and the Fixed Point block permit the initial conditions to be set to any value The Simulink blocks that can accept any Fixed Point Blockset data type are listed below 1 13 1 Introduction 1 14 Simulink Blocks That Accept Any Fixed Point Data Type Continous Description Memory Output the block input from the previous time step Discrete Description Unit Delay Sample and hold with one sample period delay Zero Order Hold Implement zero order hold of one sample period Math Description Complex to Output the real and imaginary parts of a complex input Real mag signal Real l mag to Output
156. configuring Datatype Override toUse block params 4 Run thesimulation by selecting the Run button The automatic scaling results generated by step 2 are captured from the MATLAB workspace and applied to the simulation 5 Launch the Plot System interface and plot the plant output signal The procedure and results for this simulation are shown below 6 15 6 Tutorial Feedback Controller Simulation 6 16 Fixed Point Blockset Interface fxpt_feedback oy x 1 Specify an additional Log Min Max Use block params Autoscale Safety Margin 20 range of at least 20 Log Mode Overwrite log Datatype Override Use block params Block Name MIN MAX Data Scaling EN 3 _ Turn off global overid Up Cast 2 4 S16 V Q 2 12 urn o g obal overide Numerator Terns 5 677 5 7 S32 V 0x 2 28 Denominator Terns 8 524 5 401 S32 V 0 2 27 Combine Terns 6 464 4 331 532 V 0 2 28 Down Cast 2 421 4 331 S16 V 0 2 12 Block path fxpt_feedback Run Stop Autoscale Plot Help Close oo botes 4 Run the simulation 2 Script Each block is scaled based on its own maximum and minimum values obtained from the previous simulation using double precision numbers As shown above the interface displays the new scaling for each block that had its scaling changed This scaling is based on the raw simulation values multiplied by 1 2 Note that no saturations or overflows are reported 5 Launch the plot system Simulation R
157. ction is vectorized and supports scalar expansion Parameters Initial condition INS Sample time tt Cancel Help Amply Initial Condition The initial output of the simulation Sample Time Sample time Input Port u Any data type supported by the blockset Input Port R Any data type supported by the blockset Output Port Same as the input u 10 211 Unit Delay Resettable Direct Feedthrough No of the input port Yes of the reset port Scalar Expansion Yes See Also Unit Delay and related blocks 10 212 Unit Delay Resettable External IC Purpose Library Description Parameters and Dialog Box Characteristics Delay a signal one sample period with reset and external initial condition Delays Holds TheUnit Delay Resettable External IC block delays a signal one sample period The block can reset its state based on an external reset signal R The block has two input ports one for the input signal u and the other for the reset signal R When thereset signal is false the block outputs the input signal delayed by one time step When the reset signal is true the block resets the current state to the initial condition given by the signal IC and outputs that state delayed by one time step Theinput u and initial condition IC must be the same data type but can be any data type The output is the same data type as the inputs u and IC The reset R can be any data type Y ou specify th
158. d Look up method Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling by back propagation Output data type Any data type supported by the Fixed P oint Blockset Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generalized fixed point output Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace The Vector of input values parameter is converted from doubles to the input data type The Vector of output values parameter is converted from doubles tothe output data type Both conversion are performed offline using 10 143 Look Up Table Example Characteristics 10 144 round to nearest and saturation Refer to Parameter Conversions on page 4 27 for more information about parameter conversions Suppose the Look Up Table block is configured to use a vector of input values given by 5 5 and a vector of output values given
159. d subtractions This is slow and requires a fair amount of machine code but this code can be shared Most processors provide a way to do logical and arithmetic shifts left and right A distinguishing difference is whether the processor can do N shifts in one instruction barrel shift or requires N instructions that shift one bit at a time The barrel shift will require less code Whether or not the barrel shift also increases speed depends on the hardware that supports the operation The compiler can also complicate the comparison In the previous example the command uAngle gt gt 8 essentially takes the upper 8 bits in a 16 bit word The compiler may detect this and replace the bit shifts with an instruction that takes the bits directly If the number of shifts is some other value such as 7 this optimization would not occur Performing Interpolation In theory you can calculate the interpolation with the following code y yData iRght yData iLeft u xData iLeft xData iRght xData iLeft yData iLeft Theterm xData iRght xData iLeft is the spacing between neighboring breakpoints If this value is constant i e even spacing some simplification is possible If spacing is not just even but also a power of two then very significant simplifications are possible for fixed point implementations Uneven case For the uneven case one possible implementation of the ideal interpolation in fixed point is as
160. d PointLead Compare output from the Lead and Lag Filter block to and Lag Filters output from analogous Simulink filters built using the Discrete Filter block Fixed Point Compare output from the State Space Realization State Space realization to output from the analogous built in Simulink State Space and Discrete State Space block Y ou can invoke a filter or system demo by double clicking the appropriate subsystem For example toinvoke the Fixed Point Derivatives demo double click the Demo Derivative subsystem For more information about filters and systems refer to Chapter 7 Building Systems and Filters Additional fixed point demos exist for direct form II series cascade form and parallel form realizations These demos and realizations are discussed in Chapter 5 Realization Structures 2 17 2 G etting Started 2 18 Data Types and Scaling Overview Fixed Point Numbers Signed Fixed Point Numbers Radix Point Interpretation Scaling ee Quantization Range and Precision Example Fixed Point Scaling Example Constant Scaling for Best Precision Floating Point Numbers Scientific Notation ThelEEE Format Range and Precision Exceptional Arithmetic 3 2 3 3 34 3 5 3 8 3 10 312 3 16 3 16 3 18 3 20 3 22 3 Data Types and Scaling Overview In digital hardware numbers are stored in binary words A binary word is a fixed length sequence of binary dig
161. d hit the OK button The System Target File Browser for this configuration is shown below System Target File Browser fxpdemo_code_only BEI System target file Description TI Code Composer Studio target DOS 46 Real Time Target Embedded C Real Time Target Visual C C Project Makefile only for the ert target TI EVM67x target Generic Real Time Target Visual C C Project Makefile only for the grt target Generic Real Time Target with dynamic memory allocation Visual C C Project Makefile only for the grt_malloc target Beta LE O Lynx Embedded OSEK Real Time Target Rapid Simulation Target Ada83 Target for GNAT Ada Simulation Target for GNAT Ada Multitasking Real Time Target for GNAT Real Time Windows Target S function Target TI Code Composer Studio target TI EVM67x target Tornado VxWorks Real Time Target xPC Target z Selection Bat toaster Rl2nightly rtw c ert ert tle DK Cancel The Fixed Point Blockset supports all targets except those that generate Ada code Note that you may not have ERT code generation capability If this is the case you should select the Generic Real Time Target Toconfigurethe code generation parameters select ERT code generation options from the Category parameter list Select the Integer code only check box and any other options you may require To configure additional code generation optimizations such as inlining select General code generation op
162. ddition and subtraction 4 31 for multiplication 4 36 for signals 4 28 online conversion for addition and subtraction 4 31 for multiplication 4 36 for signals 4 28 online help 1 18 overflow 3 21 4 2 4 12 and code generation A 4 handling by fixed point blocks 10 9 logging 6 10 10 9 overriding with doubles 9 29 10 9 global override 6 12 individual override 6 18 P padding with trailing zeros 4 9 and feedback controller demo 6 7 parallel form realization 5 10 parameter conversion 4 27 See also conversions percent safety margin 9 29 plot system interface 9 30 port data type display 10 10 precision best 9 6 maximum 9 7 of fixed point numbers 3 9 of IEEE floating point numbers 3 21 prerequisites xviii propagation of data types 10 49 Q quantization 4 2 and feedback controller demo 6 12 and rounding 4 3 of a real world value 2 12 3 6 R radix point 3 3 radix point only scaling 3 6 range of fixed point numbers 3 9 of IEEE floating point numbers 3 20 RangeFactor 9 4 rapid simulation target A 12 realizations and data types 7 2 and scaling 7 2 design constraints 5 2 direct form 5 4 parallel form 5 10 series cascade form 5 7 Real Time Workshop ERT A 8 external mode A 12 GRT A 5 Production Coder A 5 rapid simulation target A 12 Index Target Language Compiler A 13 real world value 3 5 as block input 10 100 relational operation 10 171 relay 10 173 release information 1 18 restoring broken links 9 24
163. de for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Yes 10 161 MinMax Running Resettable Purpose Library Description u mintu yp x uy Parameters and Dialog Box Characteristics See Also 10 162 Determine the minimum or maximum of a signal over time Math The MinMax Running Resettable block outputs the minimum or maximum of all past inputs u You specify whether the block outputs the minimum or the maximum with the Function parameter The block can reset its state based on an external reset signal R When the reset signal R is TRUE the block resets the output to the value of the Initial condition parameter Block Parameters MinMiax Running Resettable m Fixed Point MinMax Running Resettable mask link Output the max or min of all past inputs u The output is reset to the initial condition when the Reset input signal A is TRUE This reset action is vectorized and supports scalar expansion Parameters nc aaa Initial condition fo 0 Cancel Help Appl
164. de is to Floor Example 5 Using errmax with Power of Two Spacing The next example shows how to construct a lookup table that has power of two spacing and a specified worst case error To try the example you must first enter the enter the parameter values given in the section Setting Function Parameters for the Lookup Table on page 8 6 if you have not already done so in this MATLAB session Next at the MATLAB prompt type Spacing pow2 xdata ydata errworst fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth errmax spacing 8 13 8 Producing Lookup Table Data 8 14 To find out how many points are in the lookup table type length xdata ans 33 This means that 33 points are required to achievethe worst case error specified by errmax To verify that these points are evenly spaced type widths diff xdata This generates a vector whose entries are the differences between consecutive points in xdata Every entry of widths is 27 To find the maximum error for the lookup table type errworst errworst 3 7209e 004 This is less than the value of errmax To plot the lookup table data along with the errors type fixpt_look1_func_plot xdata ydata funcstr xmin xmax xdt xscale ydt yscale rndmeth This displays the plots shown below Creating Lookup Tables for a Sine Function Figure No 1 olx Eile Edit View Insert Tools Window Help 0S HS RAAS BOR
165. ding a multiplicative adjustment For example if you want 3 bits of additional precision with a corresponding decrease in range the multiplicative adjustment is 2 3 The Slope Additive adjustment parameter allows you to adjust the slope used by Prop by including an additive adjustment An additive slope adjustment is often not needed The most likely use is to set the multiplicative Data Type Propagation 10 56 adjustment to 0 and set the additive adjustment to force the final slope to a specified value TheBias Base parameter list specifies the bias used by Prop for the base data type The parameter values are described below Parameter Value Description Bias1 Bias2 max Bias1 Bias2 min Bias1 Bias2 Bias1 Bias2 Bias1 Bias2 Bias1 Bias2 Bias1 Bias2 The bias of Prop is given by the bias of Refl The bias of Prop is given by the bias of Ref2 The bias of Prop is given by the maximum bias of the reference signals The bias of Prop is given by the minimum bias of the reference signals The bias of Prop is given by the product of the reference signal biases The bias of Prop is given by the ratio of the Refl bias to the Ref2 bias The bias of Prop is given by the sum of the reference biases The bias of Prop is given by the difference of the reference biases The Bias Multiplicative adjustment parameter allows you to adjust the bias used by Prop by including a multiplicative a
166. djustment The Bias Additive adjustment parameter allows you to adjust the bias used by Prop by including an additive adjustment If you want to guarantee that the bias associated with Prop is zero you should configure both the multiplicative adjustment and the additive adjustment to 0 Data Type Propagation If the Propagated scaling parameter i sObtain via best precision then the following dialog box parameters are available to you 2 Propagated scaling Obtain via best precision y 2 1 Values used to determine best precision scaling E 7 Y ou specify any values such as the upper and lower limits on the propagated input for the Values used to determine best precision scaling which constrains the precision chosen to apply tothose limits Based on the data type the scaling will automatically be selected such that these values can be represent with no overflow error and minimum quantization error Characteristics Input Ports Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Yes 10 57 Dead Zone Purpose Library Description Parameters and Dialog Box 10 58 Provide a region of zero output Nonlinear The Dead Zone block is a masked S function that generates zero output within a specified region called its dead zone The lower limit of the dead zone is specified with the Start of dead zone parameter while the upper limit of the dead zone is specified with the End of de
167. ds only on the word size ws 4 11 4 Arithmetic O perations Limitations on Range 4 12 Limitations on the range of a fixed point word occur for the same reason as limitations on its precision Namely fixed point words have limited size In binary arithmetic a processor may need totake an n bit fixed point number and store it in m bits where m n 1Ifm lt n the range of the number has been reduced and an operation can produce an overflow condition Some processors identify this condition as infinity or NaN For other processors especially digital signal processors DSP s the value saturates or wraps If m gt n the range of the number has been extended E xtending the range of a word requires the inclusion of guard bits which act to guard against potential overflow In both cases the range depends on the word s size and scaling The Fixed Point Blockset supports saturation and wrapping for all fixed point data types while guard bits are supported only for fractional data types As shown below you can select saturation or wrapping with the Saturate to max or min when overflows occur check box and you can specify guard bits with the Output data type parameter Block Parameters FixPt Gateway In m Fixed Point Gateway In mask Convert from a Simulink built in data type to a Fixed Point Blockset data type m Parameters Treat input as Real World Value y Dutput data type and scaling Specit
168. e Normally Cancel Help Apply 10 215 Unit Delay With Preview Enabled Characteristics See Also 10 216 Initial condition Initial condition Sample time Sample time Input Port u Any data type supported by the blockset Input Port E Any data type supported by the blockset Output Ports Same as the input u Direct Feedthrough Yes to upper output port No to lower output port Scalar Expansion Yes Unit Delay and related blocks Unit Delay With Preview Enabled Resettable Purpose Library Description Support calculations that have feedback and depend on the current input Delays Holds The Unit Delay With Preview Enabled Resettable block supports calculations that have feedback and depend on the current input The block can reset its state based on an external reset signal R The block has two output ports When the external enable signal E is on and the reset R is false the upper port outputs the signal and the lower port outputs the signal delayed by one sample period The block has two input ports one for the input signal u and the other for the enable signal E When the enable signal E is on and the reset R is true the block resets the current statetothe initial condition given by the Initial condition parameter The block outputs that state delayed by one sample time through the lower output port and outputs the state without a delay through the upper output port When the Enab
169. e To see how the multiplication is actually implemented the three ideal values should be replaced by the general slope bias encoding scheme described in Scaling on page 3 5 4 35 4 Arithmetic O perations 4 36 Thesolution of the resulting equation for the output stored integer Qa is given below FoF _E E E FYB E E FEBb _E E Qa 2 b c 2 bt Q Q b c 2 b Qp c b 2 Q Fa Fa Fa Pl Ba E F The worst case implementation of this equation occurs when the slopes and biases of the input and output signals are mismatched This worst case implementation is permitted in simulation but is not always permitted for code generation since it often requires more resources than is considered practical for an embedded system For code generation and bit true simulations the biases must be zero and the fractional slopes must match for most blocks When these requirements are met the implementation reduces to E E E Qa 2 QQ The bit true implementation of this equation is discussed below Offline Conversions As shown in the previous section no offline conversions are performed Online Conversions and Operations The online conversions and operations for matched slopes and biases of zero are given by these steps 1 Theinteger values Qp and Qe are multiplied together QrawProduct QbQe To maintain the full precision of the product the radix point of QrawpProdud is given by the sum of the radix points of
170. e mismatched If the scaling of these signals is identical matched the number of operations is reduced from the worst most inefficient case F or example when an input has the same fractional slope and bias as the output only step 3 is required Q convert Q Exclusive use of radix point only scaling for both input signals and output signals is acommon way to eliminate the occurrence of mismatched slopes and biases and results in the most efficient simulations and generated code 4 29 4 Arithmetic O perations Rules for Arithmetic Operations 4 30 Fixed point arithmetic refers to how signed or unsigned binary words are operated on Thesimplicity of fixed point arithmeticfunctions such as addition and subtraction allows for cost effective hardware implementations This section describes the blockset specific rules that are followed when arithmetic operations are performed on inputs and parameters These rules are organized into four groups based on the operations involved addition and subtraction multiplication division and shifts F or each of these four groups the rules for performing the specified operation are presented followed by an example using the rules Computational Units The core architecture of many processors contains several computational units including arithmetic logic units ALU s multiply and accumulate units MAC s and shifters These computational units process the binary data directly
171. e Rounding e Logging minimum and maximum simulation values to the workspace e Overflow handling The model used in this example is given by the fxpdemo_db12fix demo You can launch this demo by typing its name at the MATLAB command line fxpdemo_dbl2fix The model is shown below Fe Signal Zero Order Dbl To FixPt1 FixPt to Dbl1 Generator Hold Block Descriptions The Signal Generator block is configured to output a sine wave with an amplitude defined on the interval 5 5 It always outputs double precision numbers The Gateway In block is used as the interface between Simulink and the Fixed Point Blockset Its function is to convert the double precision numbers from the Signal Generator block into one of the Fixed Point Blockset data types For simplicity its output signal is limited to 5 bits in this example 2 10 Example Converting from Doubles to Fixed Point The Gateway Out block is used as the interface between the Fixed Point Blockset and Simulink Its function is to convert one of the Fixed Point Blockset data types into a Simulink data type In this example it outputs double precision numbers The GUI block launches the Fixed Point Blockset Interface tool fxptdlg This tool provides convenient access to the global override and logging parameters the logged minimum and maximum simulation data the automatic scaling script andthe plot interface tool It is not used in this example However if you
172. e as the input Direct Feedthrough Yes Scalar Expansion No Decrement Real World and related blocks Decrement Time To Zero Purpose Library Description max W Ts 0 p Parameters and Dialog Box Characteristics See Also Decrease the real world value of the signal by the sample time but only to zero Math The Decrement Time To Zero block is a masked block that decreases the real world value ofthesignal by thesampletime Ts The output will never go below zero Block Parameters Decrement Time To Zero Fixed Point Decrement Time To Zero mask link Decrease the Real World Value of Signal by the Sample Time Ts but never go below zero Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion No Decrement Real World and related blocks 10 63 Decrement To Zero Purpose Library Description Parameters and Dialog Box Characteristics See Also 10 64 Decreases the real world value of a signal by one but only to zero Math The Decrement To Zero block is a masked block that decreases the real world value of the signal by one The output will never go below zero Block Parameters Decrement To Zero Fixed Point Decrement To Zero mask link Decrease the Real World Value of Signal by 1 0 but never go below zero Cancel Help Apply l Input Port Any data type supported by the blockset Outp
173. e definitions and formulas previously given for IEEE singles and doubles You create nonstandard floating point numbers with the float function float TotalBits ExpBits TotalBits is thetotal word size and ExpBits is the size of the exponent field The size of the fraction field and the bias are calculated from these input arguments You can specify any number of exponent bits up to 11 and any number of total bits such that the fraction field is no more than 53 bits When specifying a nonstandard format you should remember that the number of exponent bits largely determines the range of the result and the number of fraction bits largely determines the precision of the result Note These numbers are normalized with a hidden leading one for all exponents except the smallest possible exponent However the largest possible exponent might not be treated as a flag for infinity or NaNs Range and Precision Therange of a number gives the limits of the representation whilethe precision gives the distance between successive numbers in the representation The range and precision of an IEEE floating point number depend on the specific format Range The range of representable numbers for an IEEE floating point number with f bits allocated for the fraction ebits allocated for the exponent and the bias of egiven by bias 2 1 1 is given below E all E lt negative numbers lt gt lt gt positive numbers
174. e distance from 1 0 to the next largest floating point number For a computer that supports the IEEE Standard 754 eps 2 2 or 2 2204 5108 3 21 3 Data Types and Scaling Floating Point Data Type Parameters The high and low limits exponent bias and precision for the supported floating point data types are given below Table 3 4 Floating Point Data Type Parameters Data Type single double nonstandard Low Limit High Limit Exponent Precision Bias 2 126 19 38 2128 3 1938 127 2 23 10 7 2 1022 2 10 308 21024 2 19308 1023 2 52 10 16 9 1 bias DE pbias 2 71_1 2 f 3 22 Due tothe sign magnitude representation of floating point numbers there are two representations of zero one positive and one negative For both representations e 0 and 0 f 0 0 Exceptional Arithmetic In addition to specifying a floating point format the IEEE Standard 754 specifies practices and procedures so that predictable results are produced independent of the hardware platform Specifically denormalized numbers infinity and NaNs are defined to deal with exceptional arithmetic underflow and overflow If an underflow or overflow is handled as infinity or NaN then significant processor overhead is required to deal with this exception Although the IEEE Standard 754 specifies practices and procedures to deal with exceptional arithmetic conditions in a consistent manner microprocessor manufacturers may handle th
175. e override for an entire model or an individual block Simulink Model of a Feedback Design Simulink Model of a Feedback Design Reference You can run the Simulink model of the feedback design by launching the MATLAB Demo browser and selecting the Scaling a Fixed Point Control Design demo You can launch the browser by typing demo blockset Fixed Point at the command line or by opening the Demos block found in the Fixed Point Blockset library Alternatively you can access the model directly by typing its name at the command line fxpdemo_feedback The MDL file automatically runs the M file preload_feedback which populates the workspace with the required parameter values The feedback design model is shown below Plant Input pnum s pden s Plant Output FixPt GUI Analog Plant Analog to Digital Controller Digital to Analog Interface Interface Digital Controller Software on Fixed Point Processor The model consists of these blocks e Reference Simulink s Signal Generator block generates a continuous time reference signal It is configured to output a square wave 6 3 6 Tutorial Feedback Controller Simulation 6 4 ZOH Simulink s Zero Order Hold block samples and holds the continuous signal This block is configured so that it quantizes the signal in time by an amount tsamp 0 01 second Analog to Digital Interface The a
176. e scaling from another block Refer to Selecting the Output Scaling on page 2 5 for more information Floating Point Numbers The Fixed Point Blockset supports single precision and double precision floating point numbers as defined by the IEEE Standard An O verview of Blockset Features 754 1985 for Binary Floating Point Arithmetic You specify floating point numbers with the float function For example to configure the output as a single precision floating point number via the block dialog box you specify the Output data type parameter tobe float single Toconfigurea double precision floating point number you specify Output data type to be float double You can also specify a nonstandard floating point number that mimics the IEEE style For this data type the fraction mantissa can range from 1 to 52 bits and the exponent can range from 1 to 11 bits For example to configurea nonstandard floating point number having 32 total bits and 9 exponents bits you specify Output data type to be float 32 9 Note These numbers are normalized with a hidden leading 1 for all exponents except the smallest possible exponent H owever the largest possible exponent might not be treated as a flag for infinity or NaNs Selecting the O utput Scaling Most data types supported by the Fixed Point Blockset have a default scaling that you cannot change However for generalized fixed point data types you have the option of specifying t
177. e stored integer to one Perform the specified bitwise operation on the inputs Calculus Accumulator Accumulator Resettable Accumulator Resettable Limited Derivative Difference Integrator Backward Integrator Backward Resettable Integrator Backward Resettable Limited Integrator F orward Integrator Forward Resettable Compute a cumulative sum Compute a cumulative sum with external Boolean reset Compute a limited cumulative sum with external Boolean reset Compute a discrete time derivative Calculate the change in a signal over one time step Perform discrete time integration of a signal using the backward method Perform discrete time integration of a signal using the backward method with external Boolean reset Perform discrete time limited integration of a signal using the backward method with external Boolean reset Perform discrete time integration of a signal using the forward method Perform discrete time integration of a signal using the forward method with external Boolean reset 10 13 10 Block Reference 10 14 Calculus Integrator Forward Resettable Limited Integrator Trapezoidal Integrator Trapezoidal Resettable Integrator Trapezoidal Resettable Limited Sample Time Multiply Perform discrete time limited integration of a signal using the forward method with external Boolean reset Perform discrete time integration of a signal u
178. e time between samples with the Sample time parameter A setting of 1 means the Sample time is inherited Block Parameters Unit Delay Resettable External IC Fixed Point Unit Delay Resettable External Initial Condition mask link Normally the output is the signal u delayed by one sample period When the reset signal R is true the state and the output are always set equal to the initial condition signal IC This reset action is vectorized and supports scalar expansion Parameters Sample time ee Cancel Help Enpi Sample Time Sample time Input Port u Any data type supported by the blockset Input Port R Any data type supported by the blockset Input Port IC Same as the input u Output Port Same as the input u 10 213 Unit Delay Resettable External IC See Also 10 214 Direct Feedthrough No of the input port Yes of the reset port Yes of the external IC port Sample Time Inherited Scalar Expansion Yes Unit Delay and related blocks Unit Delay With Preview Enabled Purpose Library Description Parameters and Dialog Box Support calculations that have feedback and depend on the current input Delays Holds The Unit Delay With Preview Enabled block supports calculations that have feedback and depend on the current input The block has two output ports When the external enable signal E is on the upper port outputs the signal and the lower port outputs the signal delayed by one
179. ec2 0 andthe Initial condition parameter as ic1 ic2 Input Ports Any data type supported by the blockset it must be a scalar Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of initial conditions Vectorized No Purpose Description gt Multiply the input by a constant The Gain block is a masked S function that multiplies the input by a constant value referred to as the gain To multiply the input by a constant matrix use the Matrix Gain block Y ou specify the gain with the Gain value parameter The gain can be a scalar or a vector Y ou specify the scaling for the gain with the Parameter scaling parameter Note that there aretwo dialog box parameters that control the gain scaling one associated with an edit field and one associated with a parameter list If Parameter data type is a generalized fixed point number such as sfix 16 the Parameter scaling list provides you with these scaling modes e Use Specified Scaling This mode uses the slope bias or radix point only scaling specified for the editable Parameter scaling parameter for example 2 10 e Best Precision Element wise This mode produces radix points such that the precision is maximized for each element of the Gain value vector e Best Precision Vector wise This mode produces a common radix point for each element of the Gain value vector based on the best precision for the largest value of the vector
180. ed Scaling for Speed In the process of finding the scaling of the sum one reasonable goal is to simplify the calculations Simplifying the calculations should reduce the number of operations thereby increasing execution speed The following choices can help to minimize the number of arithmetic operations e Set Ba Bp B This eliminates one addition e Set Fa Fpor Fa F Either choice eliminates one of the two constant times variable multiplies The resulting formula is E E Fo E E Qa 2 GER Q or Fp E E EE Qa po Qpt 2 Q These equations appear to be equivalent However your choice of rounding and precision may make one choice stand out over the other To further simplify matters you could choose E E or Ez Ep This will eliminate some bit shifting Inherited Scaling for Maximum Precision In the process of finding the scaling of the sum one reasonable goal is maximum precision The maximum precision scaling can be determined if the range of the variable is known As shown in Example Maximizing Precision on page 4 11 the range of a fixed point operation can be determined from max Va and mi n Va For a summation the range can be determined from 4 17 4 Arithmetic O perations 4 18 min Va min V min V max V max Vp max V The maximum precision slope can now be derived max V 2 min V 2 2 1 aida i E F 2 WS D F 2 2 a In most cases the input and out
181. ed fixed point output 10 101 Gateway In Example 10 102 Round toward Rounding mode for fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace This example uses the Gateway In block to help you understand the difference between a real world value and a stored integer Consider the two fixed point models shown below Constant Gateway In Gateway Out Constanti Gateway In1 Gateway Out2 Gateway Out3 In the top model the Gateway In block treats the input as a real world value and maps that value to an 8 bit signed generalized fixed point data type with a scaling of 2 If the value is output from the Gateway Out block as a Gateway In real world value then the scaling and data type information is retained and the output value is 001111 00 or 15 If the value is output from the Gateway Out block as a stored integer then the scaling and data type information is not retained and the stored integer is interpreted as 00111100 or 60 In the bottom model the Gateway In block treats the input as a stored integer and the data type and scaling information is not applied If the valueis output from the Gateway Out block as a real world value t
182. efine a 16 bit unsigned generalized fixed point data type a ufix 16 a Class FIX IsSigned 0 MantBits 16 See Also float sfix sfrac sint ufrac uint 9 35 ufrac Purpose Syntax Description Example See Also 9 36 Create a MATLAB structure describing an unsigned fractional data type a ufrac TotalBits a ufrac TotalBits GuardBits ufrac TotalBits returns a MATLAB structure that describes the data type of an unsigned fractional number with a word size given by TotalBits ufrac TotalBits GuardBits returns a MATLAB structure that describes the data type of an unsigned fractional number The total word size is given by TotalBits with GuardBits bits located to the left of the radix point ufrac is automatically called when an unsigned fractional data type is specified in a block dialog box The default radix point for this data type is assumed to lie immediately to the left of all bits If guard bits are specified then they lie to the left the default radix point Define an 8 bit unsigned fractional data type with 4 guard bits Note that the range of this number is from 0 to 1 2 8 24 15 9375 a ufrac 8 4 a Class FRAC IsSigned MantBits GuardBits Boo float sfix sfrac sint ufix uint uint Purpose Syntax Description Example See Also Create a MATLAB structure describing an unsigned integer data type a uint TotalBits uint TotalBits returns a MATLA
183. ely Fractionals The default radix point for unsigned fractional data types is just to the left of the MSB while for signed fractionals the radix point is just to the right of the MSB If you specify guard bits then they lie to the left of the radix point You specify unsigned and signed fractional numbers with the ufrac and sfrac functions respectively Generalized Fixed Point Numbers For signed and unsigned generalized fixed point numbers there is no default radix point Y ou specify unsigned and signed generalized fixed point numbers with the ufix and sfix functions respectively Fixed Point N umbers Scaling The dynamic range of fixed point numbers is much less than that of floating point numbers with equivalent word sizes To avoid overflow conditions and minimize quantization errors fixed point numbers must be scaled With the Fixed Point Blockset you can select a fixed point data type whose scaling is defined by its default radix point or you can select a generalized fixed point data type and choose an arbitrary linear scaling that suits your needs This section presents the scaling choices available for generalized fixed point data types A fixed point number can be represented by a general slope bias encoding scheme V V SQ B where e Vis an arbitrarily precise real world value e Vis the approximate real world value e Qisan integer that encodes V e S F 25 is the slope e B is the bias The slope is
184. en spacing you use a binary search method that loops up to log2 N times With even and power of two spacing you can determine the location with the execution of one line of C code But you cannot decide the relative advantages of power of two versus evenly spaced without detailed knowledge of the hardware and the C compiler The effort of calculating the interpolation favors the power of two case which uses a bitwise AND operation and a shift to replace a subtraction anda division The amount of advantage provided by this depends on the specific hardware but you would expect an advantage in code size speed and also in accuracy The evenly space case calculates the interpolation with a minor improvement in efficiency over the unevenly spaced case Function Reference 9 Function Reference 9 2 Overview This chapter contains reference pages for the Fixed Point Blockset M file functions In some cases you will not call these functions from the MATLAB command line nstead they are automatically called when you specify certain parameter values via block dialog boxes or via the Fixed Point Blockset Interface tool The functions are listed below Table 9 1 Fixed Point Blockset Functions Function Description autofixexp Automatically change the scaling for each fixed point block that does not have its scaling locked fixptbestexp Determine the exponent that gives the best precision fixed point representation of a va
185. en you manually specify the scaling via the Propagated scaling edit field Refer to Selecting the Scaling on page 10 6 to learn how to specify the scaling If the parameter list is configured as Inherit via propagation rule then you must use the parameters described in Inheriting Scaling Information on page 10 54 10 49 Data Type Propagation Remarks 10 50 After you use the information from the reference signals you can apply a second level of adjustments to the data type and scaling by using individual multiplicative and additive adjustments This flexibility has a variety of uses For example if you are targeting a DSP then you can configure the block so that the number of bits associated with a MAC multiply and accumulate operation is twice as wide as the input signal and has a certain number of guard bits added to it The Data Type Propagation block also provides a mechanism to force the computed number of bits to a useful value For example if you are targeting a 16 bit micro then the target C compiler is likely to support sizes of only 8 bits 16 bits and 32 bits The block will force these three choices to be used F or example suppose the block computes a data type size of 24 bits Since 24 bits is not directly usable by the target chip the signal is forced up to 32 bits which is natively supported Thereis alsoa method for dealing with floating point reference signals This makes it easier to create des
186. enerate pure integer code for a fixed point Fixed Point Code digital controller The Double to Fixed Point Conversion demo is discussed in Example Converting from Doubles to Fixed Point on page 2 10 while the Scaling a Fixed Point Control Design demo is the subject of Chapter 6 Tutorial Feedback Controller Simulation Advanced Demos Filters and Systems Thefilter and system demos are intended to be used as a design aid so you can see how to build and test filters and systems suited to your particular needs The output of these demos is compared to the output of analogous built in Simulink blocks with identical input Y ou can access the filter and system demos through the Filters amp Systems Examples block which is included with the Fixed Point Blockset library Alternatively you can type fixptsys at the MATLAB command line The advanced demos are listed below Table 2 2 Advanced Fixed Point Blockset Demos Demo Name Description Fixed Point Compare output from the Integrator Trapezoidal Integrators Integrator Backward and Integrator Forward blocks to output from Simulink s Discrete ntegrator block Fixed Point Compare output from the Derivative and Derivative Derivatives Filtered realizations to output from the Simulink derivatives built using the Discrete Filter and Transfer Fn blocks Demos Table 2 2 Advanced Fixed Point Blockset Demos Continued Demo Name Description Fixe
187. ent in the output vector If no value matches the block s input then the block performs linear interpolation between the two appropriate elements of the table to determine an output value If the block input is less than the first or greater than the last input vector element then the block extrapolates using the first two or last two points e Interpolation Use End Values This method performs linear interpolation as described above but does not extrapolate outside the end points of the input vector Instead the end point values are used e Use Input Nearest This method does not interpolate or extrapolate Instead the element in x nearest the current input is found The corresponding element in y is then used as the output e Use Input Below This method does not interpolate or extrapolate Instead the element in x nearest and below the current input is found The 10 141 Look Up Table Remarks Parameters and Dialog Box 10 142 corresponding element in y is then used as the output If there is no element in x below the current input then the nearest element is found e Use Input Above This method does not interpolate or extrapolate Instead the element in x nearest and above the current input is found The corresponding element in y is then used as the output If there is no element in x above the current input then the nearest element is found For a detailed description of all other block parameters refer t
188. er of inputs can be supplied instead of multiply divide characters e If only one vector is input then a single or will collapse the vector using the specified operation For a detailed description of all other block parameters refer to Block Parameters on page 10 4 The Math library contains the following implementations which areall linked to the Product block but have different parameter settings e Multiply e Divide e Product of Elements e Product of Elements Inverted e Multiply Matrix Product Parameters and Dialog Box Block Parameters Product r Fixed Point Product mask link Multiply or divide inputs Specify one of the following a 4 or for each input b The number of inputs if only multiplication is desired c A single or to collapse a vector m Parameters Enter characters or the number of inputs F al Dutput data type and scaling Specity viados y Output data type ex sfix 16 uint 8 float single fe Output scaling Slope or Slope Bias ex 2 9 pmo I Lock output scaling so autoscaling tool can t change it Round toward Floor X T Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Multiplication Element wise Z Enter characters or the number of inputs Enter as many multiply or divide characters as there are inputs For multiplication only you can ente
189. eration Gain Value Binary Value Decimal Value N A original number 2 00110 101 6 625 Shift left by 2 bits 4 11010 100 26 5 Shift right by 2 bits 0 25 00001 101 1 625 Rules for Arithmetic O perations The figure below shows the fixed point model used to generate the above data F ufix8 En3 double V FixPt FixPt Display Gain Gateway Out Shift bits two places to the left but leave radix point unchanged 6 625 ufix8_En3 E FixPt Constant F ufix8_En3 double 1 625 Vv FixPt FixPt Display1 Gain1 Gateway Out1 Shift bits two places to the right but leave radix point unchanged Refer to Chapter 10 Block Reference for more information about the Gain block 4 Arithmetic O perations Example Conversions and Arithmetic Operations 4 46 This example uses the FIR block to illustrate when parameters are converted from a double to a fixed point number when the input data type is converted to the output data type and when the rules for addition and subtraction and multiplication are applied For details about conversions and operations refer to Parameter and Signal Conversions on page 4 26 and Rules for Arithmetic Operations on page 4 30 Note If a block can perform all four arithmetic operations such as the FIR block then the rules for multiplication and division are applied first Suppose you configure the FIR block for two outputs SIMO mode where the first output is given
190. erits the scaling of the input signal Other blocks require that you specify the output scaling with the Output scaling parameter Still other blocks provide you with the option of inheriting the output scaling and data type information from a driving block or specifying the scaling For the latter case you control how the output scaling and data type is specified with the Output data type and scaling parameter list This list supports three choices Specify via dialog Inherit via internal rule and Inherit via back propagation Note that some fixed point blocks support only two of the three choices If you select Specify via dialog you must explicitly specify the output scaling with the Output scaling parameter If you select Inherit via internal rule theoutput scaling is inherited from the input s If you select Inherit via back propagation the output scaling is inherited by back propagation typically from the Data Type Propagation block F or information about theinheritancerules refer tothe description in Selecting the Data Type on page 10 4 10 7 10 Block Reference The supported scaling modes for generalized fixed point data types are given below Default scaling is used for all other fixed point data types Table 10 2 Scaling Modes for Generalized Fixed Point Data Types Scaling mode Description Radix point only Specify radix point only powers of two scaling For example a scaling of 27 10 or pow2
191. erved for flagging infinity NaN and denormalized numbers sothetrue exponent values range from 126 to 127 Floating Point N umbers Single Precision Format ThelEEE single precision floating point format is a 32 bit word divided into a 1 bit sign indicator s an 8 bit biased exponent e and a 23 bit fraction f A representation of this format is given below b31 b30 b22 bo S e f The relationship between this format and the representation of real numbers is given by CDS o gt 127 value 4 1 22 928 0 f denormalized e 0 f gt 0 1 f normalized O lt e lt 255 exceptional value otherwise Denormalized values are discussed in Exceptional Arithmetic on page 3 22 Double Precision Format ThelEEE double precision floating point format is a 64 bit word divided into a 1 bit sign indicator s an 11 bit biased exponent e and a 52 bit fraction f A representation of this format is given below b63 De bs1 Do S e f The relationship between this format and the representation of real numbers is given by iy 2 203 1 f normalized 0 lt e lt 2047 value 31 22 102 gf denormalized e 0 f gt 0 exceptional value otherwise Denormalized values are discussed in Exceptional Arithmetic on page 3 22 3 19 3 Data Types and Scaling 3 20 Nonstandard IEEE Format The Fixed Point Blockset supports a nonstandard I EEE style floating point data type This data type adheres to th
192. es to upper output port No to lower output port Scalar Expansion Yes Unit Delay and related blocks 10 223 Unit Delay With Preview Resettable External RV Purpose Library Description 10 224 Support calculations that have feedback and depend on the current input Delays Holds The Unit Delay With Preview Resettable External RV block supports calculations that have feedback and depend on the current input The block can reset its state based on an external reset signal R The block has two output ports When the external reset R is false the upper port outputs the signal and the lower port outputs the signal delayed by one sample period When the external reset R is true the upper output signal is forced to equal the external reset signal RV Thelower output signal is not affected until onetime step later at which time it is equal to the external reset signal RV at the previous timestep The block uses theinternal Initial condition only when the model starts or when a parent enabled subsystem is used The internal Initial condition only affects the lower output signal The first output is only affected through feedback Theinput u and initial condition IC must be the same data type but can be any data type The output is the same data type as the inputs u and IC The reset R can be any data type Y ou specify the time between samples with the Sample time parameter A setting of 1 means the Sample time is inheri
193. ese conditions in ways that depart from the standard Some of the alternative approaches such as saturation and wrapping are discussed in Chapter 4 Arithmetic Operations Denormalized N umbers Denormalized numbers are used to handle cases of exponent underflow When the exponent of the result is too small i e a negative exponent with too large a magnitude the result is denormalized by right shifting the fraction and leaving the exponent at its minimum value The use of denormalized numbers is also referred to as gradual underflow Without denormalized numbers the Floating Point N umbers gap between the smallest representable nonzero number and zero is much wider than the gap between the smallest representable nonzero number and the next larger number Gradual underflow fills that gap and reduces the impact of exponent underflow to a level comparable with round off among the normalized numbers Thus denormalized numbers provide extended range for small numbers at the expense of precision Infinity Arithmetic involving infinity is treated as the limiting case of real arithmetic with infinite values defined as those outside the range of representable numbers or lt representable numbers lt With the exception of the special cases discussed below NaNs any arithmetic operation involving infinity yields infinity Infinity is reoresented by the largest biased exponent allowed by the format and a fraction of zero
194. esents the FIR denominator coefficients The first summation in y k represents multiplication and accumulation of the most recent inputs and numerator coefficients in the accumulator The second summation in y k represents multiplication and accumulation of the most recent inputs and denominator coefficients in the accumulator Since the FIR coefficients inputs and outputs are all represented by 16 bit numbers the base data type any multiplication involving these numbers produces a 32 bit output the accumulator data type Simulation Results Simulation Results Using Simulink and the Fixed Point Blockset you can easily transition from a digital controller described in the ideal world of double precision numbers to one realized in the world of fixed point numbers Thesimulation approach used in this tutorial follows these steps 1 Takean initial guess at the scaling For this tutorial an initial proof of concept simulation using a reasonable guess at the fixed point word size and scaling is the first step in simulating the digital controller This step is included only to illustrate how difficult it is to guess the best scaling 2 Perform a global override of the fixed point data types and scaling using double precision numbers The maximum and minimum simulation values for each digital controller block are logged to the workspace 3 Usethe automatic scaling procedure This procedure uses the doubles simulation values previ
195. esults A close up of the plant output signal is shown below Note that a steady state has been achieved but a small limit cycle is present in the steady state dueto poor A D design Plotting fxpdemo_feedback outputs of x 2 5 2 4 2 3 2 2 e Limitcyclesproduced by the A2D block As shown below the scaling of the A2D did not change because it was locked Block Parameters A2D r Fixed Point Gateway In mask link Convert from a Simulink built in data type to a Fixed Point Blockset data type y Parameters Treat input as Real World Value y Dutput data type and scaling Specity via dialog Output data type ex sfix 16 uint 8 float single ff Output scaling Slope or Slope Bias ex 2 9 4 FM Lock output scaling so autoscaling tool can t changeit Scaling is unchanged by Round toward Nearest y the autoscaling script IV Saturate to max or min when overflows occur FF Override data type s with doubles Iv Log minimums and maximums j Cancel Help Apply 6 17 6 Tutorial Feedback Controller Simulation Simulation 4 Individual Override Theprevious simulation optimized results for the fixed point digital controller In this simulation the A2D block is configured so that it feeds the digital controller with doubles This represents overriding the A D hardware constraints and is accomplished by checking the Override with doubles
196. esults of the current implementation step 3 There is no specific modeling approach For example models may be obtained from first principles such as equations of motion or froma frequency response such as a sine sweep There are many controllers that meet the same frequency domain or time domain specifications Additionally for each controller there are an infinite number of realizations The Fixed Point Blockset helps expedite the design cycle by allowing you to simulate the effects of various fixed point controller digital filter structures Compatibility with Simulink Blocks Compatibility with Simulink Blocks Y ou can connect Simulink blocks directly to Fixed Point Blockset blocks provided the signals use built in Simulink data types The built in data types include uint8 uint16 uint32 int8 int16 int32 single double and boolean TheFixed Point Blockset supports all built in data types However a fixed point signal consisting of 8 16 or 32 bit integers is compatible with Simulink only when its scaling is given by a slope of 1 and a bias of 0 Some Simulink blocks impose restrictions on the data type of the signals they can handle For example some blocks accept only doubles Toincorporate these blocks into your fixed point model you must configure the driving block s to use doubles Some Simulink blocks can accept signals of any data type For these blocks you can input any of the built in data types or any of the blo
197. ettable mask link Normally the output is the signal u delayed by one sample period When the reset signal A is true the state and the output are always set equal to the initial condition parameter This reset action is vectorized and supports scalar expansion When the enable signal is false the block is disabled and the state and output values do not change except for resets The enable action is vectorized and supports scalar expansion Parameters Initial condition A Sample time Oe Cancel Help Apply Initial Condition The initial output of the simulation Unit Delay Enabled Resettable Sample Time Sample time Characteristics Input Port u Any data type supported by the blockset Input Port E Any data type supported by the blockset Input Port R Any data type supported by the blockset Output Port Same as the input u Direct Feedthrough No of the input port No of the enable port Yes of the reset port Scalar Expansion Yes See Also Unit Delay and related blocks 10 207 Unit Delay Enabled Resettable External IC Purpose Library Description Parameters and Dialog Box 10 208 Delay a signal one sample period if the enable is on Delays amp Holds The Unit Delay Enabled Resettable External IC block combines the features of the Unit Delay Enabled Unit Delay External IC and Unit Delay Resettable blocks The block can reset its state based on an external reset signal R
198. eway Out mask link Convert from a Fixed Point Blockset data type to a Simulink built in data type The conversion has two possible goals One goal is to have the Real World Values of the input and the output be equal The other goal is to have the Stored Integer Values of the input and the output be equal Overflows and quantization errors can prevent the goal from being fully achieved The input supports all built in and fixed point data types The output supports all built in datatypes Parameters 7 N Input and Output to have equal PLN Dutput data type Round toward Floor hd I Saturate to max or min when overflows occur T Log minimums and maximums Cancel Help Apply 10 108 Gateway Out Characteristics See Also Output and Input to have equal Specify the type of value the input and output are to have equal Output data type Any built in data type supported by Simulink Round toward Rounding mode for fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Log minimums and maximums If checked minimum and maximum simulation values are logged tothe workspace Input Ports Any data type supported by the blockset Output Port Any built in Simulink data type Direct Feedthrough Yes Scalar Expansion N A Gateway In and related blocks 10 109 Increment Real World Purpose Library
199. f an IEEE double 64 total bits 11 exponent bits float TotalBits ExpBits returns a MATLAB structure that describes a nonstandard floating point data type that mimics the IEEE style That is the numbers are normalized with a hidden leading one for all exponents except the smallest possible exponent However the largest possible exponent might not be treated as a flag for Inf s and NaN s float is automatically called when a floating point number is specified in a block dialog box Note Unlike fixed point numbers floating point numbers are not subject to any specified scaling Define a nonstandard EEE style floating point data type with 31 total bits excluding the hidden leading one and 9 exponent bits a float 31 9 a Class FLOAT MantBits 21 ExpBits 9 sfix sfrac sint ufix ufrac uint 9 25 fpupdate Purpose Syntax Description 9 26 U pdate obsolete fixed point blocks from previous Fixed Point Blockset releases to current fixed point blocks fpupdate model fpupdate model blkprompt fpupdate model blkprompt varprompt fpupdate model blkprompt varprompt muxprompt fpupdate model blkprompt varprompt muxprompt message fpupdate model replaces all obsolete fixed point blocks contained in model with current fixed point blocks The model must be opened prior to calling fpupdate fpupdate model blkprompt prompts you for replacement of obsolete blocks If b1kprompt
200. f these methods selected from the Method parameter list e Interpolation Extrapolation This is the default method it performs linear interpolation and extrapolation of the inputs If theinputs match row and column parameter values the output is the value at the intersection of the row and column Ifthe inputs do not match row and column parameter values then the block generates output by linearly interpolating between the appropriate row and column values If either or both block inputs are less than thefirst or greater than the last row or column values the block extrapolates from the first two or last two points Interpolation Use End Values This method performs linear interpolation as described above but does not extrapolate outside the end points of the input vector Instead the end point values are used Use Input Nearest This method does not interpolate or extrapolate Instead the elements in x and y nearest the current inputs are found The corresponding element in z is then used as the output Use Input Below This method does not interpolate or extrapolate Instead the elements in x and y nearest and below the current inputs are found The corresponding element in z is then used as the output If there are no elements in x or y below the current inputs then the nearest elements are found Look Up Table 2D Remarks Parameters and Dialog Box e Use Input Above This method does not interpolate or extr
201. f thesignal by one Increase the stored integer value of a signal by one Multiply the input by a constant matrix Determine the minimum or maximum input value Determine the minimum or maximum of a signal over time Multiply or divide inputs Add or subract inputs Negate the input 10 19 10 Block Reference 10 20 Nonlinear Blocks Dead Zone Dead Zone Dynamic Rate Limiter Rate Limiter Dynamic Relay Saturation Saturation Dynamic Provide a region of zero output Set the input within the bounds to zero Limit the rising and falling rates of the signal Limit the rising and falling rates of the signal Switch output between two constants Bound the range of the input Bound the range of the input Sign Indicate the sign of the input Wrap To Zero Set output to zero if input is above threshold Select MultiPort Switch Switch Switch output between different inputs based on the value of the first input Switch output between the first input and the third input based on the value of the second input The Fixed Point Blockset Libraries Sources Constant Counter Free Counter Limited Repeating Sequence Interpolated Repeating Sequence Stair Generate a constant value Count up and overflow back to zero after the maximum value possible is reached for the specified number of bits Count up and wrap back to zero after outputting the specified upper limit
202. fix function Nearest This mode rounds toward the nearest representable number with the exact midpoint rounded toward positive infinity Rounding toward nearest is equivalent to MATLAB s round function Ceiling This mode rounds toward positive infinity and is equivalent to MATLAB ceil function e Floor This mode rounds toward negative infinity and is equivalent to MATLAB s floor function Overflow Handling You control how overflow conditions are handled for fixed point operations with the Saturate to max or min when overflows occur check box If checked then overflows saturate to either the maximum or minimum value represented by the data type For example an overflow associated with a signed 8 bit integer can saturate to 128 or 127 If unchecked then overflows wrap to the appropriate value that is representable by the data type F or example the number 130 does not fit in a signed 8 bit integer and would wrap to 126 Locking the Output Scaling If the output data type is a generalized fixed point number then you have the option of locking its scaling by checking the Lock output scaling so autoscaling tool can t change it check box When locked the automatic scaling script autofixexp will not change the output scaling Otherwise the autofixexp is free to adjust the scaling Overriding with Doubles By checking the Override data type s with doubles check box you can override any data type with doubles This featu
203. fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth nptsmax xdata ydata errworst fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth errmax nptsmax xdata ydata errworst fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth errmax nptsmax spacing fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth errmax optimizes the breakpoints of a lookup table over a specified range The lookup table satisfies the maximum acceptable error maximum number of points and spacing requirements given by the optional parameters The breakpoints refer to the x values of the lookup table The command xdata ydata errworst fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth errmax returnstheX and Y coordinates of the lookup table as vectors xdata and ydata respectively It also returns the maximum absolute error of the lookup table as a variable errworst The fixed point approximation is found by interpolating between the lookup table data points The required input parameters are as follows Input Value funcstr Function of x funcstr is the function for which breakpoints are approximated xmin Minimum value of x xmax Maximum value of x xdt Data type of x fix pt_look1_func_approx Input Value xscale Scaling for the x values ydt Data type of y yscale Scaling for the y values rndmeth Rounding
204. fy the real time implementation of a control law or digital filter and floating point numbers can effectively approximate real world numbers then why usea microcontroller or processor with fixed point hardware support The answer to this question in many cases is cost and size e Cost Fixed point hardware is more cost effective where price cost is an important consideration When using digital hardware in a product especially mass produced products fixed point hardware costing much less than floating point hardware can result in significant savings Size The logic circuits of fixed point hardware are much less complicated than those of floating point hardware This means the fixed point chip size is smaller with less power consumption when compared with floating point hardware For example consider a portable telephone where one of the product design goals is to make it as portable small and light as possible If one of today s high end floating point general purpose processors is used a large heat sink and battery would also be needed resulting in a costly large and heavy portable phone After making the decision to use fixed point hardware the next step is to choose a method for implementing the dynamic system for example control system or digital filter Floating point software emulation libraries are generally ruled out because of timing or memory size constraints Therefore you are left with fixed point math where binary
205. g Box Implement a time varying Direct Form I realization of a filter Filters The Filter Direct Form Time Varying block implements a Direct Form realization of the specified filter The block only supports single input single output filters The block automatically selects the data types and scalings of the output the coefficients and any temporary variables Block Parameters Filter Direct Form Time Yarying r Fixed Point Filter Direct Form Time Varying mask link A Direct Form realization of the specified filter is used Only single input single output filters are supported The data types and scalings of the output the coefficients and any temporary variables are automatically selected The automatic choices will be acceptable in many situations In situations where the automatic choices give unacceptable results manual layout of the filter is necessary For manual layout it is suggest that the blocks under this mask be used as a starting point Note 1 The full denominator should have a leading coefficient of 1 0 but this leading coefficient should be excluded when entering the parameter For example if the denominator is den 1 1 7 0 72 just enter den 2 end 1 7 0 72 Note 2 The numerator does NOT need to be the same size as the full denominator Parameters Initial condition for previous output joo Initial condition for previous input AAA Round toward Floor ha I Satura
206. gers and any floating point data type 10 171 Relational Operator Pa ra meters Block Parameters Relational Operator and Dia log Box Fixed Point Relational Operator mask link Perform the specified relational operation on the inputs The output data type should represent zero exactly Parameters occ A Logical output data type ex uint 8 sint 32 A Cancel Help Apply Operator Relational operator used to compare the two inputs Logical output data type Output data type You should only use data types that can represent zero exactly Conversions Theinput with the smallest positive range is converted to the data type of the other input offline using round to nearest and saturation This conversion is performed prior to comparison Refer to Parameter Conversions on page 4 27 for more information about parameter conversions Characteristics Input Port Any data type supported by the blockset Output Port Any data type supported by the blockset that can exactly represent zero Direct Feedthrough Yes Scalar Expansion Of inputs 10 172 Relay Purpose Library Description A Switch output between two constants Nonlinear The Relay block is a masked S function that allows the output to switch between two specified values When the relay is on it remains on until the input drops below the value of the Switch off point parameter When therelay is off it remains off until the
207. global and stack RAM is used When the lookup table has even power of two spacing division is replaced by a bit shift As a result the execution speed is faster than for evenly spaced data See the chapter Chapter 8 Producing Lookup Table Data for a tutorial on using fixpt_look1_func_approx fix pt_look1_func_approx The following table summarizes the effect of spacing on the execution speed error and memory used Table 9 2 Comparison of the Spacing Options Parameter Execution Speed Error ROM Usage RAM Usage Even Power of Two Spaced Data The execution speed is the fastest The position search and interpolation are the same as for evenly spaced data H owever to increase the speed more the position search is replaced by a bit shift and the interpolation is replaced with a bit mask The error can be larger than that for unevenly spaced data because approximating a function with nonuniform curvature requires more points to achieve the same accuracy Uses less command ROM but more data ROM Not significant Evenly Spaced Data The execution speed is faster then that for unevenly spaced data because the position search is faster and the interpolation requires a simple division The error can be larger than that for unevenly spaced data because approximating a function with nonuniform curvature requires more points to achieve the same accuracy Uses less command R
208. half of the first bit corresponds to temperatures real world values greater than zero 1 Introduction The quantization error is 25 33 K bit lt Error lt 25 33 K bit The range of interest of the quantized conversion and the absolute value of the quantized error are shown below Visualization of Quantized Conversion 400 Es T E T T T Quantized Value Q 1 1 1 1 1 1 240 260 280 300 320 340 360 380 Real World Value V K S o T to wo o o T Quantization Error K bit 3 T o 240 260 280 300 320 340 360 380 Real World Value V K As an alternative to the purely linear conversion consider the general linear conversion with maximum precision V HK z 222K Q 222 K 0 5 AAA Physical Q uantities and M easurement Scales The quantized conversion and range of interest are shown below Visualization of Quantized Conversion Quantized Value Q 19 75 K bit with Bias 231 875 K V 222 V 380 K 0 50 100 The quantization error is 9 875 K bit lt Error lt 9 875 K bit which is approximately 2 5 times smaller than the error associated with the purely linear conversion 150 200 250 Real World Value V K 300 350 400 1 Introduction Therange of interest of the quantized conversion and the absolute value of the quantized error are shown below Visualization of Quantized Conversion 400 ie T T T T T
209. he CPU In either case storing the value as an accumulator data type is not much more costly than storing it as a base data type Targeting an Embedded Processor Design Rule 4 Summation Can Use the Accumulator Data Type Addition and subtraction can use the accumulator data type if there is justification The typical justification is reducing the buildup of errors due to round off or overflow For example a common filter operation is a weighted sum of several variables Multiplying a variable by a weight will naturally produce a product of the accumulator type Before summing each product could be converted back to the base data type This approach introduces round off error into each part of the sum Alternatively the products can be summed using the accumulator data type and the final sum can be converted to the base data type Round off error is introduced in just one point and the precision will generally be better The cost of doing an addition or subtraction using accumulator type numbers is slightly more expensive but if there is justification it is usually worth the cost 7 Building Systems and Filters 7 6 Producing Lookup Table Data Overview Worst Case Error for a Lookup Table Example Square Root Function Creating Lookup Tables for a Sine Function Parameters for fixpt_look1 func approx Setting Function Parameters for the Lookup Table Example 1 Using errmax with Unrestricted Spacing Example 2
210. he Fixed Point Blockset you must be aware of these three issues e When numerical block parameters are converted from a double to a Fixed Point Blockset data type e When input signals are converted from one Fixed Point Blockset data type to another if at all e When arithmetic operations on input signals and parameters are performed For example suppose a fixed point block performs an arithmetic operation on its input signal and a parameter and then generates output having characteristics that are specified by the block The following diagram illustrates how these issues are related Fixed Point Block Parameter Value bo Input Operation us Output Data Type Output Scaling tout Rounding da Overflow Handling Parameter conversions and signal conversions are discussed below Arithmetic operations are discussed in Rules for Arithmetic Operations on page 4 30 4 26 Parameter and Signal C onversions Parameter Conversions Block parameters that accept numerical values are always converted from a double toa Fixed Point Blockset data type Parameters can be converted tothe input data type the output data type or toa data type explicitly specified by the block For example the FIR block converts the Initial condition parameter tothe input data type and converts the FIR coefficients parameter to a data type you explicitly specify via the block dialog box Parameters are alwa
211. he output scaling via the block dialog box or inheriting the output scaling from another block You control how the output scaling is selected with the Output data type and scaling parameter list The Fixed Point Blockset supports two general scaling modes radix point only scaling and slope bias scaling In addition to these general scaling modes the blockset provides you with additional block specific scaling choices for constant vectors and constant matrices These scaling choices are based on radix point only scaling and are designed to maximize precision Refer to Example Constant Scaling for Best Precision in Chapter 3 for more information To help you understand the supported scaling modes the general slope bias encoding scheme is presented in the next section The General Slope Bias Encoding Scheme When representing an arbitrarily precise real world value with a fixed point number it is often useful to define a general slope bias encoding scheme 2 5 2 G etting Started 2 6 V V SQ B where e Vis the real world value e V is the approximate real world value e Qis an integer that encodes V e B isthe bias e S F 2 is the slope The slope is partitioned into two components e 2E specifies the radix point E is the fixed power of two exponent e F is the fractional slope It is normalized such that 1 lt F lt 2 Radix Point Only Scaling Thisis powers of two scaling since it involves moving only
212. he x data scaling ydt sfix 16 Set the y data type yscale 2 14 Set the y data scaling rndmeth Floor Set the rounding method 8 3 8 Producing Lookup Table Data 8 4 Next type errworst fixpt_look1_func_plot xdata ydata funcstr xmin xmax xdt xscale ydt yscale rndmeth This returns the worst case error of the lookup table as the variable errworst errworst 0 1250 It also generates the plots shown below Figure No 1 olx File Edit View Insert Tools Window Help JDSMS LAA 2AP Function sqrt x Ideal red Fixed Point Lookup Approximation blue 0 0 0 1 0 2 03 04 05 06 OF O8 09 1 Table uses 3 unevenly spaced data points Input The input is Unsigned 16 Bit with 16 bits right of binary point The output is Signed 16 Bit with 14 bits right of binary point Maximum Absolute Error 0 12503 log2 MAE 2 9996 MAE yBit 2048 5 The least significant 12 bits of the output can be inaccurate The most significant nonsign bit of the output is used The remaining 3 nonsign bits of the output are used and always accurate The sign bit of the output is not used The rounding mode is to Floor The upper box Outputs displays a plot of the square root function and a plot of the fixed point lookup approximation underneath The approximation is found by linear interpolating between the breakpoints The lower box Absolute Error displays the errors at all points in the interval from 0 to 1 Notice that
213. hecked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion Of inputs and gain Integrator Backward and related blocks 10 129 Integrator Trapezoidal Resettable Purpose Library Description K Ts R 2i 10 130 1 1 Perform discrete time integration of a signal using the trapezoidal method with external Boolean reset Calculus The Integrator Trapezoidal Resettable block performs a discrete time integration of a signal using the trapezoidal method The block can reset its state based on an external reset signal R When the reset signal R is false at time k the block calculates the output at timek by the rule y k y k 1 w k w k 1 where u k is the input at time k and K Ts 2 w k U k When the reset signal R is true at timek the block resets the output y k tothe value of the Initial condition for previous output parameter and resets w k to the value of the Initial condition for previous weighted input K Ts u 2 parameter Integrator Trapezoidal Resetta ble Parameters a nd Dia log Box Block Parameters Integrator Trapezoidal Resettable r Fixed Point Integrator Trapezoidal Resettable mask link Discrete time integration of the in
214. hen the scaling and data type information is applied to the stored integer and the output value is 000011 11 or 3 75 If the value is output from the Gateway Out block as a stored integer then you get back the original input value of 15 The model shown below illustrates how a summation operation applies to real world values and stored integers and how scaling information is dealt with in generated code int16 15 Constant Gateway In sfx16_En4 int16 15 Constanti Gateway In1 Note that the summation operation produces the correct result when the Gateway Out block outputs a real world value This is because the specified scaling information is applied to the stored integer value However when the Gateway Out block outputs a stored integer value then the summation 10 103 Gateway In operation produces an unexpected result due to the absence of scaling information If you generate code for the above model then the code captures the appropriate scaling information The code for the Sum block is shown below The inputs to this block are tagged with the specified scaling information so that the necessary shifts are performed for the summation operation Sum Block lt Root gt Sum y ud ul InputO Data Type Fixed Point S16 2 2 Input1 Data Type Fixed Point S16 2 4 OutputO Data Type Fixed Point S16 2 5 Round Mode Floor Saturation Mode Wrap F HF sum in1
215. hey are carried out by the FIR block 1 TheFIR coefficients parameter is converted from doubles to the Parameter data type offline using round to nearest and saturation Thelnitial condition parameter is converted from doubles tothe input data type offline using round to nearest and saturation 4 Arithmetic O perations 2 The coefficients and inputs are multiplied together for the initial time step for both outputs For y3 0 the operations 13 u 0 11 0 8 and 7 1 1 are performed while for y 0 the operations 6 u 0 and 5 0 8 are performed The results of these operations are then converted to the Output data type using the specified rounding and overflow modes 3 Thesum is carried out for y 0 and y 0 Note that the rules for addition and subtraction are satisfied since the coefficients and inputs are already converted to the Output data type 4 Steps 2 and 3 are repeated for subsequent time steps 4 48 Realization Structures Overview 5 2 Direct Formil ee ce a ak 5 4 Series Cascade Form 5 7 Parallel Form 5 10 5 Realization Structures 5 2 Overview This chapter investigates how you can realize digital filters using the Fixed Point Blockset The Fixed Point Blockset addresses the needs of the control system and signal processing fields and other fields where algorithms are implemented on fixed point hardware In signal
216. ideal gas equation The ideal gas equation involves division by air temperature For proper results an absolute temperature scale such as Kelvin or Rankine must be used in the equation However quantization directly to an absolute temperature scale would cause needlessly large quantization errors The temperature of the air flowing into the engine has a limited range Ona typical engine the radiator is designed to keep the block below the boiling point of the cooling fluid Let s assume a maximum of 225 F 380 K Astheair flows through the intake manifold it can be heated up to this maximum temperature For a cold start in an extreme climate the temperature can be as Physical Q uantities and M easurement Scales low as 60 F 222 K Therefore using the absolute Kelvin scale the range of interest is 2222 K to 380 K The air temperature needs to be quantized for processing by the embedded control system Assuming an unrealistic quantization to 3 bit unsigned numbers 0 1 2 7 the purely linear conversion with maximum precision is 380 K VS pr Q The quantized conversion and range of interest are shown below Visualization of Quantized Conversion 8 T T T T T T T V 222 K V 380 K Quantized Value Q 50 6667 K bit with Bias 0 K 1 1 ll 1 1 1 1 1 0 50 100 150 200 250 300 350 400 Real World Value V K Noticethat there are 7 5 possible quantization values This is because only
217. ides several associated products that are especially relevant to the kinds of tasks you can perform with the Fixed Point Blockset For more information about any of these products see either e The online documentation for that product if it is installed or if you are reading the documentation from the CD e The products section of the MathWorks Web site http www mathworks com products Note Thetoolboxes listed below all include functions that extend MATLAB s capabilities The blocksets all include blocks that extend Simulink s capabilities xiii Preface Product Description Control System Toolbox DSP Blockset Real Time Workshop Simulink Simulink Report Generator Stateflow Stateflow Coder xPC Target Tool for modeling analyzing and designing control systems using classical and modern techniques Simulink block libraries for the design simulation and prototyping of digital signal processing systems Tool that generates customizable C code from Simulink models and automatically builds programs that can run in real time in a variety of environments Interactive graphical environment for modeling simulating and prototyping dynamic systems Tool for documenting information in Simulink and Stateflow in multiple output formats Tool for graphical modeling and simulation of complex control logic Tool for generating highly readable efficient C code from Stateflow diagrams Tool for
218. ify the operations with the Enter characters or the number of inputs parameter Plus minus characters indicate the operations to be performed on the inputs e f there are two or more inputs then the number of plus minus characters must equal the number of inputs For example requires three inputs and configures the block to subtract the second middle input from the first top input and then add the third bottom input e If only addition of inputs is required then a numeric parameter value equal to the number of inputs can be supplied instead of plus minus characters e If only one vector is input then a single or will collapse the vector using the specified operation For a detailed description of all other block parameters refer to Block Parameters on page 10 4 The Math Library contains the followingimplementations which areall linked to the Sum block but have different parameter settings Add e Subtract e Sum of Elements e Sum of Elements Negated Sum Parameters and Dialog Box Block Parameters Sum r Fixed Point Sum mask link Add or subtract inputs Specify one of the following a 4 or for each input b The number of inputs if only addition is desired c A single or to collapse a vector Parameters Enter characters or the number of inputs Output data type and scaling Specity via dialog Output data type ex sfix 16 uint 8 float sina
219. igns that are easily retargeted from fixed point chips to floating point chips or visa versa The Data Type Propagation block allows you to set up libraries of useful subsystems that will be properly configured based on the connected signals Without this data type propagation process a subsystem that you use from a library will almost certainly not work as desired with most integer or fixed point signals and manual intervention to configure the data type and scaling would be required This block can eliminatethe manual intervention in many situations Precedence Rules The precedence of the dialog box parameters decreases from top to bottom Additionally e Double precision reference inputs have precedence over all other data types e Single precision reference inputs have precedence over integer and fixed point data types e Multiplicative adjustments are carried out before additive adjustments e The number of bits is determined before the precision or positive range is inherited from the reference inputs Data Type Propagation Parameters and Dialog Box Block Parameters Data Type Propagation r Fixed Point Data Type Propagation mask link Set the Data Type and Scaling of the propagated signal based on information from the reference signals Notes 1 Items closer to the top of the dialog have higher priority precedence a Reference inputs of type double have priority over all others b Singles have priority over i
220. ion about the Simulink Accelerator A 11 A Code Generation A 12 Using External Mode or rsim Target If you are using the Real Time Workshop external mode or rsim rapid simulation target there are situations where you may get unexpected errors when tuning block parameters These errors can arise when you use blocks that support constant scaling for best precision and you use the best precision scaling option To avoid these errors you should usethe Use Specified Scaling parameter value Refer to Example Constant Scaling for Best Precision on page 3 12 for a description of the constant scaling feature Refer to Chapter 10 Block Reference for a description of blocks that support this feature For more information about external mode or rapid simulation target refer to the Real Time Workshop User s Guide External Mode If you change a fixed point block parameter by a sufficient amount approximately a factor of two the radix point changes If you change a parameter such that the radix point moves during an external mode simulation or during graphical editing and you reconnect tothetarget a checksum error occurs and you must rebuild the code For example suppose a block has a parameter value of 2 You then build the code and connect in external mode While connected you change the parameter to 4 If the simulation is stopped and then restarted this parameter change causes a radix point change In externa
221. ion values are logged tothe workshops Characteristics nput Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough For all math operations options except Ts and 1 Ts Scalar Expansion No the weight is always a scalar 10 183 Saturation Purpose Library Description J Parameters and Dialog Box Conversions Characteristics 10 184 Bound the range of the input Nonlinear The Saturation block is a masked S function that limits the input signal to upper and lower saturation values Y ou specify the upper bound of the input with the Upper limit parameter and the lower bound of the input with the Lower limit parameter If the input signal is outside these limits the output saturates to one of the bounds Block Parameters Saturation rm Fixed Point Saturation mask link Bound the range of the input Parameters Upper limit mE Lower limit ps Cancel Help Apply Upper limit The upper bound on the input signal Lower limit The lower bound on the input signal Both the Upper limit and Lower limit parameters are converted tothe input data type offline using round to nearest and saturation Input Port Any data type supported by the blockset Output Port Same as input data type Direct Feedthrough Yes Scalar Expansion Of input and limits Saturation Dynamic Purpose Library Description up J yF lo Parameters and Dial
222. irect_form2 10 BE 6H 1 1 1 1 1 1 0 20 40 60 80 100 120 140 160 180 200 8 Next define a fixed point base data type BaseType sfix 16 Follow the automatic scaling procedure described in the autofixexp reference pages with 20 safety margin and then run the simulation sim fxpdemo_preconvert_fixpt Thesimulation now produces an error This is becausethe vector signal leading into the scope is not homogeneous with regard to data type and scaling In general solving the problem of nonhomogeneous signals requires that you analyze how the signal is being used If the distinct scaling and data type properties are important then you must fully or partially unvectorize the relevant part of the model Alternatively you can force the signals to be homogenous using the Gateway Out block Since this example plots real world values in the Scope inserting gateway blocks on the signals leading into the Scope is an adequate solution autofixexp fixpt_convert_prep fxptdlg fixpt convert prep Purpose Prepare a Simulink model for more complete conversion to fixed point Syntax fixpt_convert_prep SystemName Description fixpt_convert_prep SystemName prepares the Simulink model or subsystem specified by SystemName for more complete conversion less encapsulation to fixed point using the fixpt_convert function It does so by replacing this select set of blocks e Old style Latch blocks Old style La
223. is a masked block that counts up until the maximum possible value 2 bits 1 is reached where Nbits is the number of bits Then the counter overflows to zero and restarts counting up The counter is always initialized to zero You can specify the number of bits with the Number of Bits parameter Y ou can specify the sample time with the Sample time parameter The output is an unsigned integer If the global doubles overrideis selected the Free Counter does not wrap back to zero Block Parameters Counter Free r Fixed Point Counter Free mask link This block is a counter that overflows back to zero after it has reached the maximum value possible for the specified number of bits The count is always initialized to zero The output is normally an unsigned integer with the specified number of bits Parameters Number of Bits AA Sample time O Cancel Help Enply Number of Bits Specified number of bits Sample time Sample time Output Port Unscaled integer or a floating point data type Scalar Expansion No Vectorized No 10 45 Counter Limited Purpose Count up and wrap back to zero after outputting the specified upper limit Library Sources Description The Limited Counter block is a masked block that counts up until the specified upper limit is reached Then the counter wraps back to zero and restarts counting up The counter is always initialized to zero You can specify the
224. is a power of two The section Restricting the Spacing on page 8 10 and the examples that follow it explain how to use the spacing parameter Setting Function Parameters for the Lookup Table To dothe examples in this section you must first set parameter values for the fixpt_look1_func_approx function To do so type the following at the MATLAB prompt funcstr sin 2 pi x Define the sine function xmin 0 Set the minimum input of interest xmax 0 25 Set the maximum input of interest Creating Lookup Tables for a Sine Function xdt ufix 16 Set the x data type xscale 2 16 Set the x data scaling ydt sfix 16 Set the y data type yscale 2 14 Set the y data scaling rndmeth Floor Set the rounding method errmax 2 10 Set the maximum allowed error nptsmax 21 Specify the maximum number of points If you exit MATLAB after typing these commands you must retype them before trying any of the other examples in this section Example 1 Using errmax with Unrestricted Spacing The first example shows how to create a lookup table that has the fewest data points for a specified worst case error with unrestricted spacing Before trying the example enter the same parameter values given in the section Setting Function Parameters for the Lookup Table on page 8 6 if you have not already done soin this MATLAB session You specify the maximum allowed error by typing errmax 2 10 Creating
225. is checked the Upper limit is included in the interval for which the block outputs TRUE Interval closed on left When the box is checked the Lower limit is included in the interval for which the block outputs TRUE Characteristics Input Ports Any data type supported by the blockset Output Port Same data type as output Direct Feedthrough Yes Scalar Expansion Yes See Also Interval Test 10 138 Logical Operator Purpose Library Description o Perform the specified logical operation on the inputs Logic Comparison TheLogical Operation block is a masked S function that performs the specified logical operation on its inputs An input value is TRUE 1 if it is nonzero and FALSE 0 if it is zero You select the Boolean operation connecting the inputs with the Operator parameter list The supported operations are given below Operation Description AND TRUE if all inputs are TRUE OR TRUE if at least oneinput is TRUE NAND TRUE if at least oneinput is FALSE NOR TRUE when no inputs are TRUE XOR TRUE if an odd number of inputs are TRUE NOT TRUE if the input is FALSE The number of input ports is specified with the Number of input ports parameter The output type is specified with the Logical output data type parameter An output value is 1if TRUE and 0 if FALSE Note The output data type should represent zero exactly Data types that satisfy this condition include signed and unsigned integers and any
226. ith the plot The error drops to zeroat a breakpoint and increases between breakpoints due to the difference in curvature of the ideal function and the line drawn between breakpoints The resulting plots are shown below 9 20 fix pt_look1_func_approx Figure No 1 olx Eile Edit View Insert Tools Window Help JOSUS KAALY PER junction sin 2 pi x Ideal red Fixed Point Lookup Approximation blue Absolute Error 0 05 0 1 0 15 0 2 0 25 Table uses 33 power of 2 spaced data point Put The input is Unsigned 16 Bit with 16 bits right of binary point The output is Signed 16 Bit with 14 bits right of binary point Maximum Absolute Error 0 00037209 log2 MAE 11 3921 MAE yBit 6 0964 The least significant 3 bits of the output can be inaccurate The most significant nonsign bit of the output is used The remaining 12 nonsign bits of the output are used and always accurate The sign bit of the output is not used The rounding mode is to Floor The lookup table requires 33 points to achieve a maximum absolute error of 2 11 3922 See Also fixpt_look1_func_plot 9 21 fixpt look1 _func plot Purpose Plot a function with x values generated by the fixpt_look1_func_approx function Syntax errworst fixpt_look1_func_plot xdata ydata funcstr xmin xmax xdt xscale ydt yscale rndmeth Description fixpt_look1_func_plot xdata ydata funcstr xmin xmax xdt xscale ydt yscale rndmeth plots a lookup table appro
227. ithmetic and its limitations Describes how to create fixed point realization structures using fixed point blocks Describes how to simulate a fixed point digital controller design Describes how to create and use fixed point systems and filters Describes how to create lookup table data using the lookup table approximation functions Describes MATLAB M file scripts and functions provided with the blockset Describes each fixed point block in detail Describes the simulation features that are available for code generation Recommendations for producing efficient code are provided Provides a selected list of references Installation Information Installation Information To determine if the Fixed Point Blockset is installed on your system type ver atthe MATLAB command line When you enter this command MATLAB displays information about the version of MATLAB you arerunning including a list of installed add on products and their version numbers Check the list to see if the Fixed Point Blockset appears For information about installing the blockset see the MATLAB Installation Guide for your platform If you experience installation difficulties and have Web access look for the installation and license information at the MathWorks Web site http www mathworks com support Preface Typographical Conventions This manual uses some or all of these conventions Item Convention Used Example
228. its 1 s and 0 s The way in which hardware components or software functions interpret this sequence of 1 s and O s is described by a data type Binary numbers are represented as either fixed point or floating point data types A fixed point data typeis characterized by the word sizein bits the radix binary point and whether it is signed or unsigned The radix point is the means by which fixed point values are scaled Within the Fixed Point Blockset fixed point data types can be integers fractionals or generalized fixed point numbers The main difference between these data types is their default radix point Floating point data types are characterized by a sign bit a fraction or mantissa field and an exponent field The blockset adheres to the IEEE Standard 754 1985 for Binary Floating Point Arithmetic referred to simply as the IEEE Standard 754 throughout this guide and supports singles doubles and a nonstandard I EEE style floating point data type When choosing a data type you must consider these factors e The numerical range of the result e The precision required of the result e The associated quantization error i e the rounding mode e The method for dealing with exceptional arithmetic conditions These choices depend on your specific application the computer architecture used and the cost of development among others With the Fixed Point Blockset you can explore the relationship between data types range precisi
229. ixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Same as the input u Direct Feedthrough Yes Scalar Expansion Of inputs and gain Integrator Backward and related blocks 10 123 Integrator Forward Resettable Limited Purpose Library Description Y kts L R z 1 Remarks 10 124 Perform discrete time limited integration of a signal using the forward method with external Boolean reset Calculus The Integrator Forward Resettable Limited block performs a discrete time integration of a signal using the forward method When the cumulative sum reaches one of the limits given by the Upper limit and Lower limit parameters the sum saturates to that limit When the external reset signal R is false the block multiplies the input by the weighted sample time and adds the result to the cumulative sum since time zero When the external reset signal R is true the block outputs the Initial condition for previous output parameter The first term of the sum is the product of the weighted sample time and the value of the Initial condition for previous input parameter The output of the Integrator Forward Resettable Limited block differs from the output of the Integr
230. ks FIR Purpose Description willl Implement a fixed point finite impulse response FIR filter TheFIR block isa masked S function that samples and holds the N most recent inputs multiplies each input by a specified value its FIR coefficient and stacks them in a vector This block supports both single input single output SISO and single input multi output SIMO modes For the SISO mode the FIR coefficients parameter is specified as a row vector For the SIMO mode the FIR coefficients are specified as a matrix where each row corresponds to a separate output The Initial condition parameter provides the initial values for all times preceding the start timein the FIR realization Y ou specify the time interval between samples with the Sample time parameter Y ou specify the scaling for the FIR coefficients with the Parameter scaling parameter Note that there are two dialog box parameters that control the FIR coefficient scaling one associated with an edit field and one associated with a parameter list If Parameter data type is a generalized fixed point number such as sfix 16 the Parameter scaling list provides you with these scaling modes e Use Specified Scaling This mode uses the slope bias or radix point only scaling specified for the editable Parameter scaling parameter for example 2 10 Best Precision Element wise This mode produces radix points such that the precision is maximized for each element of
231. l can t change it If the box is checked output scaling is locked 10 179 Repeating Sequence Stair Characteristics See Also 10 180 Output scaling Select the scaling method using the specified scaling or using the best precision Override data type s with doubles If checked the Output data type is overridden with doubles Output Port Any data type supported by the blockset Scalar Expansion No Vectorized No Repeating Sequence Interpolated Sample Time Multiply Purpose Library Description Support calculations involving sample time Calculus The Sample Time Multiply block is a masked S function that adds subtracts multiplies or divides the input signal u by a weighted sample time Ts Y ou specify the math operation with the Operation parameter Additionally you can specify to use only the weight with either the sample time or its inverse Enter the weighting factor with the Weight value If the weight is 1 wis removed from the equation For a detailed description of all block parameters refer to Block Parameters on page 9 4 For more information about converting from one Fixed Point Blockset data type to another refer to Signal Conversions on page 4 26 The Calculus library contains the following implementations which are all linked to the Sample Time Multiply block but have different parameter settings e Sample Time Divide e Sample Time Add e Sample Time Subtract e Sample
232. l can t change it Round toward Floor nd I Saturate to max or min when overflows occur T Override data type s with doubles IV Log minimums and maximums Esa Help Apply The parameters associated with this block are discussed below For detailed information about each fixed point block refer to Chapter 10 Block Reference An O verview of Blockset Features Real World Values Versus Integer Values Y ou can configure the fixed point gateway blocks to treat signals as real world values or as stored integers with the Treat input as parameter list The possible values are Real World Value and Stored Integer In terms of the variables defined in The General Slope Bias Encoding Scheme on page 2 5 the real world value is given by V and the stored integer value is given by Q You may want totreat numbers as stored integer values if you are modeling hardware that produces integers as output Selecting the Output Data Type For many fixed point blocks you have the option of specifying the output data type via the block dialog box or inheriting the output data type from another block You control how the output data type is selected with the Output data type and scaling parameter list The possible values are Specify via dialog Inherit via internal rule and Inherit via back propagation Some blocks support only two of these values The Fixed Point Blockset supports several fixed point and floating p
233. l mode the radix point is kept fixed If you keep the parameter value of 4 and disconnect from the target then when you reconnect a checksum error occurs and you must rebuild the code Rapid Simulation Target If a parameter change is great enough and you are using the best precision mode for constant scaling then you cannot use the rapid simulation target If you change a block parameter by a sufficient amount approximately a factor of two the best precision mode changes the radix point Any change in the radix point requires the code to be rebuilt since the model checksum is changed This means that if best precision parameters are changed over a great enough range you cannot use the rapid simulation target and a checksum error message occurs when you initialize the rsim executable Customizing Generated Code Customizing Generated Code Y ou can customize generated code by directly modifying the TLC file fixpttarget tlc which is located in the fixpoint directory The two most important customizations are described below Macros Versus Functions Y ou can modify the TLC file to generate macros or C functions calls With macros you can avoid the overhead of a function call With function calls you can significantly reduce the overall code size for large routines Additionally many debuggers will not allow you to single step through macros This is not the case with function calls The factory default setting is to generate m
234. l number Left of the most significant bit sfrac Signed fractional number Right of the sign bit The word size in bits of fixed point data types is given as an argument to the data type For example sfix 16 specifies a 16 bit signed generalized fixed point number Word sizes from 1 to 128 bits are supported Floating point data types are EEE style and are specified as float single for single precision numbers and float double for double precision numbers Nonstandard EEE style numbers are specified as float TotalBits ExpBits where TotalBits is the total number of physical bits and ExpBits is the number of exponent bits Note A default radix point is not included with the generalized fixed point data type Instead the scaling must be explicitly specified as described below For more information about supported data types and their default scaling refer to Chapter 3 Data Types and Scaling Selecting the Scaling For generalized fixed point data types you need to associate scaling information with numerical parameters and the output You can associate scaling information in these ways 10 6 Common Block Features Parameters The numerical parameter values of some fixed point blocks inherit the scaling of an input signal or the output signal Other blocks requirethat you specify the parameter scaling explicitly with the Parameter scaling parameter Output The output of some fixed point blocks inh
235. l u delayed by one sample period Parameters Sample time e Cancel Help Apply Sample time Sample time Characteristics Input Port u Any data type supported by the blockset Input Port IC Same as the input u Output Port Same as the input u Direct Feedthrough No of the input port Yes of the external IC port Scalar Expansion Yes 10 210 Unit Delay Resettable Purpose Library Description Parameters and Dialog Box Characteristics Delay a signal one sample period Delays Holds The Unit Delay Resettable block delays a signal one sample period The block can reset its state based on an external reset signal R The block has two input ports one for the input signal u and the other for the external reset signal R When the reset signal is false the block outputs the input signal delayed by one time step When the reset signal is true the block resets the current state tothe initial condition specified by the Initial condition parameter and outputs that state delayed by one time step Y ou specify the time between samples with the Sample time parameter A setting of 1 means the Sample time is inherited Block Parameters Unit Delay Resettable r Fixed Point Unit Delay Resettable mask link Normally the output is the signal u delayed by one sample period When the reset signal R is true the state and the output are always set equal to the initial condition parameter This reset a
236. lant and controller For the feedback design used in this tutorial the plant is characterized by a transfer function The characteristics of the plant are unimportant for this tutorial and are not discussed The digital controller mode used in this tutorial is described by a z domain transfer function and is implemented using a direct form realization Evaluate the behavior of the plant and controller This is accomplished with a Bode plot The evaluation is idealized since all numbers operations and states are double precision Simulate the system The feedback controller design is simulated using Simulink and the Fixed Point Blockset Of course in a simulation environment you can treat all components software and hardware as though their characteristics are not fixed 6 5 6 Tutorial Feedback Controller Simulation Idealized Feedback Design Open loop controller and plant and plant only Bode plots for the Scaling a Fixed Point Control Design demo are shown below The open loop Bode plot results from a digital controller described in the idealized world of continuous time and double precision coefficients storage of states and math operations The plant and controller design criteria are not important for the purposes of this tutorial The Bode plots were created using the workspace variables produced by the preload_feedback M file Bode Plots Plant Only dashed and Open Loop solid T ae o Magnitude
237. le sfis 16 Output scaling Slope or Slope Bias ex 2 9 jao I Lock output scaling so autoscaling tool can t change it Round toward Fo I Saturate to max or min when overflows occur I Override data type s with doubles VV Log minimums and maximums Cancel Help Apply l Enter characters or the number of inputs Enter as many plus or minus characters as there are inputs For addition only you can enter the number of inputs sincethis is the default operation Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling from the driving block or by back propagation Output data type Any data type supported by the Fixed Point Blockset Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generalized fixed point output 10 193 Sum Operations Characteristics 10 194 Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the
238. le signal is off the block is disabled and the state and output values do not change except for resets The enable signal is on when E is not 0 and off when E is 0 Theinput u and initial condition IC must be the same data type but can be any data type The output is the same data type as the inputs u and IC The reset R can be any data type Y ou specify the time between samples with the Sample time parameter A setting of 1 means the Sample time is inherited 10 217 Unit Delay With Preview Enabled Resettable Parameters a nd Dia log Box fue E Unit Delay With Preview His Resettable m Fixed Point State Enabled Resettable mask link Unit Delays With Preview have two outputs instead of just one Normally the first output equals the signal u and the second output is 4 unit delayed version of the first output Having both signals is useful for implementing recursive calculations where the result should include the most recent inputs The second output of a Unit Delay With Preview can be safely feedback into calculations of the block s inputs without causing an algebraic loop Meanwhile the first output will show the most up to date calculations The external reset signal A works with the internal initial condition When the reset signal R is true the first output signal is forced to equal the initial condition The second output signal is not affected until one time step later The internal initial condition is
239. lements of the table to determine an output value If the block input is less than the first or greater than the last input vector element then the block extrapolates using the first two or last two points Interpolation Use End Values This method performs linear interpolation as described above but does not extrapolate outside the end points of the input vector Instead the end point values are used Use Input Nearest This method does not interpolate or extrapolate Instead the element in x nearest the current input is found The corresponding element in y is then used as the output Use Input Below This method does not interpolate or extrapolate Instead the element in x nearest and below the current input is found The corresponding element in y is then used as the output If thereis no element in x below the current input then the nearest element is found Use Input Above This method does not interpolate or extrapolate nstead the element in x nearest and above the current input is found The corresponding element in y is then used as the output Ifthereis no element in x above the current input then the nearest element is found For a detailed description of all other block parameters refer to Block Parameters on page 10 4 10 147 Look Up Table Dynamic Parameters and Dialog Box 10 148 Block Parameters Look Up Table Dynamic m Fixed Point Look Up Table Dynamic mask link Approximate a one dimensi
240. link This block strips the scaling off a fixed point signal It maps the input data type to the smallest built in data type that has sufficient bits to hold the input The stored Integer Value of the input will be the value of the output The output always has nominal scaling slope 1 0 and bias 0 0 so the output does not have a distinction between Real World Value and Stored Integer Value Cancel Help Apply l Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion Yes Sign Purpose Library Description Parameters and Dialog Box Characteristics Indicatethe sign of the input Nonlinear The Sign block is a masked S function that indicates the sign of the input e The output is 1 when the input is greater than zero e The output is O when the input is equal to zero e The output is 1 when the input is less than zero Theoutput is a signed data type with the same number of bits as the input and with nominal scaling a slope of one and a bias of zero Block Parameters Sign Output 1 for positive input 1 for negative input and O for O input y Fixed Point Signum mask link Ed Cancel Help Apply Input Port Any data type supported by the blockset Output Port A signed Fixed Point Blockset data type Direct Feedthrough Yes Scalar Expansion N A 10 187 Sine Purpose Library Descri
241. lockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion Yes Dead Zone Decrement Real World Purpose Decrease the real world value of the signal by one Library Math Description The Decrement Real World block is a masked block that decreases the real world value of the signal by one Overflows always wrap e Parameters and Dialog Box Block Parameters Decrement Real World Fixed Point Real World Value Decrement mask link Decrease the Real World Value of Signal by 1 0 Overflows will always wrap Cancel Help Apply i Characteristics nput Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion No 10 61 Decrement Stored Integer Purpose Library Description Parameters and Dialog Box Characteristics See Also 10 62 Decrease the stored integer value of a signal by one Math The Decrement Stored Integer block is a masked block that decreases the stored integer value of a signal by one Floating point signals are also decreased by one and overflows always wrap Block Parameters Decrement Stored Integer Decrease the Stored Value of Signal by 1 Floating Point signals are decreased by 1 0 Fixed Point Stored Integer Value Decrement mask parameterized link E will always wrap E Cancel Help Apply Input Port Any data type supported by the blockset Output Port Sam
242. low occurred You can display a block s dialog box by double clicking on the appropriate entry Fixed Point Blockset Interface fxpdemo_feedback Ol x Log Min Max Use block params Y Autoscale Safety Margin 0 0 Log Mode Override log x Doubles Override Use block params y Block path Run Stop Autoscale Plot Help Close fx ptdlg The Log Min Max This menu controls which blocks log data A11 logs min max data for all blocks None doesn t log any min max data and Use block params logs min max data for all blocks that have the Log minimums and maximums check box checked Log Mode This menu controls how the log file is updated when multiple simulations arerun Override log updates all logged values for each simulation run Merge log keeps the highest and lowest logged values across multiple simulations Autoscale Safety Margin This parameter multiplies the simulation values by the specified factor and allows you to specify a range differing from that defined by the maximum and minimum values logged to the workspace For example a value of 55 specifies that a range at least 55 percent larger is desired A value of 15 specifies that a range up to 15 percent smaller is acceptable The Autoscale Safety Margin parameter is used as part of the automatic scaling procedure Before automatic scaling is performed you must run the simulation to collect min max data Data Type Ove
243. ls 0 015625 01 010101 You can use the maximum precision as the scaling parameter in fixed point blocks fixptbestexp sfix ufix 9 7 fixpt_convert Purpose Syntax Description 9 8 Convert Simulink models and subsystems to fixed point equivalents res fixpt_convert res fixpt_convert SystemName res fixpt_convert SystemName Display res fixpt_convert SystemName Display AutoSave res fixpt_convert converts the Simulink model or subsystem specified by bdroot res is a structure that contains lists of blocks handled during conversion The fields of this structure are given below Output Field Description replaced Blocks that are replaced with fixed point equivalents or with other blocks from a user specified replacement list skipped Blocks that are skipped because they are fixed point compatible Some of these blocks can cause errors if used in certain ways For example the Mux block can create lines that give different data types at down stream input ports encapsulated Structure containing lists of blocks grouped by type that are encapsulated between fixed point gateway blocks The encapsulated versions are not truly fixed point but they will function within a fixed point model res fixpt_convert SystemName converts the Simulink model or subsystem specified by SystemName res fixpt_convert SystemName Display returns information associated with the conversi
244. lue fixptbestprec Determine the maximum precision available for the fixed point representation of a value fixpt_convert Convert Simulink models and subsystems to fixed point equivalents fixpt_convert_prep Prepare a Simulink model for more complete conversion to fixed point fixpt_look1_func_approx Optimize for a fixed point function the x values that are generated for a lookup table fixpt_look1_func_plot Plot a function with x values generated by the fixpt_look1_func_approx function fixpt_restore_links Restore links for fixed point blocks float Create a MATLAB structure describing a floating point data type O verview Table 9 1 Fixed Point Blockset Functions Continued Function Description fpupdate Update obsolete fixed point blocks from previous Fixed Point Blockset releases to current fixed point blocks fxptdlg Launch the Fixed Point Blockset nterface tool sfix Create a MATLAB structure describing a signed generalized fixed point data type sfrac Create a MATLAB structure describing a signed fractional data type showfixptsimranges Display the logged maximum and minimum values from the last simulation sint Create a MATLAB structure describing a signed integer data type ufix Create a MATLAB structure describing an unsigned generalized fixed point data type ufrac Create a MATLAB structure describing an unsigned fractional data type uint Create a MATLAB structure describing an unsig
245. lues for an 8 bit gener alized fixed point data type with radix point only scaling are given below Note that the first scaling value 2 represents a radix point that is not contiguous with the word Table 3 2 Range of an 8 Bit Fixed Point Data Type Radix Point Only Scaling Scaling Precision Range of Signed Values low high Range of Unsigned Values low high 2 2 0 2 1 0 2 0 5 2 0 25 ae 0 125 ri 0 0625 256 254 128 127 64 63 5 32 31 75 16 15 875 8 7 9375 0 510 0 255 0 127 5 0 63 75 0 31 875 0 15 9375 Fixed Point N umbers Table 3 2 Range of an 8 Bit Fixed Point Data Type Radix Point Only Scaling Scaling Precision Range of Signed Range of Unsigned Values low high Values low high 7 0 03125 4 3 96875 0 7 96875 2 0 015625 2 1 984375 0 3 984375 a 0 0078125 1 0 9921875 0 1 9921875 ri 0 00390625 0 5 0 49609375 0 0 99609375 The precision and range of signed and unsigned values for an 8 bit fixed point data type using slope bias scaling are given below The slope starts at a value of 1 25 and the bias is 1 0 for all slopes Note that the slope is the same as the precision Table 3 3 Range of an 8 Bit Fixed Point Data Type Slope Bias Scaling Bias Slope Precision Range of Signed Range of Unsigned Values low high Values low high 1 1 25 159 159 75 1 319 75 1 0 625 79 80 375 1 160 375 1 0 3125 39 40 6875 1 80 6875
246. m simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Same as the input u Direct Feedthrough Yes of the input and reset source ports Scalar Expansion Of inputs and gain Integrator Backward and related blocks Integrator Trapezoidal Resettable Limited Purpose Library Description u R K Ts 2 z 1 Perform discrete time limited integration of a signal using the trapezoidal method with external Boolean reset Calculus The Integrator Trapezoidal Resettable block performs a discrete time integration of a signal using the trapezoidal method The block can reset its state based on an external reset signal R When the cumulative sum reaches one of the limits given by the Upper limit and Lower limit parameters the sum saturates to that limit When the reset signal R is false at time step k the block calculates the output at time k by the rule y k y k 1 w k w k 1 where u k is the input at time k and K Ts w k 5 U k When thereset signal R is true at timek the block resets the output y k tothe value of the Initial condition for previous output parameter The block also resets w k tothe value of the Initial condition for previous weighted input K Ts u 2 parameter 10 133 Integrator Trapezoidal Resettable Limited Parameters a nd Dia log Box B a OS Integrator Wee iiaa Limited rm Fixed Point Integrator Trapezoidal
247. mat but not so after conversion toa fixed point data type Note Unlikethe Look Up Table block the Look U p Table Dynamic block allows you to change the table data without stopping the simulation For example you may want to automatically incorporate new table data if the physical system you are simulating changes Y ou define the look up table by inputting the x and y table data to the block as 1 by n vectors To help reduce the ROM used by the code generated for this block you can use different data types for the x table data and the y table data However these restrictions apply e The y table data and the output vector must have the same sign the same bias and the same fractional slope e The x table data and the x data vector must have the same sign the same bias and the same fractional slope Additionally the precision and range for the x data vector must greater than or equal to the precision and range for the x table data The block generates output based on the input values using one of these methods selected from the Look up method parameter list e Interpolation Extrapolation This is the default method it performs linear interpolation and extrapolation of the inputs Look Up Table Dynamic Ifa value matches the block s input the output is the corresponding element in the output vector If no value matches the block s input then the block performs linear interpolation between the two appropriate e
248. me Workshop you can generate C code for execution on a fixed point embedded processor the generated code uses only integer types and automatically includes all operations such as shifts needed to account for differences in fixed point locations Ex ploring the Blockset To open the Fixed Point Blockset library type fixpt at the MATLAB command line or right click on the Fixed Point Blockset listing in the Simulink Library Browser Double click on any block icon in the library to see its parameter dialog box Press the Help button to view the HTML based help for that block Related Products Related Products System Requirements The Fixed Point Blockset is a multiplatform product that you install on a host computer running any of the operating systems supported by The MathWorks The Fixed Point Blockset requires e MATLAB 6 0 Release 12 e Simulink 4 0 Release 12 In addition if you want to modify the fixed point blocks you need one of the C compilers supported by the mex utility If you want to generate code from your fixed point models you must have the Real Time Workshop If you want to create an executable from the generated code you must have the appropriate C compiler and linker For the most up to date information about system requirements see the system requirements section available in the support area of the MathWorks Web site http www mathworks com support Associated Products The MathWorks prov
249. ments of the vector If a bit mask is not specified then the output is a scalar If a bit mask is specified then the output is a vector 10 31 Bitwise Operator Remarks 10 32 e For two or more inputs the block performs the operation between all of the inputs If the inputs are vectors the operation is performed between corresponding elements of the vectors to produce a vector output When configured as a multi input XOR gate this block performs an addition modulo two operation as mandated by the IEEE Standard for Logic Elements If the Use bit mask check box is not checked then the block can accept multiple inputs You select the number of input ports with the Number of input ports parameter The input data types must be identical If the Use bit mask check box is checked then a singleinput is associated with the bit mask you specify with the Bit mask parameter Y ou specify the bit mask using any valid MATLAB expression For example you can specify the bit mask 00100101 as 2 5 2 2 2 0 Alternatively you can use strings to specify a hexadecimal bit mask such as FE73 12AC If the bit mask is larger than the input signal data type then it is ignored Note The output data type which is inherited from the driving block should represent zero exactly Data types that satisfy this condition include signed and unsigned integers and any floating point data type The Treat mask as parameter list controls how the mask
250. merator coefficients and the Denominator coefficients excluding lead parameters The block only supports single input single output filters The block automatically selects the data types and scalings of the output the coefficients and any temporary variables Block Parameters Filter Direct Form Il r Fixed Point Filter Direct Form II mask link A Direct Form Il realization of the specified filter is used Only single input multiple output filters are supported The data types and scalings of the output the coefficients and any temporary variables are automatically selected The automatic choices will be acceptable in many situations In situations where the automatic choices give unacceptable results manual layout of the filter is necessary For manual layout it is suggest that the blocks under this mask be used as a starting point Note 1 The full denominator should have a leading coefficient of 1 0 but this leading coefficient should be excluded when entering the parameter For example if the denominator is den 1 A 0 72 just enter den 2 end 1 7 0 72 Note 2 The numerator does NOT need to be the same size as the full denominator Parameters Numerator coefficients fie 2 0 30 2 Denominator coefficients excluding lead which must be 1 0 ro 0 6 Initial condition fo D Round toward Floor z I Saturate to max or min when overflows occur I Override data type s with doubles V
251. meters Initial condition a Sample time 1 Number of delays fa Order output vector starting with Didest X Cancel Help Apply 10 197 Tapped Delay Conversions Characteristics 10 198 Initial condition The initial output of the simulation Sample time Sample time Number of delays The number of discrete time operators Order output vector starting with Specify whether the oldest delay version is output first or the newest delay version is output first The Initial condition parameter is converted from a double to the input data type offline using round to nearest and saturation Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough No Scalar Expansion Yes of initial conditions Unary Minus Purpose Library Description Parameters and Dialog Box Characteristics Negate the input Math The Unary Minus block is a masked S function that negates the input The block accepts only signed data types For signed data types you cannot accurately negate the most negative value since the result is not representable by the data type In this case the behavior of the block is controlled by the Saturate to max or min when overflows occur check box If checked the most negative value of the data type wraps to the most positive value If not checked the operation has no effect If an overflow occurs then a warning is returned t
252. minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion N A Conversion Inherited 10 41 Conversion Inherited Purpose Library Description 7 Remarks 10 42 Convert from one Fixed Point Blockset data type to another and inherit the data type and scaling Data Type The Conversion Inherited block is a masked S function that forces dissimilar data types to be the same The first top input is used as the reference signal and the second bottom input is converted to the reference type by inheriting the data type and scaling information Either input will be scalar expanded such that the output has the same width as the widest input If you want to specify the data type and scaling when converting from one Fixed Point Blockset data type to another you should use the Conversion block For a detailed description of all block parameters refer to Block Parameters on page 10 4 For more information about converting from one Fixed Point Blockset data type to another refer to Signal Conversions on page 4 27 Inheriting the data type and scaling provides these advantages e It makes reusing existing models easier e It allows you to create new fixed point models with less effort since you can avoid the detail of specifying the associated parameters C
253. mple time Output data type and scaling Specify the output data type and scaling via the dialog box or by inheriting the data type and scaling by back propagation Output data type Any data type supported by the blockset Output scaling Select the scaling method using the specified scaling or using the best precision Lock output scaling so autoscaling tool can t change it If the box is checked output scaling is locked Override data type s with doubles If checked the Output data type is overridden with doubles Output Port Any data type supported by the blockset Scalar Expansion Yes 10 177 Repeating Sequence Stair Purpose Library Description EN 10 178 Output and repeat the discrete time sequence Sources The Repeating Sequence Stair block is a masked block that outputs and repeats a discrete time sequence Y ou can specify the stair sequence with the Vector of output values parameter For example the vector can bespecifiedas 3 1 2 4 1 producing the stair sequence shown in the plot w L N T 1 Repeating Stair Sequence a T 1 0 0 5 1 1 5 Time Sample Y ou can specify the sample time with the Sample time parameter Y ou can select the output data type and scaling with the Output data type and scaling parameter and set the output data type with the Output data type parameter For fixed poin
254. mulation Data is logged only from blocks where the Log minimums and maximums check box is checked The logged data is stored in the FixPtSimRanges cell array which can be accessed by the autofixexp automatic scaling script See Also autofixexp fxptdlg 9 33 sint Purpose Syntax Description Example See Also 9 34 Create a MATLAB structure describing a signed integer data type a sint TotalBits sint TotalBits returns a MATLAB structurethat describes the data type of a signed integer with a word size given by TotalBits sint is automatically called when a signed integer is specified in a block dialog box The default radix point for this data type is assumed to lie to the right of all bits Define a 16 bit signed integer data type sint 16 a a Class INT IsSigned 1 MantBits 16 float sfix sfrac ufix ufrac uint ufix Purpose Create a MATLAB structure describing an unsigned generalized fixed point data type Syntax a ufix TotalBits Description ufix TotalBits returns a MATLAB structurethat describes the data type of an unsigned generalized fixed point data type with a word size given by TotalBits ufix is automatically called when an unsigned generalized fixed point data type is specified in a block dialog box Note The default radix point is not included in this data type description Instead the scaling must be explicitly defined in the block dialog box Example D
255. n Coder If your version of the Real Time Workshop does not support ERT code generation then you may want to select the Generic Real Time Target GRT Using GRT all Fixed Point Blockset blocks except the gateway blocks will generate pure integer code However the code related to the GRT infrastructure is not generated to exclude floating point operations For example GRT may decide when to execute blocks based on a floating point counter 1 Copy the fixed point portion of your model to a new model If your original model includes blocks that represent hardware analog systems and other blocks not related to embedded software then you must A 5 A Code Generation A 6 create a new model This new model contains only the fixed point portion which represents the software that will be running on the fixed point processor For example the digital controller subsystem shown above contains the fixed point blocks from the fxpdemo_feedback model used for code generation 2 Insert Gateway In blocks as needed Changethe Treat input as parameter from Real World Value to Stored Integer This does not change the signal s value but it is needed to tag integers with fixed point scaling information The Gateway In block dialog box for this configuration is shown below Block Parameters Tag r Fixed Point Gateway In mask link Convert from a Simulink built in data type to a Fixed Point Blockset data m Pa
256. n approach is heuristic Using the Approximation Function 1 Choose a function and use the eval funcstr command to view the function before creating the lookup table 2 Define the remaining inputs Run the fixpt_look1_func_approx function Usethe fixpt_look1_func_plot to plot the function from the selected breakpoints and to calculate the error and the number of points used Vary the inputs to produce sets of breakpoints that generate functions with varying number of points required and worst case error Compare the number of points required and worst case error from various runs to choose the best set of breakpoints Calculating the Output Function To calculate the function use the returned breakpoints with The eval function A function lookup table The x values are the breakpoints from the fixpt_look1_func_approx function and the y values can be supplied using the eval function 9 17 fixpt_look1_func_approx 9 18 Selecting Spacing to O ptimize Speed Error ROM and RAM The spacing you choose depends on the parameters you want to optimize execution speed function approximation error ROM usage and RAM usage e The execution speed depends on the bisection search and the interpolation method e The error depends on how accurately the method approximates the nonuniform curvature of the function e The ROM usage depends on the amount of data and command ROM used e The RAM usage depends on how much
257. n is obtained when 0 lt Zero lt Pole lt 1 m Parameters Pole of filter in Z plane 0 35 Zero of filter in Z plane 0 75 Initial condition for previous output pe oo o ao Initial condition for previous input fo 0 Round toward Floor z I Saturate to max or min when overflows occur TF Override data typefs with doubles M Log minimums and maximums Cancel Help Apply Pole of filter in Z plane Set the pole of the filter Zero of filter in Z plane Set the zero of the filter 10 89 Filter Lead or Lag Characteristics See Also 10 90 Initial condition for previous output Set the initial condition for the previous output Initial condition for previous input Set the initial condition for the previous input Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset it must be a scalar Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of initial conditions Vectorized No FIR and related blocks Filter Real Zero Purpose Library Description Parameters
258. n wasted A second approach is to use a nonstandard scale In this scale the integers 0 and 255 represent water at the freezing point and at the boiling point respectively On the upside this scale gives maximum precision sincethere are 254 values between freezing and boiling instead of just 99 The units are roughly 0 3921568 degrees Celsius per bit sothe conversion to Celsius requires division by 2 55 which is a relatively expensive operation on most fixed point processors A third approach is to use a semi standard scale For example the integers O and 200 could represent water at the freezing point and at the boiling point respectively The units for this scale are 0 5 degrees Celsius per bit On the downside this scale doesn t usethe numbers from 201 to 255 which represents a waste of more than 21 On the upside this scale permits relatively easy conversion to a standard scale The conversion to Celsius involves division by 2 which is a very easy shift operation on most processors Measurement Scales Beyond Multiplication One of the key operations in converting from one scale to another is multiplication The preceding case study gave three examples of conversions from a quantized integer value Q toa real world Celsius value V that involved only multiplication 100 C 100 bits Q Conversion 1 _ 100 C i V 255 bits Q3 Conversion 2 E Q3 Conversion 3 Graphically the conversion is a line with slope S
259. nalog to digital A D interface consists of a Gateway In block that converts a Simulink double toa Fixed Point Blockset data type It represents any hardware that digitizes the amplitude of the analog input signal In the real world its characteristics are fixed Digital Controller The digital controller is a subsystem that represents the software running on the hardware target It is discussed in detail in Digital Controller Realization on page 6 7 Digital to Analog Interface The digital to analog D A interface consists of a Gateway Out block that converts a Fixed Point Blockset data type into a Simulink double It represents any hardware that converts a digitized signal into an analog signal In the real world its characteristics are fixed Analog Plant The analog plant is described by a transfer function and is the object controlled by the digital controller In the real world its characteristics are fixed Simulation Setup Setting up the fixed point feedback controller simulation involves these steps 1 Identify all design components In the real world there are design components with fixed characteristics the hardware and design components with characteristics that you can change the software The main components modeled in this feedback design are the A D hardware the digital controller the D A hardware and the analog plant Simulink M odel of a Feedback Design 2 Develop a theoretical model of the p
260. nce information The Apply button sets the current parameter values and but does not close the dialog box Simulink stores the strings entered in these fields and passes them to MATLAB for evaluation when a simulation is started If MATLAB variables are used the simulation uses the values that exist in the workspace at the start of the simulation These variables are not necessarily the same as when the variables are entered into the dialog box fields If a simulation is running when a parameter is changed MATLAB evaluates the parameter as soon as you press the OK or Apply button 10 3 10 Block Reference 10 4 Common Block Features For convenience all the common block features are described in this section These common features include e Block parameters e Block icon labels e Port data type display Block Parameters Many Fixed Point Blockset blocks use the same parameters which you configure through the block dialog box The common block parameters are associated with these blockset features e Parameter and output data type selection e Parameter and output scaling selection e Rounding e Overflow handling e Overriding the output data type with doubles e Logging simulation results Block specific parameters are described in the block reference pages Selecting the Data Type For many fixed point blocks you need to associate data type information with numerical parameters and the output Y ou can associate d
261. nction Parameters for the Lookup Table on page 8 6 if you have not already done so in this MATLAB session Next at the MATLAB prompt type spacing even xdata ydata errworst fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth errmax spacing Y ou can find the number of points in the lookup table by typing length xdata ans 20 To plot the lookup table along with the errors type fixpt_looki_func_plot xdata ydata funcstr xmin xmax xdt xscale ydt yscale rndmeth This produces the following plots 8 11 8 Producing Lookup Table Data 8 12 Figure No 1 olx Eile Edit View Insert Tools Window Help JDS HS RAAS POR Function sin 2 pi x Ideal red Fixed Point Lookup Approximation blue 1 Absolute Error Bo 0 Table uses 20 evenly spaced data points Input The input is Unsigned 16 Bit with 16 bits right of binary point The output is Signed 16 Bit with 14 bits right of binary point Maximum Absolute Error 0 00092109 log2 MAE 10 0844 MAE yBit 15 0912 The least significant 4 bits of the output can be inaccurate The most significant nonsign bit of the output is not used The remaining 10 nonsign bits of the output are used and always acourate The sign bit of the output is not used The rounding mode is to Floor Example 4 Using nptsmax with Even Spacing The next example shows how to create a lookup table that has evenly space breakpoint
262. ndling O verflows Overflow handling for fixed point numbers is specified with the Saturate to max or min when overflows occur check box f checked fixed point overflow results saturate Otherwise overflow results wrap Whenever a result saturates a warning is displayed Overriding with Doubles If the Override data type s with doubles check box is checked then the Parameter data type and Output data type parameter values are ignored Instead parameters and outputs are represented using double precision floating point numbers Also any calculations are performed using floating point arithmetic An exception to this rule is when parameters or outputs contain a bias In this case the bias is not ignored in subsequent fixed point operations If the parameter and output data types are both floating point the check box is not available Logging Simulation Results The minimum and maximum values produced by the simulation are logged if the Log minimums and maximums check box is checked The logged values are stored in the FixPtSimRanges global cell array in the MATLAB workspace Y ou can access these values with the showfixptsimranges script or with the Fixed Point Blockset Interface tool fxptdlg In addition tologging the minimum and maximum simulation values overflow information is also logged If an overflow occurs then a warning an error or nothing occurs depending on how the Data Overflow parameter of Simulink s Simulation P
263. ned integer data type 9 3 autofixexp Purpose Syntax Description 9 4 Automatically change the scaling for each fixed point block that does not have its scaling locked autofixexp The autofixexp script automatically changes the scaling for each block that does not have its scaling locked This script uses the maximum and minimum data obtained from the last simulation run to log data to the workspace The scaling is changed such that the simulation range is covered and the precision is maximized The script follows these steps 1 Theglobal variable FixPtTempGlobal is created to steal parameters such as data type from variables not known in the base workspace For example assume the Sum block has its output data type specified as DerivedVar DerivedVar is derived in the mask initialization based on mask parameters and the block is under a mask The value of the parameter DerivedVar is retrieved by temporarily replacing DerivedVar with stealparameter DerivedVar in the block dialog A model update is then forced When stealparameter DerivedVar is evaluated it returns the value of DerivedVar without modification and stores the value in FixPtTempGlobal The stolen value is immediately used by this procedure and is not needed again Therefore the procedure can move from one block to the next using the same global variable 2 TheRangeFactor variable allows you to specify a range differing from that defined by the ma
264. ng fxpdemo_parallel_form at the MATLAB command line FixPtGain2 t C if Out Vv Output FixPtGain1 FixPiSumt FixPt to Dbl Mux3 Comparison ooo b 00 In F Input To FixPt e FixPtUni FixPtSum Deer El FixPtGain a i F FixPtGain5 i S F FixPtSum3 FixPtGain6 f la E E gt 2 ZF ZA p Sisua FixPtUnit FixPtUnit a Delay1 Delay2 lt FixPtGain3 i FixPtGain4 d 5 12 Tutorial Feedback Controller Simulation Overview 2 vs a ee ee 8 6 2 Simulink Model of a Feedback Design 6 3 Idealized Feedback Design 2 2 2 2 6 6 Digital Controller Realization 6 7 Simulation Results 2 2 2 6 9 Simulation 1 Initial Guess at Scaling 2 2 6 9 Simulation 2 Global Override 2 6 12 Simulation 3 Automatic Scaling 2 2 6 15 Simulation 4 Individual Override 24 6 18 6 Tutorial Feedback Controller Simulation 6 2 Overview The purpose of this tutorial is to show you how to use fixed point blocks to simulate a fixed point feedback design using the Fixed Point Blockset Interface tool In doing so many of the essential blockset features are demonstrated These include e Output data type selection e Output scaling e Logging maximum and minimum simulation results e The automatic scaling tool e Overriding the output data typ
265. ng edge when the signal s value decreases to a nonpositive value and ts previous value was strictly positive Detect an increase in a signal s value The Fixed Point Blockset Libraries Edge Detect Detect Rise Nonnegative Detect Rise Positive Detect a rising edge when a signal s value increases to a nonnegative value and its previous value was strictly negative Detect a rising edge when a signal s value increases to a strictly positive value and its previous value was nonpositive Filters Filter Direct Forml Filter Direct Form Time Varying Filter Direct Form I Filter Direct Form Time Varying Filter First Order Filter Lead or Lag Filter Real Zero FIR State Space Implement a Direct Form I realization of a filter Implement a time varying Direct Form realization of a filter Implement a Direct Form II realization of a filter Implement a time varying Direct Form realization of a filter Implement a discrete time first order filter Implement a discrete time lead or lag filter Implement a discrete time filter that has a real zero and no pole Implement a fixed point finite impulse response FIR filter Implement discrete time state space 10 17 10 Block Reference 10 18 Logic amp Comparison Compare to Constant Compare To Zero Interval Test Interval Test Dynamic Logical Operator Relational Operator Determine if a signal i
266. ng existing models easier e it allows you to create new fixed point models with less effort since you can avoid the detail of specifying the associated parameters 10 105 Gateway In Inherited Parameters a nd Dia log Box Block Parameters Gateway In Inherited gt Fixed Point Gateway In Inherited mask link Convert the second input to the data type and scaling of the first input The conversion has two possible goals One goal is to have the Real World Values of the input and the output be equal The other goal is to have the Stored Integer Values of the input and the output be equal Overflows and quantization errors can prevent the goal from being fully achieved The both inputs and the output support all built in and fixed point data types Parameters Input and Output to have equal PEA Round toward Floor bs I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Input and Output to have equal Specify the type of value that the input and output are to have equal Round toward Rounding mode for fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are l
267. ning the full simulation range For a complex model the absence of such a procedure can make achieving this goal tedious and time consuming Automatic scaling is performed for the Controller block This block is a subsystem representing software running on the target and requires optimization Automatic scaling consists of these steps 1 Configure Autoscale Safety Margin to 20 This sets scaling so that the largest simulation value seen is at least 20 smaller than the maximum value allowed The Autoscale Safety Margin parameter value multiplies the raw simulation values by a factor of 1 2 Configuring this parameter to a value greater than 1 guarantees the simulation covers the largest possible range although it does not necessarily mean the resolution improves Since there is always some uncertainty when representing a real world value with a fixed point number with only a few simulations using this parameter is recommended 2 Run the autofixexp M file script by selecting the Autoscale button This script automatically changes the scaling on all fixed point blocks that do not have their scaling locked and that have their output data type specified as a generalized fixed point number It uses the minimum and maximum data logged from the previous simulation The scaling changes such that the precision is maximized whilethe full range of simulation values are spanned for each block 3 Turn off the global override with doubles by
268. nt block is a masked block that determines if a signal is equal to the specified constant where e The output is true not 0 when the input signal is equal to the specified constant e The output is false equal to 0 when the input signal is not equal to the specified constant You enter the constant with the Constant value parameter Block Parameters Compare To Constant Fixed Point Compare To Constant mask link how a signal compares to a constant Parameters Cocco aa Constant value Boo o Cancel Help Apply Operator Specify how the input is compared to the constant value Constant value Specify the constant value that the input is compared with Input Port Any data type supported by the blockset Output Port An 8 bit unsigned integer Direct Feedthrough Yes Scalar Expansion Yes 10 35 Compare To Zero Purpose Library Description Parameters and Dialog Box Characteristics See Also 10 36 Determine if a signal is equal to zero Logic Comparison The Compare To Zero block is a masked block that determines if a signal is equal to zero where e The output is true not 0 when the input signal is equal to zero e The output is false equal to 0 when the input signal is not equal to zero Block Parameters Compare To Zero r Fixed Point Compare To Zero mask link Determine how a signal compares to zero Parameters Cancel Help Apply
269. nt value m Parameters Constant value jod Output data type and scaling Specity via dialog y Output data type ex sfix 16 uint 8 float single sti 6 Output scaling pe or Slope Bias ev 279 E 1000 Output scaling Best Precision Vector wise I Override data type s with doubles IV Interpret vectors as 1 D Cancel Help Apply Constant value Constant value output by the block It can be a scalar or vector All members of the output vector must be the same data type Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling via back propagation Output data type Any data type supported by the Fixed Point Blockset Output scaling Radix point only or slope bias scaling Additionally if Constant value is specified as a vector it can be scaled using the constant vector scaling modes for maximizing precision These scaling modes are available only for generalized fixed point data types Override data type s with doubles If checked Output data type is overridden with doubles Constant Conversions Characteristics Interpret vectors as 1 D If checked a column or row matrix value for the Constant value parameter results in a vector output whose elements are the elements of the row or column The Constant value parameter is converted from a double to the specified output data type offline using round to nearest and saturati
270. nteger and fixed point data types c Multiplicative adjustments are carried out before additive adjustments d Number of Bits is determined before the precision or positive range is inherited from the reference signals 2 PosRange is one bit higher than the exact maximum positive range of the signal 3 The computed Number of Bits is promoted to the smallest allowable value that is greater than or equal If none exists then error m Parameters 1 Propagated data type i pro 1 1 IF any reference input is double output is doube x 1 2 If any reference input is single output is sne El 13 IsSigned isSignedi orIsSigned2 El 1 41 Number ofBits Base mas NumBits1 NumBits2 Z 1 4 2 Number of Bits Multiplicative adjustment fi 1 4 3 Number of Bits Additive adjustment fo 1 4 4 Number of Bits Allowable final values fi 128 2 Propagated scaling inherit via propagation rule y 2 1 1 Slope Base min Stopet Slope2 y 2 1 2 Slope Multiplicative adjustment fi 2 1 3 Slope Additive adjustment fo 2 2 1 Bias Base Biast y 2 2 2 Bias Multiplicative adjustment fi 2 2 3 Bias Additive adjustment fo TF Override data type s with doubles Cancel Help Ea 10 51 Data Type Propagation 10 52 Propagated data type Use the parameter list to propagate the data type via the dial og box or inherit the data typefrom the reference signals Use the edit field to specif
271. nts Y ou specify the number of breakpoints in the lookup table by typing nptsmax 21 Creating the Lookup Table Next type xdata ydata errworst fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth nptsmax Theempty brackets tell thefunction toignorethe parameter errmax which is not used in this example Omitting errmax causes the function fixpt_look1_func_approx to return a lookup table of size specified by nptsmax with the smallest worst case error 8 9 8 Producing Lookup Table Data 8 10 Thefunction returns a vector xdata with 21 points Y ou can find the maximum error for this set of pointsis given by typing errworst at the MATLAB prompt This returns errworst 5 1139e 004 Plotting the Results To plot the lookup table along with the errors type fixpt_look1_func_plot funcstr xdata xdt xscale ydata ydt yscale rndmeth The resulting plots are shown below Figure No 1 olx File Edit View Insert Tools Window Help DSUS RAAL OD Function sin 2 pi x Ideal red Fixed Point Lookup Approximation blue 1 Table uses 21 unevenly spaced data points Put The input is Unsigned 16 Bit with 16 bits right of binary point The output is Signed 16 Bit with 14 bits right of binary point Maximum Absolute Error 0 00051139 log2 MAE 10 9333 MAE yBit 8 3785 The least significant 4 bits of the output can be inacourate The most significant nonsign bit of the
272. nvolving Qa a divide by zero and zero divided by zero are possible In these cases the hardware will give some default behavior but you must make sure that these default responses give meaningful results for the embedded system Recommendations for Arithmetic and Scaling Summary From the previous analysis of fixed point variables scaled within the general slope bias encoding scheme you can conclude e Addition subtraction multiplication and division can be very involved unless certain choices are made for the biases and slopes e Radix point only scaling guarantees simpler math but generally sacrifices some precision e It is important to note that the previous formulas don t show that Constants and variables are represented with a finite number of bits Variables are either signed or unsigned The rounding and overflow handling schemes These decisions must be made before an actual fixed point realization is achieved 4 25 4 Arithmetic O perations Parameter and Signal Conversions The previous sections of this chapter together with Chapter 3 Data Types and Scaling describe how data types scaling rounding overflow handling and arithmetic operations areincorporated intothe Fixed Point Blockset With this knowledge you can define the output of a fixed point model by configuring fixed point blocks to suit your particular application However to completely understand the results generated by t
273. o Block Parameters on page 10 4 To avoid parameter saturation errors the automatic scaling script autofixexp employs a special rule for the Look Up Table block autofixexp modifies the scaling by using the output look up values in addition to the logged minimum and maximum simulation values This prevents the data from being saturated to different values The look up values are given by the Vector of output values parameter the YDataPoints variable Block Parameters Look Up Table m Fixed Point Look Up Table mask link Approximate a one dimensional function using a selected look up method m Parameters Vector of input values 55 Vector of output values tanh 5 5 Look Up Method Interpolation Use End Values x Output data type and scaling Specity via dialog x Output data type ex sfix 16 uint 8 float single ft 6 Output scaling Slope or Slope Bias ex 2 9 jeo I Lock output scaling so autoscaling tool can t change it Round toward Floor v I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Look Up Table Conversions Vector of input values The vector of input values must be the same size as the output vector and strictly monotonically increasing Vector of output values The vector of output values must be the same size as the input vector Look up metho
274. o introduces a cumulative downward bias in the result for positive numbers and a cumulative upward bias in the result for negative numbers That is all positive numbers are rounded to smaller positive 4 4 Limitations on Precision numbers while all negative numbers are rounded to smaller negative numbers Rounding toward zero is shown below Round Toward Zero 1 T T T 0 5 4 Positive numbers are rounded to smaller positive numbers OF J Negative numbers are rounded to smaller negative numbers 0 5 f 4 1 1 0 0 2 0 4 0 6 0 8 1 Time An example comparing rounding to zero and truncation for unsigned and two s complement numbers is given in Example Rounding to Zero Versus Truncation on page 4 9 Round Toward Nearest When rounding toward nearest the number is rounded to the nearest representable value This mode has the smallest errors associated with it and these errors are symmetric As a result rounding toward nearest is the most useful approach for most applications 4 5 4 Arithmetic O perations In MATLAB you can round to nearest using the round function Rounding toward nearest is shown below Round Toward Nearest 1 T T 0 5 j All numbers are rounded to the nearest representable number OF 4 0 5 J 1 0 0 2 0 4 0 6 0 8 1 Time Round Toward Ceiling When rounding toward ceiling bo
275. o max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Same as the input u Direct Feedthrough Yes Scalar Expansion Of inputs and gain Detect Change Purpose Library Description En Parameters and Dialog Box Characteristics Detect a change in a signal s value Edge Detect The Detect Change block is a masked block that determines if an input does not equal ts previous value where e The output is true not 0 when the input signal does not equal its previous value e The output is false equal to 0 when the input signal equals its previous value Block Parameters Detect Change Fixed Point Detect Change mask link If the input is does not equal its previous value then output TRUE otherwise output false Cancel Help Baal Input Port Any data type supported by the blockset Output Port An 8 bit unsigned integer Direct Feedthrough Yes Scalar Expansion Yes Vectorized Yes 10 67 Detect Decrease Purpose Library Description a Parameters and Dialog Box Characteristics See Also 10 68 Detect a decrease in a signal s value E dge Detect
276. o the workspace Conversions Thetable data is converted from doubles to the x data type This conversion is performed offline using round to nearest and saturation Refer to Parameter Conversions on page 4 27 for more information about parameter conversions Example For an example that illustrates the look up methods supported by this block see the example included in the Look Up Table block reference pages Characteristics Input Port s Any data type supported by the blockset Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion No See Also Look Up Table and related blocks 10 149 Look Up Table 2D Purpose Library Description VA 10 150 Approximate a two dimensional function using a selected look up method LookUp The Look Up Table 2 D block is a masked S function that computes an approximation to some function z f x y given x y z data points Thelook up method can use interpolation extrapolation or the original values of the inputs Also the x and y data vectors must be strictly monotonically increasing as described in the Look Up Table reference pages The Row parameter is a 1 by m vector of x data points the Col parameter is a 1 by n vector of y data points and the Table parameter is an m by n matrix of z data points Both the row and column vectors must be strictly monotonically increasing The block generates output based on the input values using one o
277. o the MATLAB command line For example suppose the block input is an 8 bit signed integer The range of this data typeis from 128 to 127 and the negation of 128 is not representable If the Saturate to max or min when overflows occur check box is checked then the negation of 128 is 127 If it is not checked then the negation of 128 remains at 128 Block Parameters Unary Minus Fixed Point Unary Minus mask link ay Minus of a Signal Parameters Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Input Port Any data type supported by the blockset Output Port Same as the input a nonzero bias is negated offline Direct Feedthrough No Scalar Expansion Of input or initial conditions 10 199 Unit Delay Purpose Library Description Remarks 10 200 Delay a signal one sample period Delays amp Holds The Unit Delay block is a masked S function that delays its input by the specified sample period This block is equivalent to the z discrete time operator The block accepts one input and generates one output both of which can be scalar or vector If the input is a vector all elements of the vector are delayed by the same sample period You specify the block output for the first sampling period with the Initial condition parameter Careful selection of this parameter can minimize unwanted output behavior The time between samples is spe
278. o the value of the control input e f you specify more than one data input the block behaves like a multi port switch The block output is the data input that corresponds to the value of the control input If at least one of the data inputs is a vector the block output is a vector Any scalar inputs are expanded to vectors e f theinputs are scalar the output is a scalar For a detailed description of all other block parameters refer to Block Parameters on page 10 4 Note The output data type is determined by the data input with the largest positive range The Index Vector block also in the Select library is another implementation of the MultiPort Switch block having different parameter settings 10 163 MultiPort Switch Parameters and Dialog Box Characteristics 10 164 Block Parameters MultiPort Switch gt Fixed Point Multi Port Switch mask link Switch output between different inputs based on value of input one m Parameters Number of input ports FF Use zero based indexing Output data type and scaling Inherit via internal rule y Round toward Floor as I Saturate to max or min when overflows occur IV Log minimums and maximums Cancel Help Apply Number of input ports The number of data inputs to the block Use zero based indexing Controls whether the first item has index zero or index one Output data type and scaling Inherit the output data
279. oals FixPtGain1 a3 Series Cascade Form Series Cascade Form In the canonical series cascade form the transfer function H z is written as a product of first order and second order transfer functions uZ _ e z This equation yields the canonical series cascade form shown below 2 Hohoho 2H 2 wick Factoring H z into H z where i 1 2 3 p can be done in a number of ways Using the poles and zeros of H z you can obtain H z by grouping pairs of conjugate complex poles and pairs of conjugate complex zeros to produce second order transfer functions or by grouping real poles and real zeros to produce either first order or second order transfer functions You could also group two real zeros with a pair of conjugate complex poles or vice versa Since there are many ways to obtain H z it is desirable to compare the various groupings to see which produces the best results for the transfer function under consideration H z H z H2 2 H3 Z H 2 For example one factorization of H z might be H z H4 Z H gt Z H p 2 1 bz1 p 1 8z1 fz2 l111 az1 11 1 021 d 22 i 1 i jt l Y ou must also takeinto consideration that the ordering of the individual H z s will lead to systems with different numerical characteristics You may want to try various orderings for a given set of H z s to determine which gives the best numerical characteristics 5 7 5 Realization Structures
280. ock has two input ports one for the input signal u and the other for the enable signal E When the enable signal E is on and the reset R is true the upper output signal is forced to equal the external reset signal RV The lower output signal is not affected until onetime step later at which timeit is equal tothe external reset signal RV at the previous time step The block uses the internal Initial condition only when the mode starts or when a parent enabled subsystem is used The internal Initial condition only affects the lower output signal The first output is only affected through feedback When the Enable signal is off the block is disabled and the state and output values do not change except for resets The enable signal is on when E is not O and off when E is 0 Theinput u and initial condition IC must be the same data type but can be any data type The output is the same data type as the inputs u and IC The reset R can be any data type Y ou specify the time between samples with the Sample time parameter A setting of 1 means the Sample time is inherited 10 219 Unit Delay With Preview Enabled Resetta ble External RV Parameters H Block Parameters Un h n Enabled Resettable Externa and Dialog Box E O 3 z m Fixed Point Unit Delay With Preview Enabled Resettable External RW mask Unit Delays With Preview have two outputs instead of just one Normally the first output equals the signal u and the second output is
281. of the plant output signal is shown below Thelimit cycleis nolonger present in the steady state confirmation of a poor A D design This means you 6 19 6 Tutorial Feedback Controller Simulation should replace the hardware amplify the signal or do some digital processing to better condition the signal Plotting fxpdemo_feedback outputs olx 2 5 2 4 2 3 2 2 Limit cycles removed 6 20 Building Systems and Filters Overview si o a eR i 7 2 RealizationsandDataTypes 2 2 7 2 Realizations and Scaling 2 7 2 Targeting an Embedded Processor 7 3 SizeAssumptions oaoa a a 7 3 Operation Assumptions 7 3 Design Rules aoaaa aa a 7 4 7 Building Systems and Filters Overview The Fixed Point Blockset provides several fixed point filter and system realizations These realizations are intended to be used as design templates so you can easily see how to build filters and systems that suit your particular application needs Realizations are provided for state space integrator derivative and lead or lag systems For more information about realization structures refer to Chapter 5 Realization Structures or the references included in Appendix B Realizations and Data Types In an ideal world where numbers calculations and storage of states have infinite precision and range there are virtually an infinite number of realizations for
282. of two spacing requires more points than even spacing 8 18 Summary of the Lookup Table Functions Summary of the Lookup Table Functions The following summarizes how to use the lookup table approximation functions 1 Define e The ideal function to be approximated e Therange xmin to xmax over which to find X and Y data e The fixed point implementation data type scaling and rounding method e The maximum acceptable error the maximum number of points and the spacing 2 Run the fixpt_look1_func_approx function to generate X and Y data 3 Usethe fixpt_look1_func_plot function to plot the function and error between the ideal and approximated function using the selected X and Y data and to calculate the error and the number of points used 4 Vary input criteria such as errmax nptsmax and spacing to produce sets of X and Y data that generate functions with varying worst case error number of points required and spacing 5 Compare results of the number of points required and maximum absolute error from various runs to choose the best set of X and Y data 8 19 8 Producing Lookup Table Data 8 20 Effect of Spacing on Speed Error and Memory Usage This section compares the implementations of lookup tables that use breakpoints whose spacing is uneven even and power of two This comparison is only valid when the breakpoints are not tunable If the breakpoints can be tuned in the generated code then all three c
283. og Box Characteristics See Also Bound the range of the input Nonlinear The Saturation Dynamic block is a masked block that bounds the range of the input signal to upper and lower saturation values The input signal outside of these limits saturates to one of the bounds where e The input below the lower limit is set to the lower limit e Theinput above the upper limit is set to the upper limit The input for the upper limit is the up port and the input for the lower limit is the lo port Block Parameters Saturation Dynamic Fixed Point Saturation Dynamic mask link ou the range of the input E Cancel Help Appi Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion Yes Saturation 10 185 Scaling Strip Purpose Library Description Sealing Strip Parameters and Dialog Box Characteristics 10 186 Remove scaling and map to a built in integer Data Type The Scaling Strip block strips the scaling off a fixed point signal It maps the input data type to the smallest built in data type that has enough data bits to hold the input The stored integer value of the input is the value of the output The output always has nominal scaling slope 1 0 and bias 0 0 so the output does not makea distinction between real world value and stored integer value Block Parameters Scaling Strip Fixed Point Scaling Strip mask
284. ogged to the workspace Characteristics Input Port Any built in Simulink data type Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion No See Also Gateway In and related blocks 10 106 Gateway Out Purpose Library Description fom gt Remarks Convert a Fixed Point Blockset data type to a Simulink data type Data Type The Gateway Out block is a masked S function that converts any data type supported by the Fixed Point Blockset to a Simulink data type The Output and Input to have equal parameter list controls how the output is treated The possible values are Real World Value and Stored Integer n terms of the general encoding scheme described in Scaling on page 3 5 Real World Value treats the output as V SQ B whereS is the slope and B is the bias Stored Integer treats the output as a stored integer Q Selecting Stored Integer may be useful in these circumstances e f you are generating code for a fixed point processor the resulting code only uses integers and does not use floating point operations e f you want to partition your model based on hardware characteristics For example part of your model may involve simulating hardware that produces integers as output Note f the fixed point signal is a true integer such as sint 8 or uint 16 then Real World Value and Stored Integer produce identical output values For more information about this p
285. oint data types Fixed point data types are characterized by their word size in bits and radix binary point The radix point is the means by which fixed point values are scaled Additionally e Unsigned and two s complement formats are supported e The fixed point word size can range from 1 to 128 bits e The radix point is not required to be contiguous with the fixed point word Floating point data types are characterized by their sign bit fraction mantissa field and exponent field The Fixed Point Blockset supports IEEE singles IEEE doubles and a nonstandard EEE style floating point data type Note You can create Fixed Point Blockset data types directly in the MATLAB workspace and then pass the resulting structure to a fixed point block or you can specify the data type directly with the block dialog box Integers You specify unsigned and signed integers with the uint and sint functions respectively 2 3 2 G etting Started For example to specify a 16 bit unsigned integer via the block dialog box you configure the Output data type parameter as uint 16 Tospecify a 16 bit signed integer you configure the Output data type parameter as sint 16 For integer data types the default radix point is assumed to lie to the right of all bits Fractional Numbers You specify unsigned and signed fractional numbers with the ufrac and sfrac functions respectively For example to configurethe output as a 16 bit unsigned
286. oint formulas for maximum precision are still valid The maximum precision representations are the most useful choices unless there is an overriding need to avoid any shifting The encoding of the constants is Ep KF 2 E 20 F2 KB B i E j 20 EZ resulting in the formula Q 2 0 08 2 Qy Inherited Scaling for Speed The number of arithmetic operations can be reduced with these choices e Set Ba KBy This eliminates one constant term e Set Fa KF and Ea Ep This sets the other constant term to unity The resulting formula is simply Qa Qb If the number of bits is different then either handling potential overflows or performing sign extensions is the only possible operations involved Recommendations for Arithmetic and Scaling Inherited Scaling for Maximum Precision The scaling for maximum precision does not need to be different than the scaling for speed unless the output has fewer bits than the input If this is the Case then saturation should be avoided by dividing the slope by 2 for each lost bit This will prevent saturation but will cause rounding to occur Division Division of values is an operation that should be avoided in fixed point embedded systems but it can occur in places Therefore consider the division of two real world values Va Viv These values are represented by the general slope bias encoding scheme described in Scaling on page 3 5 In a fixed point system the di
287. oints have spacing 278 The smallest breakpoint was zero so uAngle replaced the general case of uAngle SmallestBreakPoint Comparison To determine where the input is located with respect to the breakpoints the unevenly spaced case clearly requires much more code than the other two cases This code requires additional command ROM This ROM penalty can be reduced if many lookup tables share the binary search algorithm as a function Even if the code is shared the number of clock cycles required to determine the location of the input is much higher for the unevenly spaced cases than the other two cases If the code is shared then function call overhead decreases the speed of execution a little more In the evenly spaced case and the power of two spaced case you can determine the location of theinput with a single line of code The evenly spaced cased uses a general integer division The power of two case uses a shift instead of general division because the divisor is an exact power of two Without knowing the 8 23 8 Producing Lookup Table Data 8 24 specific processor to be used you cannot be certain that a shift is better than division Many processors can implement division with a single assembly language instruction so the code will be small However this instruction often takes many clock cycles to complete Quite a few processors do not provide a division instruction Division on these processors is implemented via repeate
288. omitted Using the parameters described the section Setting Function Parameters for the Lookup Table on page 8 6 the following examples illustrate the results of using different values for notsmax when you enter xdata ydata errworst fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth errmax numptsmax The results for three different settings for notsmax are as follows e numptsmax 33 The function creates the lookup table with 33 points having power of two spacing as in Example 3 numptsmax 21 Since the errmax and numptsmax conditions cannot be met with power of two spacing the function creates the lookup table with 20 points having even spacing as in Example 5 numptsmax 16 Since the errmax and numptsmax conditions cannot be met with either power of two or even spacing the function creates the lookup table with 16 points having unrestricted spacing as in Example 1 Comparing the Examples The following table summarizes the results for the examples Example Options Worst Case Error Number of Points in Table 1 errmax 2 10 unrestricted 27 10 16 2 nptsmax 21 unrestricted 2 10 933 21 3 errmax 2 10 even 2 10 0844 20 4 nptsmax 21 even 2 10 2209 21 5 errmax 2 10 pow2 2 11 3921 33 6 nptsmax 21 pow2 2 9 627 17 8 17 8 Producing Lookup Table Data Note that when you specify errmax even spacing requires more data points than unrestricted and power
289. ompared using the Plot System interface The procedure for this simulation and the simulation results are shown below Simulation Results Fixed Point Blockset Interface fxpt_feedback lolx Log Min Max Use block params Autoscale Safety Margin 0 0 Configure all blocks to output doubles Log Mode overwrite log Datatype Override Doubles override ON Data Scaling Up Cast FLT_S16 Nunerator Terms Denominator Terms Combine Terms A Down Cast FLT_S16 Block path fxpt_feedback Run Stop Autoscale Plot Help Close Launch the Plot System 2 Run the simulation interface The Plot System interface is shown below This simulation plots both the fixed point and ideal double precision signals for the plant output 6 13 6 Tutorial Feedback Controller Simulation CD Select the plant output PlantInput signal PlantOutput ReferenceSignal Plot Signals Plot Doubles Plot Both Cancel 2 Plot both the ideal and fixed point signals The ideal and fixed point plant output signals are shown below The deal signal is produced by overriding the block output scaling Plotting fxpdemo_feedback outputs Of x Ideal plant output Fixed point plant output signal 6 14 Simulation Results Simulation 3 Automatic Scaling Using the automatic scaling procedure you can easily maximize the precision of the output data type whilespan
290. on Round toward Rounding mode for the fixed point output 10 25 Accumulator Resetta ble Characteristics See Also 10 26 Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Same data type as the input u Direct Feedthrough Yes of the input and reset source ports Scalar Expansion Of inputs and gain Accumulator and related blocks Accumulator Resetta ble Limited Purpose Library Description Parameters and Dialog Box Compute a limited cumulative sum with external Boolean reset Calculus The Accumulator Resettable Limited block computes a cumulative sum based on the values of an external Boolean reset signal The block can reset ts state based on an external reset signal R When the cumulative sum reaches one of the limits given by the Upper limit and Lower limit parameters the sum saturates to that limit The block has two input ports one for the input signal u and another for the reset signal R When the reset R is false at time n the block adds the current value of the input signal u to the sum at time n 1 When the cumulative sum is outside the limits given by the Upper limi
291. on Refer to Parameter Conversions on page 4 27 for more information about parameter conversions Output Port Any data type supported by the blockset Direct Feedthrough No Scalar Expansion No the output is always the same size as Constant value 10 39 Conversion Purpose Convert from one Fixed Point Blockset data type to another Library Data Type Description The Conversion block is a masked S function that converts from one Fixed Point Blockset data type to another This block requires that you specify the data type and scaling for the conversion If you want to inherit this information from an input signal you should use the Conversion Inherited block For a detailed description of all block parameters refer to Block Parameters on page 10 4 For more information about converting from one Fixed Point Blockset data type to another refer to Signal Conversions on page 4 27 Parameters a nd Dia log Box Block Parameters Cony m Fixed Point to Fixed Point Conversion mask link Convert the input to the data type and scaling of the output The conversion has two possible goals One goal is to have the Real World Values of the input and the output be equal The other goal is to have the Stored Integer Values of the input and the output be equal Overflows and quantization errors can prevent the goal from being fully achieved The input and the output support all built in and fixed point data
292. on and quantization error in the modeling of dynamic digital systems With the Real Time Workshop you can generate production code based on that model 3 2 Fixed Point N umbers Fixed Point Numbers Fixed point numbers are stored in data types that are characterized by their word size in bits radix point and whether they are signed or unsigned The Fixed Point Blockset supports integers fractionals and generalized fixed point numbers The main difference between these data types is their default radix point Note Fixed point word sizes up to 128 bits are supported A common representation of a binary fixed point number either signed or unsigned is shown below radix point where e b are the binary digits bits e The size of the word in bits is given by ws e The most significant bit MSB is the leftmost bit and is represented by location bys 1 e The least significant bit LSB is the rightmost bit and is represented by location bo e The radix point is shown four places to the left of the LSB Signed Fixed Point Numbers Computer hardware typically represent the negation of a binary fixed point number in three different ways sign magnitude one s complement and two s complement Two s complement is the preferred representation of signed fixed point numbers and is supported by the Fixed Point Blockset 3 3 3 Data Types and Scaling 3 4 Negation using two s complement consists of a
293. on according to the method specified by Display The Display methods are given below Display Method Description on Display detailed block information outline Display the conversion process outline fixpt_ convert Remarks Display Method Description off Do not display block information filename Write detailed block information to the specified file on filename Display detailed block information and write detailed block information to the specified file outline filename Display the conversion process outline and write detailed block information to the specified file res fixpt_convert SystemName Display AutoSave determines the state of the converted model or subsystem If AutoSave is on then the converted model or subsystem is saved and closed If AutoSave is off then the converted model or subsystem is unsaved and left open If your Simulink model references blocks from a custom Simulink library then these blocks are encapsulated upon conversion A block is encapsulated when it cannot be converted to an equivalent fixed point block Encapsulation involves associating a Gateway In or a Gateway Out block with the Simulink block To reduce the number of blocks that are encapsulated you should convert the entire library by passing the library name to fixpt_convert and then convert the model To create a custom list of blocks to convert you should use the fixpt_convert_userpairs script Tolearn how
294. on of the resulting equation for the stored integer Qa is given by the equation in Addition on page 4 16 Using shorthand notation that equation becomes Ep Ea Ea E Qa i F b2 Qb az Fge2 Q Bret where F sp and F are the adjusted fractional slopes and Bre is the net bias The offline conversions and online conversions and operations are discussed below Offline Conversions F sp Fcc and Bng are computed offline using round to nearest and saturation Furthermore B pe is stored using the output data type Online Conversions and Operations The remaining operations are performed online by the fixed point processor and depend on the slopes and biases for the input and output data types The worst most inefficient case occurs when the slopes and biases are mismatched The worst case conversions and operations are given by these steps 1 Theinitial value for Q is given by the net bias Bne Qa Bret 2 Thefirst input integer value Qp is multiplied by the adjusted slope F sp 4 31 4 Arithmetic O perations 4 32 QrawProduct z F bQb 3 The previous produc is converted to the modified output data type where the slope is one and the bias is zero QTemp convert QRawProduct This conversion includes any necessary bit shifting rounding or overflow handling 4 Thesummation operation is performed Qa Q Qt emp This summation includes any necessary overflow handling 5 Steps 2 to4 arerepeated fo
295. on of two numbers deally the real world values obey the equation Va Vp Ve where Vp and V arethe input values and V is the output value To see how the division is actually implemented the three ideal values should be replaced by the general slope bias encoding scheme described in Scaling on page 3 5 For the case where the slopes are one and the biases are zero for all signals the solution of the resulting equation for the output stored integer Qa is given below Ep EzE Qa 2 p Qp Qo This equation involves an integer division and some bit shifts If E 2 Ep E w then any bit shifts aretotheright and the implementation is simple However if E lt E E then the bit shifts are to the left and the implementation can 4 39 4 Arithmetic O perations 4 40 be more complicated The essential issueis the output has more precision than the integer division provides To get full precision a fractional division is needed The C programming language provides access to integer division only for fixed point data types Depending on the size of the numerator some of the fractional bits may be obtained by performing a shift prior to the integer division In the worst case it may be necessary to resort to repeated subtractions in software In general division of values is an operation that should be avoided in fixed point embedded systems Division where the output has more precision than the integer division i e E lt
296. onal function using a selected look up method m Parameters Look Up Method MAA Dutput data type and scaling Specity viados y Output data type ex sfix 16 uint 8 float single stix 16 Output scaling Slope or Slope Bias ex 2 9 2 1 0 F Lock output scaling so autoscaling tool can t change it Round toward Floor X I Saturate to max or min when overflows occur TF Override data type s with doubles IV Log minimums and maximums Cancel i Help Apply Look up method Look up method Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling by back propagation Output data type Any data type supported by the Fixed Point Blockset Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generalized fixed point output Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Look Up Table Dynamic Override with data type s with doubles If checked the Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged t
297. onversion Inherited Parameters and Dialog Box Characteristics See Also Block Parameters Conversion Inherited r Fixed Point to Fixed Point Inherited Conversion mask link Convert the second input to the data type and scaling of the first input The conversion has two possible goals One goal is to have the Real World Values of the input and the output be equal The other goal is to have the Stored Integer Values of the input and the output be equal Overflows and quantization errors can prevent the goal from being fully achieved The both inputs and the output support all built in and fixed point data types Parameters Input and Output to have equal Pe Round toward Floor hd I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Input and Output to have equal Specify the type of value of the input and output that are to be equal Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the inherited data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Any data type supported by the blockset
298. onversions 4 26 Parameter Conversions ooocccocccoco eens 4 27 Signal ConverSionS 00000 cece eee eee 4 27 Rules for Arithmetic Operations 4 30 Computational Units 00 0000 c eee 4 30 Addition and Subtraction 0 0 02 c eee eee 4 30 iv Contents Multiplication Locura da as 4 35 DIVISION ata ER Adal HAG 4 39 SIMMS as tl Galata wen erat cid 4 41 Example Conversions and Arithmetic Operations 4 46 Realization Structures OVCrVICW cocos a rr hee on bet Reon wee Ee 5 2 Direct F orn beste rs Dieses Mawes ee Rees Bs 5 4 Series Cascade Form 0 0 c eee ees 57 Parallel FOr 6 263305 eee ee il ae 5 10 Tutorial Feedback Controller Simulation 6 Overview anea Boeke Ba Se a BI ee BB aa 6 2 Simulink Model of a Feedback Design 63 Idealized Feedback Design 00 0 c eee 6 6 Digital Controller Realization 6 7 Simulation Results 00 0000 eee 69 Simulation 1 Initial Guess at Scaling 6 9 Simulation 2 Global Override oooooccooccccooo 6 12 Simulation 3 Automatic Scaling s sssaaa aasan 6 15 Simulation 4 Individual Override oooooococoooo 6 18 Building Systems and Filters 7 A eta aa hee Ate oh Eta d id hate 7 2 Realizations and Data Types susua 0 000 ce eee eee 7 2 Realizations and Scaling
299. ope block output from the fxpdemo_feedback demo Plot system fxpdemo_feedback ME x Plant Input PlantOutput ReferenceSignal Plot Signals Plot Doubles Plot Both Cancel To plot the simulation results select one or more variable names and then select the appropriate plot button Y ou plot the raw signal data with the Plot Signals button Raw signal data is generated when the global override switch is off You plot doubles with the Plot Doubles button Doubles are generated when the global override switch is on You can plot both raw signal data and doubles with the Plot Both button Note that the doubles override does not overwrite the raw data To learn how to use the Fixed Point Blockset Interface tool refer to Simulation Results on page 6 9 autofixexp showfixptsimranges sfix Purpose Syntax Description Example See Also Create a MATLAB structure describing a signed generalized fixed point data type a sfix TotalBits sfix TotalBits returns a MATLAB structurethat describes the data type of a signed generalized fixed point number with a word size given by TotalBits sfix is automatically called when a signed generalized fixed point data type is specified in a block dialog box Note A default radix point is not included in this data type description Instead the scaling must be explicitly defined in the block dialog box Define a 16 bit signed generalized fixed point data t
300. or Slope Bias ex 2 9 aoo FF Lock output scaling so autoscaling tool can t change it Round toward Floor v I Saturate to max or min when overflows occur FT Override data type s with doubles IV Log minimums and maximums Cancel Help Apply FIR coefficients FIR coefficients One row per output Initial condition Initial values for all times preceding the start time 10 94 FIR Sample time Sample time Parameter data type Any data type supported by the Fixed Point Blockset Parameter scaling Radix point only or slope bias scaling Additionally the FIR coefficients vector or matrix can be scaled using the constant vector or constant matrix scaling modes for maximizing precision These scaling modes are available only for generalized fixed point data types Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling from the driving block or by back propagation Output data type Any data type supported by the Fixed Point Blockset Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generalized fixed point output Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur
301. or 10 23 Accumulator Resettable 10 25 Accumulator Resettable Limited 10 27 Bit Clear 10 29 Bit Set 10 30 Bitwise Operator 10 31 Compare To Constant 10 35 Compare To Zero 10 36 Constant 10 37 Conversion 4 43 10 40 Conversion Inherited 10 42 Cosine 10 44 Counter Free 10 45 Counter Limited 10 46 Data Type Duplicate 10 47 Data Type Propagation 10 49 Dead Zone 10 58 Dead Zone Dynamic 10 60 Decrement Real World 10 61 Decrement Stored I nteger 10 62 Decrement Time To Zero 10 63 Decrement To Zero 10 64 Derivative 10 65 Detect Change 10 67 Detect Decrease 10 68 Detect Fall Negative 10 69 Detect Fall Nonpositive 10 70 Detect Increase 10 71 Detect Rise Nonnegative 10 72 Index Detect Rise Positive 10 73 Difference 10 74 Dot Product 10 76 Filter Direct Form 1 10 78 Filter Direct Form Time Varying 10 81 Filter Direct Form II 10 83 Filter Direct Form II Time Varying 10 85 Filter First Order 10 87 Filter Lead or Lag 10 89 Filter Real Zero 10 91 FIR 4 47 10 93 Free Counter 10 97 Gain 4 45 10 97 Gateway In 2 2 10 100 Gateway In Inherited 10 105 Gateway Out 10 107 Increment Real World 10 110 Increment Stored Integer 10 111 Integer Delay 10 112 Integrator Backward 10 113 Integrator Backward Resettable 10 115 Integrator Backward Resettable Limited 10 117 Integrator Forward 10 120 Integrator F orward Resettable 10 122 Integrator F orward Resettable Limited 10 124 Integrator Trapezoidal 10 127 Integrato
302. or all blocks e Override the output data type with doubles for all blocks e Invoke the automatic scaling script To learn how to use the Fixed Point Blockset nterface tool refer to Chapter 6 Tutorial Feedback Controller Simulation Code Generation With the Real Time Workshop the Fixed Point Blockset can generate C code The code generated from fixed point blocks uses only integer types and automatically includes all operations such as shifts needed to account for differences in fixed point locations An O verview of Blockset Features Y ou can use the generated code on embedded fixed point processors or rapid prototyping systems even if they contain a floating point processor The code is structured so that key operations can be readily replaced by optimized target specific libraries that you supply Y ou can also usethe Target Language Compiler to customize the generated code Refer to Appendix A for more information about code generation using fixed point blocks 2 G etting Started Example Converting from Doubles to Fixed Point The purpose of this example is to show you how to simulate a continuous real world signal using a generalized fixed point data type The model used is the simplest possible model and employs only two fixed point blocks Although simple in design the model gives you the opportunity to explore many of the important features of the Fixed Point Blockset including e Data types e Scaling
303. or at any point of a function lookup table is the absolute value of the difference between the ideal function at the point and the corresponding Y value found by linearly interpolating between the adjacent breakpoints The worst caseerror or maximum absoluteerror of a lookup table is the maximum absolute value of all errors in the interval containing the breakpoints For example if theideal function is the square root and the breakpoints of the lookup table are 0 25 and 1 then in a perfect implementation of the lookup table the worst case error is 1 8 125 which occurs at the point 1 16 0625 In practice the error could be greater depending on the fixed point quantization and other factors Example Square Root Function This example shows how to use the function fixpt_look1_func_plot to find the maximum absolute error for the simple lookup table whose breakpoints are 0 25 and 1 The corresponding Y data points of the lookup table which you find by taking the square roots of the breakpoints are 0 5 and 1 To use the function fixpt_look1_func_plot you need to first define its parameters To do so type the following at the MATLAB prompt funcstr sqrt x Define the square root function xdata 0 25 1 Set the breakpoints ydata sqrt xdata Find the square root of the breakpoints xmin 0 Set the minimum breakpoint xmax 1 Set the maximum breakpoint xdt ufix 16 Set the x data type xscale 2 16 Set t
304. or if additional analysis is required 4 8 Limitations on Precision Example Rounding to Zero Versus Truncation Rounding to zero and truncation or chopping are sometimes thought to mean the same thing However the results produced by rounding to zero and truncation are different for unsigned and two s complement numbers To illustrate this point consider rounding a 5 bit unsigned number to zero by dropping truncating the two least significant bits For example the unsigned number 100 01 4 25 is truncated to 100 4 Therefore truncating an unsigned number is equivalent to rounding to zero or rounding to floor Now consider rounding a 5 bit two s complement number by dropping the two least significant bits At first glance you may think truncating a two s complement number is the same as rounding to zero For example dropping the last two digits of 3 75 yields 3 00 However digital hardware performing two s complement arithmetic yields a different result Specifically the number 100 01 3 75 truncates to 100 4 which is rounding to floor As you can see rounding to zero for a two s complement number is not the same as truncation when the original value is negative For this reason the ambiguous term truncation is not used in this guide and four explicit rounding modes are used instead Padding with Trailing Zeros Padding with trailing zeros involves extending the least significant bit LSB of anumber with ex
305. orm a shift with the Fixed Point Blockset using either the Conversion block or the Gain block The Conversion block shifts both the bits and radix point while the Gain block shifts the bits but not the radix point These two modes of shifting as well as shifting tothe right are discussed below Note Performinga plain or raw machine level shift such as those given in the example above with the Fixed Point Blockset is complicated by the available scaling options Therefore a single Shift block is not provided For more information about scaling refer to Scaling on page 3 5 4 Arithmetic O perations 4 42 Shifting to the Right Shifts to the right can be classified as a logical shift right or an arithmetic shift right For a logical shift right a 0 is incorporated into the most significant bit for each bit shift For an arithmetic shift right the most significant bit is recycled for each bit shift With the Fixed Point Blockset shifting to the right follows these rules e For signed numbers an arithmetic shift right is performed Therefore the most significant bit is recycled for each bit shift For example given the signed fixed point number 10110 101 a bit shift two places to the right with the radix point unmoved yields the number 11101 101 e For unsigned numbers a logical shift right is performed Therefore the most significant bit is a O for each bit shift For example given the unsigned fixed poin
306. ounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Characteristics Input Ports Any data type supported by the blockset Output Port Same as the input u Direct Feedthrough Yes Scalar Expansion Of inputs and gain See Also Integrator Backward and related blocks 10 126 Integrator Trapezoidal Purpose Library Description Perform discrete time integration of a signal using the trapezoidal method Calculus The Integrator Trapezoidal block performs a discrete time integration of a signal using the trapezoidal method At time step k the block computes the average of the inputs at times k 1 and k multiplies the average by the weighted sample time and adds the result to the cumulative sum since time zero The block outputs the sum up tothe k th time step at time The block calculates the output at time k by the rule y k y k 1 w k w k 1 where u k is the input at time k and K Ts 2 w k U k At the first time step y 0 is set to the value of Initial condition for previous output and w 0 is set to the value of Initial condition for previous weighted input K Ts u 2 10 127 Integrator Trapezoidal Pa
307. ously logged to the MATLAB workspace and changes the scaling for each block that does not have its scaling fixed 4 Performa simulation on the fixed hardware block by overriding the data type with doubles This simulation determines whether the A D hardware warrants modification or replacement The feedback controller simulation is performed with the Fixed Point Blockset Interface tool You launch the Interface tool by selecting the GUI block within the fxpdemo_feedback model by selecting Fixed Point from the Tools menu in the model window or by typing fxptdlg fxpdemo_feedback at the command line The four simulation trials are described in the following sections The quality of the simulation results is determined by examining the input and output of the analog plant Simulation 1 Initial Guess at Scaling Thefirst simulation uses guesses for the scaling In general you won t need to perform this step and this simulation is included to illustrate the difficulty of guessing at scaling 6 9 6 Tutorial Feedback Controller Simulation 6 10 After you launch the nterface tool press the Run button to run the simulation When the simulation is finished the interface displays the block name the maximum and minimum simulation results the data type and the scaling for each block You can then easily plot the results by pressing the Plot button which launches the Plot System interface The procedure for this simulation
308. output is used The remaining 11 nonsign bits of the output are used and always acourate The sign bit of the output is not used The rounding mode is to Floor Restricting the Spacing In the previous two examples the function fixpt_look1_func_approx creates lookup tables with unrestricted spacing between the breakpoints Y ou can Creating Lookup Tables for a Sine Function restrict the spacing toimprove the computational efficiency of the lookup table using the spacing parameter The options for spacing are e unrestricted The default e even The distance between any two adjacent breakpoints is the same e pow2 Thedistance between any two adjacent breakpoints is the same and is a power of two Both power of two and even spacing increase the computational speed of the lookup table and use less command ROM However specifying either of the spacing restrictions along with errmax usually requires more data points in the lookup table than does unrestricted spacing in order to achieve the same degree of accuracy The section Effect of Spacing on Speed Error and Memory Usage on page 8 20 discusses the trade offs between different spacing options Example 3 Using errmax with Even Spacing The next example shows how to create a lookup table that has evenly spaced breakpoints and a specified worst case error Totry the example you must first enter the enter the parameter values given in the section Setting Fu
309. ox by selecting Parameters under the Simulation menu In the Solver window configure Solver options to Fixed step and discrete no continuous states and configure Fixed step size tothe required value The Solver window for this configuration is shown below Simulation Parameters fxpdemo_code_only ME ES Solver Workspace 1 0 Diagnostics Advanced Real Time Workshop Simulation time Start time 0 0 Stop time 4 2tsamp Solver options Type Fixed step x discrete no continuous states y Fixed step size tsamp Mode SingleT asking y Output options Refine output Refine factor 1 Select the Real Time Workshop window in the Simulation Parameters dialog box Configure the System target file parameter to ert t1c The A Code Generation Template makefile and Make command parameters are automatically updated This configuration is shown below Simulation Parameters fxpdemo_code_only BBE Solver Workspace 1 0 Diagnostics Advanced RealTime Workshop Category Target configuration y Generate code Configuration System target file ert tle Browse Template makefile ert_default_tmf Make command make rw V Generate code only Stateflow options Launch the System Target F ile Browser by selecting the Browse button in the Configuration panel If it is available select Embedded C Real Time A 8 Generating Pure Integer Code Target as the system target file an
310. partitioned into two components e 2E specifies the radix point E is the fixed power of two exponent e F isthe fractional slope It is normalized such that 1 lt F lt 2 Note S andB are constants and do not show up in the computer hardware directly only the quantization value Q is stored in computer memory Thescaling modes available to you within this encoding scheme are described below For detailed information about how the supported scaling modes effect fixed point operations refer to Recommendations for Arithmetic and Scaling on page 4 16 3 5 3 Data Types and Scaling 3 6 Radix Point O nly Scaling As the name implies radix point only or powers of two scaling involves moving only the radix point within the generalized fixed point word The advantage of this scaling mode is the number of processor arithmetic operations is minimized With radix point only scaling the components of the general slope bias formula have these values e F 1 e S 2E e B 0 That is the scaling of the quantized real world number is defined only by the slope S which is restricted to a power of two Radix point only scaling is specified with the syntax 2 E where E is unrestricted This creates a MATLAB structure with a bias B 0 and a fractional slope F 1 0 For example the syntax 2 10 defines a scaling such that the radix point is at a location 10 places to the left of the least significant bit Slope Bias
311. pdate messages generated during the update process If message is 1 the default all messages are displayed If message is 0 all messages are suppressed fpupdate calls addterms to terminate any unconnected input or output ports by attaching Ground or Terminator blocks respectively Example To see how fpupdate works convert the obsolete model fixpoint obsolete fpex1 madl fpex1 fpupdate fpex1 9 27 fx ptdlig Purpose Syntax Description Parameters and Dialog Box 9 28 Launch the Fixed Point Blockset nterface tool fxptdlg model fxptdlg model launches the Fixed Point Blockset Interface tool for the fixed point M DL file model The interface provides convenient access to the global overrides and min max logging settings the logged min max data the automatic scaling script and the plot interface tool You can launch the Interface tool for as many different MDL files as you want and the tool controls only the specified model You can also invoke the nterface tool from the Tools menu in the model window or with the Fixed Point GUI block which is included with all blockset demos For each block in the model that logs data the nterface tool displays the block names the minimum simulation value the maximum simulation value the data type and the scaling Additionally if a signal saturates or overflows then a message is displayed for the associated block indicating how many times saturation or overf
312. pe the number of different bit patterns is 2W For example if the fixed point data type is an integer with scaling defined as S 1 and B 0 then the maximum unsigned value is 2 1 since zero must be represented In two s complement negative numbers must be represented as well as zero so the maximum value is 2 S 1 1 Additionally since there is only one representation for zero there must be an unequal number of positive and negative numbers This means there is a representation for 2 S but not for 2WS Precision The precision scaling of integer and fractional data types is specified by the default radix point F or generalized fixed point data types the scaling must be explicitly defined as either slope bias or radix point only In either case the precision is given by the slope 3 9 3 Data Types and Scaling 3 10 Fixed Point Data Type Parameters The low limit high limit and default radix point only scaling for the supported fixed point data types are given below Table 3 1 Fixed Point Data Type Range and Default Scaling Name Data Type Integer uint sint Fractional ufrac sfrac Generalized ufix Fixed Point E sfix Low Limit 0 2s _ 2Ws 1 0 T 2045 1 N A N A N A N A High Limit gws 1_ 1 Default Scaling Precision 1 1 2 ws La 2 ws 1 2 ws 1 N A N A Example Fixed Point Scaling The precision range of signed values and range of unsigned va
313. plies the input by a constant matrix referred to as the matrix gain The block generates its output by multiplying the input by a specified matrix y Ku where K is the matrix gain and u is the input If the matrix has m rows and n columns then the input to this block should bea vector of length n The output is a vector of length m You specify the matrix gain with the Gain matrix value parameter Y ou specify the scaling for the matrix gain with the Parameter scaling parameter Note that there are two dialog box parameters that control the matrix gain scaling one associated with an edit field and one associated with a parameter list If Parameter data type is a generalized fixed point number such as sfix 16 the Parameter scaling list provides you with these scaling modes e Use Specified Scaling This mode uses the slope bias or radix point only scaling specified for the editable Parameter scaling parameter for example 2 10 e UseBest Precision Element wise This mode produces radix points such that the precision is maximized for each element of the Gain matrix value matrix e UseBest Precision Row wise This mode produces a common radix point for each element of a Gain matrix value row based on the best precision for the largest value of that row e UseBest Precision Column wise This mode produces a common radix point for each element of a Gain matrix value column based on the best precision for the largest value of
314. ported by the blockset Input Port E Any data type supported by the blockset Input Port IC Same as the input u Output Port Same as the input u Unit Delay Enabled External IC Direct Feedthrough Yes of the reset input port No of the enable input port Yes of the external IC port Scalar Expansion Yes See Also Unit Delay and related blocks 10 205 Unit Delay Enabled Resettable Purpose Library Description Parameters and Dialog Box 10 206 Delay a signal one sample period Delays Holds The Unit Delay Enabled Resettable block combines the features of the Unit Delay Enabled and Unit Delay Resettable blocks The block can reset ts state based on an external reset signal R When the enable signal E is on and the reset signal R is false the block outputs the input signal delayed by one sample period When the enable signal E is on and the reset signal R is true the block resets the current state tothe initial condition specified by the Initial condition parameter and outputs that state delayed by one sample period When the enable signal is off the block is disabled and the state and output do not change except for resets The enable signal is on when E is not 0 and off when E is 0 Y ou specify the time between samples with the Sample time parameter A setting of 1 means the Sample time is inherited Block Parameters Unit Delay Enabled Resettable m Fixed Point Unit Delay Enabled Res
315. ption sini2 pfu P Parameters and Dialog Box Characteristics 10 188 Implement a sine wave in fixed point using a lookup table approach that exploits quarter wave symmetry Lookup The Sine block is a masked block that implements a sine wave in fixed point using a lookup table method that exploits quarter wave symmetry You can set the number of data points to retrieve from the lookup table with the Number of data points for lookup table parameter Block Parameters Sine r Fixed Point Sine mask link Implement a Sine function in Fixed Point using a lookup table approach that exploits quarter wave symmetry The output is normally a signed 16 bit number with 14 bits to the right of the binary point The most efficient implementation is obtained when the number of data points is a power of 2 plus 1 For example 2 5 1 Parameters Number of data points for lookup table 2 5 1 Cancel Help Apply Number of data points for lookup table Number of data points to retrieve from the lookup table Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion N A State Space Purpose Library Description y n Oxtn Duin xint1Axin Buln Implement discrete time state space Filters The State Space block implements the system described by y n Cx n Du n x n 1 Ax n Bu n where u is the input x is the sta
316. put Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap 10 87 Filter First Order Characteristics See Also 10 88 Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged tothe workspace Input Ports Any data type supported by the blockset it must be a scalar Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of initial conditions Vectorized No FIR and related blocks Filter Lead or Lag Purpose Library Description Parameters and Dialog Box Implement a discrete time lead or lag filter Filters TheF ilter Lead or Lag block implements a discrete time lead or lag filter of the input The instantaneous gain of the filter is one and the DC gain is equal to 1 z 1 p where z is the zero and p is the pole of the filter The block implements a lead filter when 0 lt z lt p lt 1 and implements a lag filter when 0 lt p lt z lt 1 Block Parameters Filter Lead or Lag r Fixed Point Filter Lead or Lag mask link Discrete time lead or lag filter of the input The filter has a unity instanteous gain the DC gain equals 1 Zero 1 Pole Lead action is obtained when 0 lt Pole lt Zero lt 1 Lag actio
317. put discrete time sequence and repeat interpolating between data points Library Sources Description The Repeating Sequence nterpolated block outputs a discrete time sequence and then repeats it Between data points the block uses the method specified AL 5 by the Look up Method parameter to determine the output Parameters a nd Dia log Box Block Parameters Repeating Sequence Interpolated r Fixed Point Repeating Sequence Interpolated mask link Discrete time sequence is output then repeated Between data points the specified lookup method is used to determine the output Parameters Vector of output values lt 1421 Vector of time values to 010506 1 Look Up Method Interpolation Use End Values Sample time joo Output data type and scaling Specity via dialog Output data type ex sfix 16 uint 8 float single sf 6 Output scaling Slope or Slope Bias ex 2 9 21 0 TF Override data type s with doubles Cancel Help Apply Vector of output values Column vector containing output values of the discrete time sequence Vector of time values Column vector containing time values The time values must be a strictly increasing and the vector must have the same size as the vector of output values 10 176 Repeating Sequence Interpolated Characteristics Look up Method Specify the lookup method to determine the output between data points Sample time Sa
318. put u using trapezoidal method with extemal boolean reset This block only works with fixed sample rates so it will not work inside a triggered subsystem m Parameters Gain value Poo Initial condition for previous output 0 Initial condition for previous weighted input K Ts u 2 00 a ee Output data type and scaling Inherit via intemalule Round toward Floor he I Saturate to max or min when overflows occur TF Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Gain value Specify the weight by which the sample time is multiplied Initial condition for previous output Set the initial condition for the previous output Initial condition for previous weighted input K Ts u 2 Set the initial condition for the previous weighted input Output data type and scaling The options are e Specify via dialog e Inherit via internal rule e Inherit via back propagation When Specify via dialog is selected you can specify the Output data type and Output scaling parameters 10 131 Integrator Trapezoidal Resettable Characteristics See Also 10 132 Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximu
319. put word sizes are much greater than one and the slope becomes b WSp WS E c WS WS F2 F2 F2 which depends only on the size of the input and output words The corresponding bias is a B min V F 2 min Q The value of the bias depends on whether the inputs and output are signed or unsigned numbers If the inputs and output are all unsigned then the minimum value for these variables are all zero and the bias reduces to a particularly simple form B B B a If the inputs and the output are all signed then the bias becomes ws 1 ws 1 ws 1 2 ws 1 C 4 A eho ea a a E B B B Radix Point O nly Scaling For radix point only scaling finding Qa results in this simple expression Recommendations for Arithmetic and Scaling E E E E Qa 2 Qpt2 Q This scaling choice results in only one addition and some bit shifting The avoidance of any multiplications is a big advantage of radix point only scaling Note The subtraction of values produces results that are analogous to those produced by the addition of values Accumulation The accumulation of values is closely associated with addition V Va_old Vb a_new Finding Qa new involves one multiply of a constant and a variable two additions and some bit shifting F B b 5E E b gt Ea Ae Qp 2 Qa new F gt The important difference for fixed point implementations is that the scaling of the outp
320. r in deciding to use one spacing method over another The subsequent sections assume that out of range inputs are impossible or have already been handled Determining the Location of the Input This section describes how the three fixed point lookup tables determine where the current input is relative to the breakpoints Uneven Case Unevenly spaced breakpoints require a general purpose algorithm such as a binary search to determine where the input lies in relation to the breakpoints The following code provides an example iLeft 0 iRght 7 number of breakpoints minus 1 while iRght iLeft gt 1 i iLeft iRght gt gt 1 if uAngle lt xuneven i iRght i else Effect of Spacing on Speed Error and Memory Usage iLeft i The while loop executes up to log2 N times where N is number of breakpoints Even Case Evenly spaced breakpoints require only one step to determine where the input lies in relation to the breakpoints iLeft uAngle 455U The divisor 455U represents the spacing between breakpoints In general the dividend would be uAngle SmallestBreakPoint In this example the smallest breakpoint was zero so the subtraction was optimized out Power of Two Case Power of two spaced breakpoints require only one step to determine wherethe input lies in relation to the breakpoints ileft uAngle gt gt 8 The number of shifts is 8 because the breakp
321. r 10 Block Reference If you want detailed information about a specific function refer to Chapter 9 Function Reference If You Are an Experienced User Start with Chapter 6 Tutorial Feedback Controller Simulation which describes how to simulate a fixed point digital controller design You should then read those parts of the guide that address the functionality that concerns you If you want detailed information about a specific block refer to Chapter 10 Block Reference If you want detailed information about a specific function refer to Chapter 9 Function Reference XV Preface xvi How This Book Is Organized The organization of this guide is described below Chapter Name Description Introduction Getting Started Data Types and Scaling Arithmetic Operations Realization Structures Tutorial Feedback Controller Simulation Building Systems and Filters Producing Lookup Table Data Function Reference Block Reference Code Generation Selected Bibliography Describes how the Fixed Point Blockset can help you bridge the gap between designing a dynamic system and implementing it on fixed point digital hardware Shows you how to use many Fixed Point Blockset features After reading this chapter you should be able to create simple fixed point models Describes fixed point data types floating point data types and data type scaling Describes fixed point ar
322. r Trapezoidal Resettable 10 130 Integrator Trapezoidal Resettable Limited 10 133 Interval Test 10 136 Interval Test Dynamic 10 138 Logical Operator 10 139 Look Up Table 10 141 Look Up Table 2 D 10 150 Look Up Table Dynamic 10 146 Matrix Gain 3 12 10 155 MinMax 10 159 Multiport Switch 10 163 Product 4 37 4 40 10 166 Rate Limiter 10 169 Rate Limiter Dynamic 10 170 Relational Operator 10 171 Relay 10 173 Repeating Sequence Interpolated 10 176 Repeating Sequence Stair 10 178 Sample Time Multiply 10 181 Saturation 10 184 Saturation Dynamic 10 185 Scaling Strip 10 186 Sign 10 187 Sine 10 188 State Space 10 189 Sum 4 33 10 192 Switch 10 195 Tapped Delay 10 197 Unary Minus 10 199 Unit Delay 10 200 Unit Delay Enabled 10 202 Unit Delay Enabled External IC 10 204 Unit Delay Enabled Resettable 10 206 Unit Delay Enabled Resettable E xternal IC 10 208 Unit Delay External IC 10 210 Unit Delay Resettable 10 211 Unit Delay Resettable External IC 10 213 Unit Delay With Preview Enabled 10 215 Unit Delay With Preview Enabled Resettable 10 217 Unit Delay With Preview Enabled Resettable External RV 10 219 Unit Delay With Preview Resettable 10 222 Index Unit Delay With Preview Resettable External RV 10 224 Wrap To Zero 10 226 Zero Order Hold 10 227 blockset library 10 12 Bode plot 6 6 boolean operation logical 10 139 broken links 9 24 built in data types 1 13 C ceil 4 7 chopping 4 9 de
323. r every number to be summed It is important to note that bit shifting rounding and overflow handling are applied to the intermediate steps 3 and 4 and not to the overall sum Streamlining Simulations and Generated Code If the scaling of the input and output signals is matched the number of summation operations is reduced from the worst most inefficient case F or example when an input has the same fractional slope as the output step 2 reduces to multiplication by one and can be eliminated Trivial steps in the summation process are eliminated for both simulation and code generation Exclusive use of radix point only scaling for both input signals and output signals is a common way to eliminate the occurrence of mismatched slopes and biases and results in the most efficient simulations and generated code Example The Summation Process Suppose you want to sum three numbers Each of these numbers is represented by an 8 bit word and each has a different radix point only scaling Additionally the output is restricted to an 8 bit word with radix point only scaling of 2 Rules for Arithmetic O perations The summation is shown below for the input values 19 875 5 4375 and 4 84375 FixPt Constant Qa ufix8_En3 FixPt Constant1 4 8427 E FixPt Constant2 Display Gateway Out Sum ufix8_En5 Applying the rules from the previous section the sum follows these steps 1 Since the biases a
324. r inherit the data type and scaling from the driving block or by back propagation Conversions and Operations Characteristics Output data type Any data type supported by the Fixed Point Blockset Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generalized fixed point output Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the Parameter data type and Output data type values are overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace The Gain value parameter is converted from doubles to the specified data type offline using round to nearest and saturation Refer to Parameter Conversions on page 4 27 for more information about parameter conversions The Gain block first multiples its inputs by the Gain value parameter and then converts those results tothe output data type using the specified rounding and overflow modes Refer to Rules for Arithmetic Operations on page 4 30 for more information about the rules this block adheres to when performing operations
325. r the number of inputs since this is the default operation Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling from the driving block or by back propagation Output data type Any data type supported by the Fixed Point Blockset Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generalized fixed point output 10 167 Product Operations Characteristics 10 168 Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace TheProduct block first performs the specified multiply or divide operations on the inputs and then converts the results to the output data type using the specified rounding and overflow modes Refer to Rules for Arithmetic Operations on page 4 30 for more information about the rules this block adheres to when performing operations Input Ports Any data type supported by the blockset Output Port Any data t
326. rameters Treat input as Stored Integer x Output data type ex sfix 16 uint 8 float single stix 8 Output scaling Slope or Slope Bias ex 2 9 2 4 IV Lock output scaling so autoscaling tool can t change it Hound toward Fo or z I Seturate to may ormin when overlows occur T Override data type s with doubles Log minimums and maximums E Cancel Precede all Gateway In blocks with root level Inport blocks and configure the blocks to usethe appropriate integer data type For example the Inport block shown above is configured to use the built in int8 data type 3 Insert Gateway Out Blocks as needed Changethe Treat input as parameter from Real World Value toStored Integer This does not change the signal s value but it is needed to strip fixed point scaling information from the integer Also configure the Generating Pure Integer Code Output date type parameter to usethe appropriate integer data type The Gateway Out block dialog box for this configuration is shown below Block Parameters UnT ag Fixed Point Gateway Out mask flink ES from a Fixed Point Blockset data type to a Simulink built in data type Parameters Treat output as Stored Integer v Dutput data type int16 y Cancel Help Follow all Gateway Out blocks with root level Outport blocks 4 Configure the simulation parameters Launch Simulink s Simulation Parameter s dialog b
327. rameters a nd Dia log Box Block Parameters Integrator Trapezoidal m Fixed Point Integrator Trapezoidal mask link Discrete time integration of the input using trapezoidal method This block only works with fixed sample rates so it will not work inside a triggered subsystem m Parameters Gain value Fe Initial condition for previous output 0 Initial condition for previous weighted input K Ts u 2 po Output data type and scaling Inherit via intemalule y Round toward Floor y I Saturate to max or min when overflows occur T Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Gain value Specify the weight by which the sample time is multiplied Initial condition for previous output Set the initial condition for the previous output Initial condition for previous weighted input K Ts u 2 Set the initial condition for the previous weighted input Output data type and scaling The options are e Specify via dialog e Inherit via internal rule e Inherit via back propagation When Specify via dialog is selected you can specify the Output data type and Output scaling parameters Round toward Rounding mode for the fixed point output 10 128 Integrator Trapezoidal Characteristics See Also Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If c
328. rator Backward and related blocks 10 119 Integrator Forward Purpose Library Description K Ts b z 1 Remarks Parameters and Dialog Box 10 120 Perform discrete time integration of a signal using the forward method Calculus The Integrator Forward block performs a discrete time integration of a signal using the forward method The block multiplies the input by the weighted sample time and adds the result to the cumulative sum since time zero The block outputs the sum up tothe nth time step at time n 1 The first term of the sum is the Initial condition for previous output parameter The output of the Integrator F orward block differs from the output of the Integrator Backward block only by the first and last terms in the cumulative sum Block Parameters Integrator Forward gt Fixed Point Integrator Forward mask link Discrete time integration of the input using forward method This block only works with fixed sample rates so it will not work inside a triggered subsystem m Parameters Gain value io OOO Initial condition for previous output 0 0 Dutput data type and scaling Inherit viaintemalule 7 Round toward Floor E I Saturate to max or min when overflows occur TF Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Gain value Specify the weight by which the sample time is multiplied Initial condition for previous output Set
329. rd bits 4 15 9 32 9 36 Index GUI block 9 28 See also fixed point interface tool H help 1 18 hidden bit 3 18 l icon labels 10 10 IEEE floating point numbers format double precision 3 19 exponent 3 18 fraction 3 18 nonstandard 3 20 sign bit 3 18 single precision 3 19 precision 3 21 range 3 20 infinity 3 23 4 12 inherited data types 10 5 by back propagation 10 49 scaling 10 7 by back propagation 10 49 Simulink to fixed point conversion 10 105 installation xvii integer delay 10 112 integers 2 3 and code generation A 5 outputting large values 10 107 interface L least significant bit 3 3 library 10 12 limit cycles 4 2 and feedback controller demo 6 17 lock output scaling 10 8 and feedback controller demo 6 17 logging large integer values 10 107 overflows 10 9 simulation results 9 29 10 9 logical operation 10 139 logical shift 4 42 look up table 1 D 10 141 2 D 10 150 LSB Seeleast significant bit M MAC s 4 30 propagating data type information for 10 54 masking bits 10 32 matrix gain 10 155 matrix signals 1 17 maximum value 10 159 logging 10 9 measurement scales 1 2 mex Xiii minimum value 10 159 logging 10 9 modeling the system 1 12 most significant bit 3 3 MSB 3 3 multiplication 10 166 blockset rules 4 35 scaling recommendations 4 20 4 21 Index using slope bias encoding 4 20 multiport switch 10 163 N NaNs 3 23 4 12 nonstandard IEEE format 3 20 0 offline conversion 4 27 for a
330. re is useful when debugging a simulation For example if you are simulating hardware that is constrained to output integers you can override the constraint to determine whether the hardware warrants modification or replacement 2 G etting Started Logging Simulation Values By checking the Log minimums and maximums check box you can save the maximum and minimum values encountered during a simulation to the MATLAB workspace You can then access these values with the automatic scaling script autofixexp Additional Features and Capabilities In addition to the features described in Configuring Fixed Point Blocks on page 2 2 the Fixed Point Blockset provides you with these features and capabilities e An automatic scaling tool e Code generation capabilities Automatic Scaling Y ou can use the autofixexp script to automatically change the scaling for each block that has generalized fixed point output and does not have its scaling locked The script uses the maximum and minimum values logged during the last simulation run The scaling is changed such that the simulation range is covered and the precision is maximized Asan alternativeto and extension of the automatic scaling script you can use the Fixed Point Blockset nterface tool This tool allows you to easily control the parameters associated with automatic scaling and display the simulation results for a given model Additionally you can e Turn on or turn off logging f
331. re matched the initial value of Q is trivial Q 00000 000 2 The first number to be summed 19 875 has a fractional slope that matches the output fractional slope Furthermore the radix points and storage types are identical so the conversion is trivial Qp 10011 111 Qtemp Q 3 Thesummation operation is performed Qa Q3 Qremp 10011 111 4 Thesecond number to be summed 5 4375 has a fractional slope that matches the output fractional slope soa slope adjustment is not needed The storage data types also match but the differencein radix points requires that both the bits and the radix point be shifted one place to the right 4 33 4 Arithmetic O perations 4 34 Q 0101 0111 QTemp convert Q Qtemp 00101 011 Note that a loss in precision of one bit occurs with the resulting value of QT emp determined by the rounding mode For this example round to floor is used Overflow cannot occur in this case since the bits and radix point are both shifted to the right 5 Thesummation operation is performed Qa Qat Qtemp 10011 111 _ _ 00101 011 11001 010 25 250 Note that overflow did not occur but it is possible for this operation The third number to be summed 4 84375 has a fractional slope that matches the output fractional slope soa slope adjustment is not needed The storage data types also match but the differencein radix points requires that both the bits and the radix point be shifted two places to
332. re must take into account that the sign exponent and fraction are all encoded within the same binary word This results in complex logic circuits when compared with the circuits for binary fixed point operations The Fixed Point Blockset supports single precision and double precision floating point numbers as defined by the IEEE Standard 754 Additionally a nonstandard EEE style number is supported To link the world of fixed point numbers with the world of floating point numbers the concepts behind scientific notation are reviewed below Scientific Notation A direct analogy exists between scientific notation and radix point notation For example scientific notation using five decimal digits for the fraction would take the form d ddddx 10 ddddd 0x 10P7 0 ddddd x 10 where p is an integer of unrestricted range Radix point notation using five bits for the fraction is the same except for the number base b bbbbx 2 bbbbb 0x 2974 0 bbbbb x 29 where q is an integer of unrestricted range The previous equation is valid for both fixed and floating point numbers F or both these data types the fraction can be changed at any time by the processor However for fixed point numbers Floating Point N umbers the exponent never changes whilefor floating point numbers the exponent can be changed any time by the processor For fixed point numbers the exponent is fixed but there is no reason why the radix point mu
333. right When the box is checked the Upper limit is included in the interval for which the block outputs TRUE Upper limit The upper limit of the interval for which the block outputs TRUE Interval closed on left When the box is checked the Lower limit is included in the interval for which the block outputs TRUE Lower limit The lower limit of the interval for which the block outputs TRUE Interval Test Characteristics Input Ports Any data type supported by the blockset Output Port Same data type as input Direct Feedthrough Yes Scalar Expansion Yes 10 137 Interval Test Dynamic Purpose Determine if a signal is in a specified interval Library Logic amp Comparison Description The Interval Test Dynamic block outputs TRUE if the input is between the values of the external signals up and lo The block outputs FALSE if theinput is outside those values The output of the block when the input is equal to the signal up or the signal lo is determined by whether the boxes next to Interval closed on left and Interval closed on right are checked in the dialog box Parameters a nd Dia log Box Block Parameters Interval Test Dynamic m Fixed Point Interval Test Dynamic mask link If the input is in the interval between the lower limit and the upper limit then the output is TRUE otherwise itis FALSE IV Interval closed on left Cancel Help Apply Interval closed on right When the box
334. rride This menu controls overriding the output data type for all blocks in a system Doubles override on overrides for all blocks the integer part of the fixed point number with doubles Doubles override off turns off the Override data type s with doubles for all blocks so that the data type cannot be overwritten with doubles if the check box is checked Use block params overrides the output data type with doubles for blocks that havethe Override data type s with doubles check box checked True doubles overrides for all blocks the output data type with doubles True singles overrides for all blocks the data type with singles for all blocks Block path Displays the path for each selected block The block path is described in terms of the blockset model name and if required the subsystem names The Fixed Point Blockset Interface tool contains six buttons Run Stop Autoscale Plot Help and Close The Run button runs the model and updates 9 29 fx ptdlig Example See Also 9 30 the display with the latest simulation information The Stop button stops the simulation from running The Autoscale button invokes the automatic scaling script autofixexp The Plot button invokes the Plot System interface which displays any To Workspace Outport or Scope blocks found in the model The Help button displays the HTM L based help The Close button closes the Interface tool The Plot System interface is shown below It is displaying Sc
335. rts those results to the output data type using the specified rounding and overflow modes and then performs the summation Refer to Rules for Arithmetic Operations on page 4 30 for more information about the rules this block adheres to when performing operations 10 157 Matrix Gain Characteristics 10 158 Input Ports Output Port Direct Feedthrough Scalar Expansion Any data type supported by the blockset Any data type supported by the blockset Yes No MinMax Purpose Library Description Output the minimum or maximum input value Math The MinMax block is a masked S function that outputs either the minimum or the maximum element of the inputs You can choose which function to apply with the Function parameter list Y ou specify the number of input ports with the Number of input ports parameter If the block has one input port the input must bea scalar or a vector The block outputs a scalar equal to the minimum or maximum element of the input vector If the block has multiple input ports the non scalar inputs must all have the same dimensions The block expands any scalar inputs to have the same dimensions as the non scalar inputs The block outputs a signal having the same dimensions as the input Each output element equals the minimum or maximum of the corresponding input elements For a detailed description of all other block parameters refer to Block Parameters on page 10 4 10 159 MinMa
336. s and minimizes the worst case error for a specified maximum number of points To try the example you must first enter the parameter values given in thesection Setting F unction Parameters for the Lookup Table on page 8 6 if you have not already done so in this MATLAB session Next type at the MATLAB prompt spacing even xdata ydata errworst fixpt_look1 func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth nptsmax spacing The result requires 21 evenly spaced points to achieve a maximum absolute error of 2 10 2209 Creating Lookup Tables for a Sine Function To plot the lookup table along with the errors type fixpt_look1_func_plot xdata ydata funcstr xmin xmax xdt xscale ydt yscale rndmeth lt Figure No 1 of x File Edit View Insert Tools Window Help JDSMS AAS PED Function sin 2 pi x Ideal red Fixed Point Lookup Approximation blue Absolute Error yb OO o o Table uses 21 evenly spaced data points Input The input is Unsigned 16 Bit with 16 bits right of binary point The output is Signed 16 Bit with 14 bits right of binary point Maximum Absolute Error 0 00083793 log2 MAE 10 2209 MAE yBit 13 7287 The least significant 4 bits of the output can be inacourate The most significant nonsign bit of the output is not used The remaining 10 nonsign bits of the output are used and always acourate The sign bit of the output is not used The rounding mo
337. s equal to the specified constant Determine if a signal is equal to zero Determine if a signal is in a specified interval Determine if a signal is in a specified interval Perform the specified logical operation on the inputs Perform the specified relational operation on the inputs LookUp Cosine Implement a cosine function in fixed point using a lookup table approach that exploits quarter wave symmetry Look Up Table Approximate a one dimensional function usinga selected look up method Look Up Table Provide a region of zero output Dynamic Look Up Table 2 D Sine Approximate a two dimensional function usinga selected look up method Implement a sine function in fixed point using a lookup table approach that exploits quarter wave symmetry The Fixed Point Blockset Libraries Math Blocks Abs Decrement Real World Decrement Stored Integer Decrement Time To Zero Decrement To Zero Gain Increment Real World Increment Stored I nteger Matrix Gain MinMax MinMax Running Resettable Product Sum Unary Minus Output the absolute value of the input Decrease the real world value of the signal by one Decrease the stored value of a signal by one Decrease the real world value of the signal by the sample time but only to zero Decrease the real world value of a signal by one but only to zero Multiply the input by a constant Increase the real world value o
338. s overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Same data type as the input u Direct Feedthrough Yes of the input and reset source ports Scalar Expansion Of inputs and gain Accumulator and related blocks Bit Clear Purpose Library Description Gear bit O p gt Parameters and Dialog Box Example Characteristics Set the specified bit of the stored integer to zero Bits The Bit Clear block is a masked block that sets the specified bit given by its index of the stored integer to zero Scaling is ignored Y ou can specify the bit to be set to zero with the Index of bit parameter where bit zero is the least significant bit True floating point data types are not supported Block Parameters Bit Clear Fixed Point Bit Clear mask link Es ith bit of the stored integer to 0 Scaling is ignored Index of bit 0 is least significant Parameters e Cancel Help App Index of bit Index of bit where bit 0 is the least significant bit If the Bit Clear is turned on for bit 2 bit 2 is set to 0 A vector of constants 2 510 1 2 3 4 s represented in binary as 00001 00010 00100 01000 10000 With bit 2 set to 0 the result is 00001 00010 00000 01000 10000 which is represented in decimal as 1 2 0 8 16 Input Port Any data type
339. sample period The block has twoinput ports onefor the input signal u and the other for the enable signal E When the enable signal E is off the block is disabled and the state and output values do not change except for resets The enable signal is on when E is not 0 and off when E is 0 Theinput u and initial condition IC must be the same data type but can be any data type The output is the same data type as the inputs u and IC The reset R can be any data type Y ou specify the time between samples with the Sample time parameter A setting of 1 means the Sample time is inherited Block Parameters Unit Delay With Preview Enabled r Fixed Point State Enabled mask link the first output equals the signal u and the second output is a unit delayed version of the first output Having both signals is useful for implementing recursive calculations where the result should include the most recent inputs The second output of a Unit Delay With Preview can be safely feedback into calculations of the block s inputs without causing an algebraic loop Meanwhile the first output will show the most up to date calculations When the enable signal is false the block is disabled and the state and output values do not change except for resets The enable action is vectorized and supports scalar expansion Parameters Initial condition ee Sample time ee Unit Delays With Preview have two outputs instead of just on
340. shown below Overflows Saturate 8 T T T Negative values Negative values saturateto zero saturate to zero 1 0 8 1 2 1 6 2 Time 4 13 4 Arithmetic O perations 4 14 If overflows wrap all negative values are set to the appropriate positive val ue The wrapping of overflows is shown below Overflows Wrap 8 T T Negative values Negative values wrap to positive wrap to positive values values 0 1 0 0 4 0 8 1 2 1 6 2 Time Note For most control applications saturation is the safer way of dealing with fixed point overflow However some processor architectures allow automatic saturation by hardware If hardware saturation is not available then extra software is required resulting in larger slower programs This cost is justified in some designs perhaps for safety reasons Other designs accept wrapping to obtain the smallest fastest software Limitations on Range Guard Bits Y ou can eliminate the possibility of overflow by appending the appropriate number of guard bits to a binary word For a two s complement signed value the guard bits arefilled with either 0 s or 1 s depending on the value of the most significant bit MSB This is called sign extension For example consider a 4 bit two s complement number with value 1011 If this number is extended in rangeto 7 bits with sign extension then the number becomes 1111101 and the value remains the same Guard bi
341. sing the constant matrix scaling modes for maximizing precision These scaling modes are available only for generalized fixed point data types Matrix Gain Conversions and Operations Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling from the driving block or by back propagation Output data type Any data type supported by the Fixed Point Blockset Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generalized fixed point output Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data types s with doubles If checked the Parameter data type and Output data type values are overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace The Gain matrix value parameter is converted from doubles to the specified data type offline using round to nearest and saturation Refer to Parameter Conversions on page 4 27 for more information about parameter conversions The Matrix Gain block first multiples its inputs by the Gain matrix value parameter conve
342. sing the trapezoidal method Perform discrete time integration of a signal using the trapezoidal method with external Boolean reset Perform discrete time limited integration of a signal using the trapezoidal method with external Boolean reset Support calculations involving sample time Data Type Conversion Conversion nherited Data Type Duplicate Data Type Propagation Gateway In Convert from one Fixed Point Blockset data type to another Convert from one Fixed Point Blockset data type to another and inherit the data type and scaling Set all inputs to the same data type Configure the data type and scaling of the propagated signal based on information from the reference signals Convert a Simulink data type to a Fixed Point Blockset data type The Fixed Point Blockset Libraries Data Type Gateway In Inherited Gateway Out Scaling Strip Convert a Simulink data type to a Fixed Point Blockset data type and inherit the data type and scaling Convert a Fixed Point Blockset data type toa Simulink data type Remove scaling and map toa built in integer Delays amp Holds Integer Delay Tapped Delay Unit Delay Unit Delay Enabled Unit Delay Enabled External IC Unit Delay Enabled Resettable Unit Delay Enabled Resettable External IC Unit Delay External IC Unit Delay Resettable Unit Delay Resettable External IC Unit Delay With Preview Enabled Dela
343. st be contiguous with the fraction For example a word consisting of three unsigned bits is usually represented in scientific notation in one of these four ways bbb bbb x 2 bb b bbb x 27 b bb bbb x 27 bbb bbb x 2 If the exponent were greater than 0 or less than 3 then the representation would involve lots of zeros bbb00000 bbb x 2 bbb00 bbb x 2 00bbb bbb x2 00000bbb bbb x 2 However these extra zeros never change to ones so they don t show up in the hardware Furthermore unlike floating point exponents a fixed point exponent never shows up in the hardware so fixed point exponents are not limited by a finite number of bits Note Therestriction of the radix point being contiguous with the fraction is unnecessary and the Fixed Point Blockset allows you to extend the radix point to any arbitrary location 3 17 3 Data Types and Scaling 3 18 The IEEE Format ThelEEE Standard 754 has been widely adopted and is used with virtually all floating point processors and arithmetic coprocessors with the notable exception of many DSP floating point processors Among other things this standard specifies four floating point number formats of which singles and doubles are the most widely used Each format contains three components a sign bit a fraction field and an exponent field These components as well as the specific formats for singles and doubles are discussed
344. t bo COC Upper limit eo Lower limit fs Output data type and scaling Inherit viaintemalule Round toward Floor I Saturate to max or min when overflows occur TF Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Gain value Specify the weight by which the sample time is multiplied Initial condition for previous output Set the initial condition for the previous output Upper limit The upper limit for saturation of the cumulative sum Lower limit The lower limit for saturation of the cumulative sum Output data type and scaling The options are e Specify via dialog e Inherit via internal rule e Inherit via back propagation 10 118 Integrator Backward Resetta ble Limited Characteristics See Also When Specify via dialog is selected you can specify the Output data type and Output scaling parameters Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Same as the input u Direct Feedthrough Yes of the input and reset source ports Scalar Expansion Of inputs and gain Integ
345. t and Lower limit parameters the sum saturates to one of the bounds When the reset R is true at time n the block resets the sum to the value of the Initial condition for previous output parameter and outputs the sum Block Parameters Accumulator Resettable Limited m Fixed Point Accumulator Resettable Limited mask link Limited running sum of all input u values with external boolean reset Parameters Initial condition for previous output ee Upper limit Lower limit fas Output data type and scaling Inherit via internal rule x Round toward Floor y I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Cancel Help Epp Initial condition for previous output Set the initial condition for the previous output Accumulator Resetta ble Limited Characteristics See Also 10 28 Upper limit The upper limit for saturation of the cumulative sum Lower limit The lower limit for saturation of the cumulative sum Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling from the driving block or by back propagation Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type i
346. t by 2 bits z1 0000110 1 6 5 Shift left by 2 bits 2 110 10100 6 625 The figure below shows the fixed point model used to generate the above data FixPt FixPt Display Conversion Gateway Out ufix8 En3 6 625 Shift bits and radix point E two places to the right FixPt Constant FixPt FixPt Display1 Conversion1 Gateway Outi Shift bits and radix point two places to the left Refer to Chapter 10 Block Reference for more information about the Conversion block Shifting Bits but Not the Radix Point With the Gain block you can perform a shift operation on the input by specifying the gain as a power of two This block shifts only the bits and not the radix point 4 Arithmetic O perations 4 44 In most cases you will perform a plain or raw shift To perform such a shift using the Gain block you must configure the block s dialog box this way e The output data type is identical to the input data type e The rounding mode is set to Floor Therefore bits simply fall off the left or fall off the right when a shift occurs e Overflows wrap e The gain is specified as the appropriate power of 2 to reflect the required shift For example suppose you start with the same fixed point number 00110 101 defined above To shift the bits two places to the left a gain of 4 is specified and to shift the bits two places to the right a gain of 0 25 is specified This situation is shown below Shift Op
347. t data types you can set the output scaling with the Output scaling parameter and below that parameter select the method for scaling the output with the Output scaling parameter For a detailed description of all block parameters refer to Block Parameters on page 9 4 For more information about converting from one Fixed Point Blockset data type to another refer to Signal Conversions on page 4 26 Repeating Sequence Stair Parameters and Dialog Box Block Parameters Repeating Sequence Stair m Fixed Point Repeating Sequence Stair mask link Discrete time sequence is output then repeated m Parameters Vector of output values fgv42y Sample time eT Output data type and scaling Specify viadiog y Output data type ex sfix 16 uint 8 float single aa Output scaling Slope or Slope Bias ex 2 9 2 12 I Lock output scaling so autoscaling tool can t change it Output scaling Best Precision Vector wise P Override data typefs with doubles Cancel Help Apply Vector of output values Vector containing values of the repeating stair sequence Sample time Sample time Output data type and scaling Specify the output data type and scaling via the dialog box or by inheriting the data type and scaling by back propagation Output data type Any data type supported by the blockset Output scaling Slope or slope bias scaling Lock output scaling so autoscaling too
348. t number 10110 101 a bit shift two places to the right with the radix point unmoved yields the number 00101 101 Shifting Bits and the Radix Point With the Conversion block you can perform a shift operation on the input by specifying the appropriate radix point only scaling for the output This block shifts both the bits and the radix point In most cases you will perform a plain or raw shift To perform such a shift using the Conversion block you must configure the bl ock s dialog box this way e The output data type is identical to the input data type e The rounding mode is set to Floor Therefore bits simply fall off the left or fall off the right when a shift occurs e Overflows wrap e The output scaling is specified to reflect the required shift For example suppose you start with the fixed point number 00110 101 a decimal value of 6 625 which is characterized by the blockset as an 8 bit unsigned generalized fixed point number with radix point only scaling of 23 To shift the bits and radix point two places to the right the input scaling of 23 ismultiplied by 22 which yields a scaling of 21 Toshift the bits and radix point Rules for Arithmetic O perations two places to the left the input scaling of 23 is multiplied by 22 which yields as scaling of 2 This situation is shown below Shift Operation Scaling Binary Value Decimal Value No shift original number 23 00110 101 6 625 Shift righ
349. t zero exactly Input Port s Any data type supported by the blockset Output Port Any data type supported by the blockset that can exactly represent zero Direct Feedthrough Yes Scalar Expansion Of inputs Look Up Table Purpose Library Description ES a Approximate a one dimensional function using a selected look up method Lookup The Look Up Table block is a masked S function that computes an approximation to some function y f x given x y data vectors The look up method can use interpolation extrapolation or the original values of the input Thelength of the x and y data vectors provided to this block must match Also the x data vector must be strictly monotonically increasing after conversion to the input s fixed point data type Note that due to quantization the x data vector may be strictly monotonic in doubles format but not so after conversion to a fixed point data type To map two inputs to an output use the Look Up Table 2D block Y ou define the table by specifying the Vector of input values parameter as a 1 by n vector and the Vector of output values parameter as a 1 by n vector The block generates output based on the input values using one of these methods selected from the Method parameter list e Interpolation Extrapolation This is the default method it performs linear interpolation and extrapolation of the inputs Ifa value matches the block s input the output is the corresponding elem
350. tInput plant output signal PlantOutput ReferenceSignal Ea Plot Signals Plot Doubles Plot Both Cancel 2 Plot both signals Theplant input signal and plant output signals areshown below Thesesignals reflect the initial guess at scaling Plotting fxpdemo_feedback outputs olx Fixed pointplant input signal Fixed point plant output signal 6 11 6 Tutorial Feedback Controller Simulation 6 12 The Bode plot design sought to produce a well behaved linear response for the closed loop system Clearly the response is nonlinear The nonlinear features are due to significant quantization effects An important part of fixed point design is finding scalings that reduce quantization effects to acceptable levels Simulation 2 Global Override Prior to using the automatic scaling tool a global override with doubles of the fixed point data type is performed for every block Using this feature you can obtain ideal simulation limits Additionally you must log maximum and minimum simulation values for all blocks that are to be scaled This is accomplished by checking the Log minimums and maximums check box for the relevant blocks and accepting the Log Min Max default valueUse block params Global override with doubles is accomplished by configuring Datatype Override to Doubles override ON and then running the simulation by selecting the Run button The ideal and fixed point plant output signals are then c
351. tch blocks are replaced with a version contained in the fixpt_convert_lib library The old style Latch block contains a Transport Delay block which is a very inefficient implementation for both floating point and fixed point Function blocks acting like selectors Function blocks acting like selectors are replaced with the Selector block Function blocks acting like selectors require that you specify the width of the input To get this information the model must be put into compile mode which is inefficient A select set of additional function blocks You can replace function blocks that have replacements in the fixpt_convert_1lib library Alternatively you can use fixpt_convert_prep as a prototype for creating a customized list of function blocks to be replaced Todothis copy the function and the library to another directory and then customize the library to include function blocks that you commonly encounter when converting models from floating point to fixed point Note This function is meant to be a starting point for customizing the Simulink to Fixed Point Blockset conversion process See Also fixpt_convert 9 13 fixpt_look1_func_approx Purpose Syntax Description 9 14 Optimize for a fixed point function the x values or breakpoints that are generated for a lookup table xdata ydata errworst fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth errmax xdata ydata errworst
352. te and y is the output Both equations have the same data type The matrices A B C and D have the following characteristics e A must be an n by n matrix where n is the number of states e B must be an n by m matrix where m is the number of inputs e C must bean r by n matrix where r is the number of outputs e D must bean r by m matrix In addition e The state x must be a n by 1 vector e Theinput u must be a m by 1 vector e The output y must be a r by 1 vector The block accepts one input and generates one output The input vector width is determined by the number of columns in the B and D matrices The output vector width is determined by the number of rows in the C and D matrices 10 189 State Space Parameters and Dialog Box 10 190 Block Parameters State Space m Fixed Point State Space mask link Discrete time State Space Realization m Parameters State Matrix A Input Matrix B Output Matrix C joo 84 0 0024 0 0055 Direct Feedthrough Matrix D 10 0033 Initial condition for state a K Data type for internal calculations ex sfix 16 uint 8 float single TA Scaling for State Equation AX BU ex 2 9 ANN Scaling for Output Equation CX DU ex 2 9 P4000 FF Lock output scaling so autoscaling tool can t change it Round toward Fo H T Saturate to max or min when overflows occur TF Override data type s with doubles IV Log minimums and maximums
353. te to max or min when overflows occur TF Override data type s with doubles Log minimums and maximums Cancel Help Apply 10 81 Filter Direct Form Time Varying Characteristics See Also 10 82 Initial condition for previous output Set the initial condition for the previous output Initial condition for previous input Set the initial condition for the previous input Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Port u Any data type supported by the blockset it must be a scalar Input Port Num Any data type supported by the blockset it must be a scalar Input Port Den No Any data type supported by the blockset it must be Lead a scalar Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Of initial conditions Vectorized No FIR and related blocks Filter Direct Form Il Purpose Library Description 0 2 0 3z 40 272 10 970 672 Parameters and Dialog Box Implement a Direct Form II realization of a filter Filters The Filter Direct Form block implements a Direct Form II realization of the filter specified by the Nu
354. ted Purpose Library Description Remarks Perform discrete time limited integration of a signal using the backward method with external Boolean reset Calculus The Integrator Backward Resettable Limited block performs a discrete time integration of a signal using the backward method The block can reset ts state based on an external reset signal R When the cumulative sum reaches one of the limits given by the Upper limit and Lower limit parameters the sum saturates to that limit When the reset signal R is false the block multiplies the input by the weighted sample time and adds the result to the cumulative sum since time zero When the reset signal R is true the block outputs the Initial condition for previous output parameter The output of the Integrator Backward Resettable Limited block differs from the output of the ntegrator Forward Resettable Limited block only by the first and last terms in the cumulative sum 10 117 Integrator Backward Resetta ble Limited Parameters a nd Dia log Box Block Parameters Integrator Backward Resettable Limited m Fixed Point Integrator Backward Resettable Limited mask link Discrete time limited integration of the input u using backward method with external boolean reset This block only works with fixed sample rates so it will not work inside a triggered subsystem m Parameters Gain value io OOO Initial condition for previous outpu
355. ted Unit Delay With Preview Resettable External RV Parameters and Dialog Box Characteristics See Also Block Parameters Unit Delay With Preview Resettable External AY Lx r Fixed Point Unit Delay With Preview Resettable External RW mask link Unit Delays With Preview have two outputs instead of just one Normally the first output equals the signal u and the second output is a unit delayed version of the first output Having both signals is useful for implementing recursive calculations where the result should include the most recent inputs The second output of a Unit Delay With Preview can be safely feedback into calculations of the block s inputs without causing an algebraic loop Meanwhile the first output will show the most up to date calculations This block has both an external reset value and an internal initial condition The reset value signal RW is used only when the reset signal R is true When this occurs the first output signal is forced to equal RY The second output signal is not affected until one time step later The internal initial condition is used only when the model starts or when a parent enabled subsystem is reset The internal initial condition only has direct effect on the second output The first output is only affected through feedback This reset action is vectorized and supports scalar expansion Parameters Initial condition pa Sample time mooo Cancel
356. ter Filters The Filter Direct Form block implements a Direct Form I realization of the filter specified by the Numerator coefficients and the Denominator coefficients excluding lead parameters The block only supports single input single output filters The block automatically selects the data types and scalings of the output the coefficients and any temporary variables Filter Direct Form Parameters and Dialog Box Block Parameters Filter Direct Form r Fixed Point Filter Direct Form mask link A Direct Form realization of the specified filter is used Only single input single output filters are supported The data types and scalings of the output the coefficients and any temporary variables are automatically selected The automatic choices will be acceptable in many situations In situations where the automatic choices give unacceptable results manual layout of the filter is necessary For manual layout it is suggest that the blocks under this mask be used as a starting point Note 1 The full denominator should have a leading coefficient of 1 0 but this leading coefficient should be excluded when entering the parameter For example if the denominator is den 1 1 7 0 72 just enter den 2 end 1 7 0 72 Note 2 The numerator does NOT need to be the same size as the full denominator m Parameters Numerator coefficients 10 2 0 3 0 2 Denominator coefficients excluding lead which must be
357. th positive and negative numbers are rounded toward positive infinity As a result a positive cumulative bias is introduced in the number 4 6 Limitations on Precision In MATLAB you can round to ceiling using the ceil function Rounding toward ceiling is shown below Round Toward Ceiling 1 T T T 0 5 J All numbers are rounded toward positive infinity 0 Ls e 0 5 J 1 I i f 1 0 0 2 0 4 0 6 0 8 1 Time Round Toward Floor When rounding toward floor both positive and negative numbers are rounded tonegativeinfinity As a result a negative cumulative bias is introduced in the number 4 7 4 Arithmetic O perations In MATLAB you can round tofloor using the floor function Rounding toward floor is shown below Round Toward F loor 1 T T 0 5 J All numbers are rounded toward negative infinity OF 4 0 5 J L L 1 0 0 2 0 4 0 6 0 8 1 Time Rounding toward ceiling and rounding toward floor are sometimes useful for diagnostic purposes F or example after a series of arithmetic operations you may not know the exact answer because of word size limitations which introduce rounding If every operation in the series is performed twice once rounding to positive infinity and once rounding to negative infinity you obtain an upper limit and a lower limit on the correct answer You can then decide if the result is sufficiently accurate
358. that column e UseBest Precision Matrix wise This mode produces a common radix point for each element of the Gain matrix value matrix based on the best precision for the largest value of the matrix 10 155 Matrix Gain Parameters and Dialog Box 10 156 For a detailed description of all other block parameters refer to Block Parameters on page 10 4 Block Parameters Matrix Gain r Fixed Point Matrix Gain mask link Multiply the input by a constant gain r Parameters Gain matrix value fee Gain data type and scaling Specify viados x Parameter data type ex sfix 16 uint 8 float single fete Parameter scaling Slope ex 29 214 Parameter scaling Best Precision Matixwise y Output data type and scaling Specify via dialog E Output data type ex sfix 16 uint 8 float single aa Output scaling Slope or Slope Bias ex 2 9 pao o I Lock output scaling so autoscaling tool can t change it Round toward Floor X I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Multiplication Mati K u uvet O Cancel Help Apply Gain matrix value Specify as a scalar or vector Gain data type and scaling Set the data type and scaling of the gain Parameter data type Any data type supported by the Fixed Point Blockset Parameter scaling Radix point only or slope bias scaling Additionally the gain can be scaled u
359. the FIR coefficients parameter Best Precision Row wise This mode produces a common radix point for each element of the FIR coefficients row based on the best precision for the largest value of that row e Best Precision Column wise This mode produces a common radix point for each element of the FIR coefficients column based on the best precision for the largest value of that column e Best Precision Matrix wise This mode produces a common radix point for each element of the FIR coefficients matrix based on the best precision for the largest value of the matrix 10 93 FIR If the FIR coefficients are specified as a row vector then scaling element wise and column wise produce the same result while scaling matrix wise and row wise produce the same result For a detailed description of all other block parameters refer to Block Parameters on page 10 4 Pa ra meters Block Parameters FIR and Dialog BOX FiedPointFIR mask ink Implement a finite impulse response FIR filter m Parameters FIR coefficients 0 1 1 0 9 0 1 0 1 Initial condition C Sample time mooo Gain data type and scaling Specify viados H Parameter data type ex sfix 16 uint 8 float single s6 Barameter scana Slope ex 29 Parameter scaling Best Precision Matixwise m Dutput data type and scaling Specify viados x Output data type ex sfix 16 uint 8 float single aa Output scaling Slope
360. the Lookup Table To create the lookup table type xdata ydata errworst fixpt_look1_func_approx funcstr xmin xmax xdt xscale ydt yscale rndmeth errmax Note that the nptsmax and spacing parameters are not specified The function returns three variables e xdata the vector of breakpoints of the lookup table e ydata the vector found by applying ideal function sin 27x to xdata e errworst which specifies the maximum possible error in the lookup table The value of errworst is less than or equal to the value of errmax You can find the number of X data points by typing length xdata 8 7 8 Producing Lookup Table Data This means that 16 points are required to approximate sin 27x to within the tolerance specified by errmax Y ou can display the maximum error by typing errworst This returns errworst 9 7656e 004 Plotting the Results Y ou can plot the output of the function fixpt_look1_func_plot by typing fixpt_look1_func_plot xdata ydata funcstr xmin xmax xdt xscale ydt yscale rndmeth The resulting plots are shown below lt Figure No 1 olx File Edit View Insert Tools Window Help JOSH SIRAASL PER enion sin 2 pi x Ideal red Fixed Point Lookup Approximation blue Input Table uses 16 unevenly spaced data points The input is Unsigned 16 Bit with 16 bits right of binary point The output is Signed 16 Bit with 14 bits right of binary point Maximum Absolute Error 0 00097
361. the initial condition for the previous output Integrator Forward Characteristics See Also Output data type and scaling The options are e Specify via dialog e Inherit via internal rule e Inherit via back propagation When Specify via dialog is selected you can specify the Output data type and Output scaling parameters Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion Of inputs and gain Integrator Backward and related blocks 10 121 Integrator Forward Resetta ble Purpose Library Description Y kTs R 1 1 Remarks Parameters and Dialog Box 10 122 Perform discrete time integration of a signal using the forward method with external Boolean reset Calculus The Integrator Forward Resettable block performs a discrete time integration of a signal using the forward method When the external reset signal R is false the block multiplies the input by the weighted sample time and adds the result to the cumulative sum since time zero When the external reset signal R is
362. the same system In theory these realizations are all identical to each other In the more realistic world of double precision numbers calculations and storage of states small nonlinearities are introduced due tothe finite precision and range of floating point data types Therefore each realization of a given system will produce different results In most cases however these differences are small In the world of fixed point numbers where precision and range are limited the differences in the realization results can be very large Therefore you must carefully select the data type word size and scaling for each realization element such that results are accurately represented To assist you with this selection design rules for modeling dynamic systems with fixed point math are provided in Targeting an Embedded Processor on page 7 3 Realizations and Scaling As with all Fixed Point Blockset models you must select a scaling that gives the best precision range and performance for your specific fixed point design Thescaling for each filter and system demo is based on the default parameters If these parameters are changed for example the magnitude of the input signal is increased or if you are creating a new realization you must define an appropriate scaling For each system or filter you can adjust the scaling manually with the dialog box or automatically as illustrated in Simulation Results on page 6 9 Targeting
363. the scaling that is inherited from the driving block For example the data type displays for the Fixed Point Sine demo are shown below Sine Wave 2 rad sec FixPt Sum From FixPt1 Sine Wave 1 rad sec TORRES FixPt Product From FixPt2 Common Block Features The data type display associated with the To FixPt1 block indicates that the output data type is sfix 16 a signed 16 bit generalized fixed point number with slope bias scaling of 1 5 10 Note that this scaling is not the block s default scaling The data type display associated with the To FixPt2 block indicates that the output data typeis sfix 16 with radix point only scaling of 2 6 10 11 10 Block Reference The Fixed Point Blockset Libraries To open the main Fixed Point library at the MATLAB prompt type fixpt This opens the main library window as shown below JLibrary fixpt_lib_3p1 File Edit View format Help Os HS teea 2 Ret Fixed Point Library Version 3 1 Copyright 1994 2001 The MathWorks Inc Ready 100 Locked Ui The main library contains twelve sublibraries To open a sublibrary double click on its icon The following table describes how the Fixed Point Blockset blocks are grouped into the sublibraries Bits Bit Clear Set the specified bit of the stored integer to zero 10 12 The Fixed Point Blockset Libraries Bits Bit Set Bitwise Operator Set the specified bit of th
364. thin the word The binary number 0011 0101 yields thesame value for the unsigned and two s complement representation since the MSB 0 Setting B 0 and using the appropriate weights bit multipliers and scaling the value is lt Il ws 1 V F25 Q na i 0 OAD AD Oe o OL 3 3125 3 7 3 Data Types and Scaling 3 8 Conversely the binary number 1011 0101 yields different values for the unsigned and two s complement representation since the MSB 1 Setting B 0 and using the appropriate weights bit multipliers and scaling the unsigned value is WS 1 Y na i 0 24 1 27 0 2f4 1 2 1 24 0 25 1 22 0 214 1 29 11 3125 while the two s complement value is ws 2 Y F25 Q 2 insaat y a2 i 0 24 1 27 0 28 1 2 1 2f 0 2 1 2 0 21 1 20 4 6875 Range and Precision Therangeof a number gives the limits of the representation while the precision gives the distance between successive numbers in the representation The range and precision of a fixed point number depends on the length of the word and the scaling Fixed Point N umbers Range The range of representable numbers for an unsigned and two s complement fixed point number of size ws scaling S and bias B is illustrated below y S 2W5 1 B positive numbers S 2W5 1 4 B 0 S 2WS 1 1 B m negative numbers positive numbers For both the signed and unsigned fixed point numbers of any data ty
365. tions from the Category parameter list The ERT code A Code Generation generation options for this configuration are shown below If you are using GRT the dialog box choices are slightly different Simulation Parameters fxpdemo_code_only MA ES Solver Workspace 1 0 Diagnostics Advanced RealTime workshop Category ERT code generation options y Generate code Options FT MAT file logging IV Integer code only F Initialize internal data F Initialize external 1 0 data T Terminate function required Y Single output update function I Create Simulink S Function block OK Cancel Help Apply Note that all fixed point blocks except gateway blocks produce pure integer code for all supported targets Build the code by selecting the Generate code button A 10 Using the Simulink Accelerator Using the Simulink Accelerator Y ou can use the Simulink Accelerator with your Fixed Point Blockset model if the model meets the code generation restrictions The Simulink Accelerator can drastically increase the speed of some fixed point models This is especially true for models that execute at a very large number of time steps The time overhead to generate code for a fixed point model will generally be larger than the time overhead to set up a model for simulation As the number of time steps increases the relative importance of this overhead decreases Refer to the Using Simulink guide for more informat
366. ton R and G Goodwin Digital Control and Estimation A Unified Approach Prentice Hall Englewood Clifs New J ersey 1990 Moler C Floating points IEEE Standard unifies arithmetic model Cleve s Corner The MathWorks Inc 1996 Y ou can find this article at http www mathworks com company newsletter clevescorner cleve_toc shtml Ogata K Discrete Time Control Systems Second Edition Prentice Hall Englewood Cliffs New J ersey 1995 Roberts R A and C T Mullis Digital Signal Processing Addison Wesley Publishing Company Reading Massachusetts 1987 A accumulation scaling recommendations 4 19 using slope bias encoding 4 19 accumulator data type 7 3 and feedback controller demo 6 8 addition 10 192 blockset rules 4 30 scaling recommendations 4 17 using slope bias encoding 4 16 ALU s 4 30 arithmetic shift 4 42 autofixexp 9 4 automatic scaling and feedback controller demo 6 15 and FixPt Look Up Table 2D block 10 151 and percent safety margin 9 4 9 29 interface 9 28 script 9 4 B back propagation Data Type Propagation block 10 49 FixPt Gateway Out block 10 107 FixPt Tapped Delay block 10 197 base data type 7 3 and feedback controller demo 6 8 binary point 3 3 bit clear 10 32 hidden 3 18 mask 10 32 multipliers 3 7 set 10 32 shifts 4 41 bits 3 3 block configuration 2 2 selecting a data type 2 3 selecting a scaling 2 5 block icon labels 10 10 block parameters 10 4 blocks Abs 10 22 Accumulat
367. tool can t change it Round toward Floor X I Saturate to max or min when overflows occur TF Override data type s with doubles IV Log minimums and maximums Cancel Help Apply Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling from the driving block or by back propagation Output data type Any data type supported by the Fixed Point Blockset 10 76 Dot Product Characteristics Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generalized fixed point output Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the Output data type is overridden with doubles Log minimums and maximums If checked minimum and maximum simulation values are logged to the workspace Input Ports Any data type supported by the blockset Output Port Any data type supported by the blockset Direct Feedthrough Yes Scalar Expansion Yes 10 77 Filter Direct Form Purpose Library Description 0 2 0 3710 27 8 10 970 672 10 78 Implement a Direct Form realization of a fil
368. tput The conversion has two possible goals One goal is to have the Real World Values of the input and the output be equal The other goal is to have the Stored Integer Values of the input and the output be equal Overtlows and quantization errors can prevent the goal from being fully achieved The input and the output support all built in and fixed point data types Input and Output to have equal 331 Output data type and scaling Specity via dialog Output data type ex sfix 16 uint 8 float single fe Output scaling Slope or Slope Bias ex 2 9 ao I Lock output scaling so autoscaling tool can t change it Round toward Fo S I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Parameters Cancel Hep 4w Input and Output to have equal Specify the type of value that the input and output are to have equal Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling by back propagation Output data type Any data type supported by the Fixed Point Blockset Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generaliz
369. tra bits This method involves going from low precision to higher precision For example suppose two numbers are subtracted from each other First the exponents must be aligned which typically involves a right shift of the number with the smaller value In performing this shift significant digits can fall off tothe right However when the appropriate number of extra bits is appended the precision of the result is maximized Consider two 8 bit fixed point numbers that are close in value and subtracted from each other 1 0000000 2 1 1111111 2971 where q is an integer To perform this operation the exponents must be equal 4 9 4 Arithmetic O perations 4 10 1 0000000 24 0 1111111 24 0 0000001 2 If the top number is padded by two zeros and the bottom number is padded with one zero then the above equation becomes 1 000000000 2 0 111111110 2 0 000000010 2 which produces a more precise result An example of padding with trailing zeros using the Fixed Point Blockset is illustrated in Digital Controller Realization on page 6 7 Example Limitations on Precision and Errors Fixed point variables have a limited precision because digital systems represent numbers with a finite number of bits For example suppose you must represent the real world number 35 375 with a fixed point number Using the encoding scheme described in Scaling on page 3 5 the representation is Y 7 Q 32 The t
370. ts are supported only for fractional data types For both signed and unsigned fractionals the guard bits lie to the left of the default radix point Example Limitations on Range Fixed point variables have a limited range for the same reason they have limited precision because digital systems represent numbers with a finite number of bits As a general example consider the case where an integer is represented as a fixed point word of size ws The rangefor signed and unsigned words is given by max Q min Q where 0 unsigned min Q oe cil signed MT unsigned gned Using the general slope bias encoding scheme described in Scaling on page 3 5 the approximate real world value has the range max V min V where E B unsigned min V F25 2 57 B signed E aws F2 2 1 B unsigned Mars 5 ws F2 2 1 B signed If the real world value exceeds the limited range of the approximate value then the accuracy of the representation can become significantly worse 4 15 4 Arithmetic O perations Recommendations for Arithmetic and Scaling This section describes the relationship between arithmetic operations and fixed point scaling and some basic recommendations that may be appropriate for your fixed point design For each arithmetic operation e The general slope bias encoding scheme described in Scaling on page 3 5 is used e Thescaling of the result is automatically selected based on the s
371. ts shown below Figure No 1 olx Eile Edit View Insert Tools Window Help JOSMS KAAS PER Function sin 2 pi x Ideal red Fixed Point Lookup Approximation blue 1 Absolute Error Table uses 17 power of 2 spaced data pointg Put The input is Unsigned 16 Bit with 16 bits right of binary point The output is Signed 16 Bit with 14 bits right of binary point Maximum Absolute Error 0 0012649 log2 MAE 9 6267 MAE yBit 20 7245 The least significant 5 bits of the output can be inaccurate The most significant nonsign bit of the output is used The remaining 10 nonsign bits of the output are used and always acourate The sign bit of the output is not used The rounding mode is to Floor Specifying Both errmax and nptsmax If you include both the errmax and the nptsmax parameters the function fixpt_look1_func_approx tries to find a lookup table with at most nptsmax data points whose worst case error is at most errmax If it can find a lookup table meeting both conditions it uses the following order of priority for spacing 1 Power of two 2 Even 3 Unrestricted Creating Lookup Tables for a Sine Function Table 8 1 Summary of Results for the Examples If the function cannot find any lookup table satisfying both conditions it ignores nptsmax and returns a lookup table with unrestricted spacing whose worst case error is at most errmax In this case the function behaves the same as if the nptsmax parameter were
372. types Parameters Input and Output to have equal SS We Nive Output data type and scaling Specity via dialog y Output data type ex sfix 16 uint 8 float single sfix 16 Output scaling Slope or Slope Bias ex 2 9 pmo I Lock output scaling so autoscaling tool can t change it Round toward Floor v I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Cancel Help Input and Output to have equal Specify the type of value of the input and output that are to be equal 10 40 Conversion Characteristics See Also Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling via back propagation Output data type Any data type supported by the Fixed Point Blockset Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generalized fixed point output Round toward Rounding mode for the fixed point output Saturate to max or min when overflows occur If checked fixed point overflows saturate Otherwise they wrap Override data type s with doubles If checked the Output data type is overridden with doubles Log minimums and maximums If checked
373. u Direct Feedthrough No Scalar Expansion Yes See Also Unit Delay and related blocks 10 203 Unit Delay Enabled External IC Purpose Library Description Parameters and Dialog Box Characteristics 10 204 Delay a signal one sample period if the enable is on Delays Holds The Unit Delay Enabled block is a masked block that delays a signal by one sample period when the enable signal E is on While the enableis off the block holds the current state at the same value and outputs that value The enable E ison when E is not 0 and off when E is 0 The blocks initial condition is given by the signal IC The input u and Ic data types must be the same and are any data type The output data type is the same as u and IC The enable E is any data type Y ou specify the time between samples with the Sample time parameter A setting of 1 means the Sample time is inherited Block Parameters Unit Delay Enabled External IC Fixed Point Unit Delay Enabled External Initial Condition mask link Normally the output is the signal u delayed by one sample period The initial condition is given by the signal IC When the enable signal is false the block is disabled and the state and output values do not change except for resets The enable action is vectorized and supports scalar expansion Parameters Sample time ee Cancel Help Epp Sample time Sample time Input Port u Any data type sup
374. um absolute error is less than errmax e The number of points required is less than nptsmax e The spacing is specified as unrestricted even or even power of 2 Modes for errmax nptsmax and spacing e f both errmax and nptsmax are specified The returned breakpoints will meet both criteria if possible The errmax parameter is given priority and nptsmax is ignored if both criteria cannot be met with the specified spacing e If only errmax is specified The breakpoints that meet the error criteria and have the least number of points are returned e If only nptsmax is specified The breakpoints that require nptsmax or fewer and give the smallest worst case error are returned e f more than one spacing method meets the criteria power of 2 spacing is chosen over even spacing which in turn is chosen over uneven spacing This fix pt_look1_func_approx Remarks case occurs when the errmax and nptsmax are both specified but does not typically occur when only one is specified If unrestricted is entered the function chooses the spacing that provides the best optimization If even is entered the function chooses an evenly spaced set of points including the pow2 spacing If pow2 spacing is entered the function chooses an even power of 2 spaced set of points Note Theglobal optimum may not be found The worst case error can depend on fixed point calculations which are highly nonlinear Furthermore the optimizatio
375. unsigned integer Direct Feedthrough Yes Scalar Expansion Yes Vectorized Yes Detect Change and related blocks Detect Increase Purpose Library Description EN Parameters and Dialog Box Characteristics See Also Detect an increase in a signal s value Edge Detect The Detect Increase block is a masked block that determines if an input is strictly greater than its previous value where e The output is true not 0 when the input signal is greater than its previous value e The output is false equal to 0 when the input signal is less than or equal to its previous value Block Parameters Detect Increase Fixed Point Detect Increase mask link If the input is strictly greater than its previous value then output TRUE otherwise output false A Cancel Help Boal Input Port Any data type supported by the blockset Output Port An 8 bit unsigned integer Direct Feedthrough Yes Scalar Expansion Yes Vectorized Yes Detect Change and related blocks 10 71 Detect Rise Nonnegative Purpose Library Description Parameters and Dialog Box Characteristics See Also 10 72 Detect a rising edge when a signal s value increases to a nonnegative value and its previous value was strictly negative Edge Detect The Detect Rise Nonnegative block is a masked block that determines if the input is greater than or equal to zero and its previous value was less than zero where
376. upper limit with the Upper limit parameter You can specify the sample time with the Sample time parameter A Sample time of 1 means that the sample time is inherited The output is an unsigned integer of 8 16 or 32 bits with the smallest number of bits needed to represent the upper limit Pa ra meters Block Parameters Counter Limited and Dialog BOX FuedPoint Counter Limited mask ink This block is a counter that wraps back to zero after it has output the specified upper limit The count is always initialized to zero The output is normally an unsigned integer of 8 16 or 32 bits The smallest number of bits needed to represent the upper limit is used Parameters Upper limit 7 Sample time M Cancel Help Epp Upper limit U pper limit Sample time Sample time Characteristics Output Port Unscaled integer or a floating point data type Scalar Expansion No Vectorized No See Also Counter Free 10 46 Data Type Duplicate Purpose Library Description Same DT Parameters and Dialog Box Characteristics Remarks Set all inputs to the same data type Data Type The Data Type Duplicate block is a masked S function that forces all inputs to have exactly the same data type Other attributes of input signals such as dimension complexity and sample time are completely independent You can use the Data Type Duplicate block to check for consistency of data types among blocks
377. ut Port Same as the input Direct Feedthrough Yes Scalar Expansion No Decrement Real World and related blocks Derivative Purpose Library Description Kiz 1 Tsz 7 Parameters and Dialog Box Compute a discrete time derivative Calculus The Derivative block computes a discrete time derivative by subtracting the input value at the previous time step from the current value and dividing by the sample time Block Parameters Derivative r Fixed Point Derivative mask link Discrete time derivative of the input This block only works with fixed sample rates so it will not work inside a triggered subsystem Parameters Gain value wmo Initial condition for previous weighted input K u Ts 0 0 Output data type and scaling Inherit viaintemalule x Round toward Fo H I Saturate to max or min when overflows occur I Override data type s with doubles M Log minimums and maximums Cancel Help Apply Gain value Specify the weight by which the sample time is multiplied Initial condition for previous weighted input K u Ts Set the initial condition for the previous scaled input Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling from the driving block or by back propagation 10 65 Derivative Characteristics 10 66 Round toward Rounding mode for the fixed point output Saturate t
378. ut is identical to the scaling of the first input Radix Point O nly Scaling For radix point only scaling finding Qa new results in this simple expression E E Qs new Qa old 2 Qp This scaling option only involves one addition and some bit shifting Note The negative accumulation of values produces results that are analogous to those produced by the accumulation of values 4 19 4 Arithmetic O perations 4 20 Multiplication Consider the multiplication of two real world values Va Vx Ve These values are represented by the general slope bias encoding scheme described in Scaling on page 3 5 In a fixed point system the multiplication of values results in finding the variable Qa Pipe EE El FpBe Eso ES PB LE Es Q b c 2 pt QpQc b c 2 b Qy Cc b p Q Fa Pa Pa B B_ B E y es a E a This formula shows e In general Qa is not computed through a simple multiplication of Qp and Qe e In general there is one multiply of a constant and two variables two multiplies of a constant and a variable three additions and some additional bit shifting Inherited Scaling for Speed The number of arithmetic operations can be reduced with these choices e Set Bs BpB This eliminates one addition operation e Set Fa FpF This simplifies the triple multiplication certainly the most difficult part of the equation to implement e Set Ea Ep E This eliminates some of the bit shifting The
379. vision of values results in finding the variable Qa F 2 Q Bp B Qa LO BE a2 E E FF 2 This formula shows e In general Qa is not computed through a simple division of Qp by Qe e In general there are two multiplies of a constant and a variable two additions one division of a variable by a variable one division of a constant by a variable and some additional bit shifting Inherited Scaling for Speed The number of arithmetic operations can be reduced with these choices e Set Ba 0 This eliminates one addition operation e If B 0 then set the fractional slope Fa F p F This eliminates one constant times variable multiplication The resulting formula is 4 23 4 Arithmetic O perations 4 24 Q Spt B F _ Pb EEE Ba Fb Q Q E E Q 2 If BL 0 then no clear recommendation can be made Inherited Scaling for Maximum Precision The maximum precision scaling can be determined if the range of the variable is known As shown in Example Maximizing Precision on page 4 11 the range of a fixed point operation can be determined from max V and min Va For division the range can be determined from where for nonzero denominators VLL min V min V Vin min V max V Vip max V min V Vi max V max V Radix Point O nly Scaling For radix point only scaling finding Q results in this simple expression Oh Bs ESE Q E See b c a a Q Note For the last two formulas i
380. which must pass through the origin A linethrough theorigin is called a purely linear conversion Restricting 1 3 1 Introduction 1 4 yourself to a purely linear conversion can be very wasteful and it is often better to usethe general eguation of a line V SQ B By adding a bias term B greater precision can be obtained when quantizing to a limited number of bits The general equation of a line gives a very useful conversion to a quantized scale However like all quantization methods the precision is limited and errors can be introduced by the conversion The general equation of a line with quantization error is given by V SQ BError If the quantized value Q is rounded to the nearest representable number then S S lt lt 5 5 Errors 5 That is the amount of quantization error is determined by both the number of bits and by the scale This scenario represents the best case error For other rounding schemes the error can be twice as large Example Selecting a Measurement Scale On typical electronically controlled internal combustion engines the flow of fuel is regulated to obtain the desired ratio of air to fuel in the cylinders just prior to combustion Therefore knowledge of the current air flow rate is required Some manufacturers use sensors that directly measure air flow while other manufacturers calculate air flow from measurements of related signals The relationship of these variables is derived from the
381. wo closest approximations to the real world value are Q 13 and Q 14 V V 27 13 32 35 25 27 14 32 35 50 In either case the absolute error is the same mire IV v 0 125 5 For fixed point values within the limited range this represents the worst case error if round to nearest is used If other rounding modes are used the worst case error can be twice as large Y v lt F 2E Limitations on Precision Example Maximizing Precision Precision is limited by slope To achieve maximum precision the slope should be made as small as possible while keeping the range adequately large The bias will be adjusted in coordination with the slope Assume the maximum and minimum real world value is given by max V and min V respectively These limits may be known based on physical principles or engineering considerations To maximize the precision you must decide upon a rounding scheme and whether overflows saturate or wrap To simplify matters this example assumes the minimum real world value corresponds to the minimum encoded value and the maximum real world value corresponds to the maximum encoded value Using the encoding scheme described in Scaling on page 3 5 these values are given by max V F 2 max Q B min V F2 min Q B Solving for the slope you get E max V min V _ max V min V max Q min Q 2 S_1 This formula is independent of rounding and overflow issues and depen
382. x Parameters a nd Dia log Box Block Parameters Mink ax r Fixed Point MinMax mask link Output min or max of input For a single input operators are applied across the input vector For multiple inputs operators are applied across the inputs m Parameters Fcio aa Number of input ports fi Output data type and scaling Specity via dialog y Output data type ex sfix 16 uint 8 float single sti 6 Output scaling Slope or Slope Bias ex 2 9 al 0 FF Lock output scaling so autoscaling tool can t change it Round toward Floor v I Saturate to max or min when overflows occur I Override data type s with doubles IV Log minimums and maximums Cancel Help Function The function to apply to the input Number of input ports The number of inputs to the block Output data type and scaling Specify the output data type and scaling via the dialog box or inherit the data type and scaling from the driving block or by back propagation Output data type Any data type supported by the Fixed Point Blockset Output scaling Radix point only or slope bias scaling These scaling modes are available only for generalized fixed point data types 10 160 MinMax Characteristics Lock output scaling so autoscaling tool can t change it If checked Output scaling is locked This feature is available only for generalized fixed point output Round toward Rounding mo
383. xed point variables It also provides recommendations for encoding fixed point variables such that simulations and generated code are reasonably efficient 4 2 Limitations on Precision Limitations on Precision Computer words consist of a finite numbers of bits This means that the binary encoding of variables is only an approximation of an arbitrarily precise real world value Therefore the limitations of the binary representation automatically introduce limitations on the precision of the value The precision of a fixed point word depends on the word size and radix point location Extending the precision of a word can always be accomplished with more bits although you face practical limitations with this approach Instead you must carefully select the data type word size and scaling such that numbers are accurately represented Rounding and padding with trailing zeros are typical methods implemented on processors to deal with the precision of binary words Rounding The result of any operation on a fixed point number is typically stored in a register that is longer than the number s original format When the result is put back into the original format the extra bits must be disposed of That is the result must be rounded Rounding involves going from high precision to lower precision and produces quantization errors and computational noise The blockset provides four rounding modes which are shown below 4 3 4 Arithmeti
384. ximation function and its error from the ideal function You can use the fixpt_look1_func_approx function to generate xdata and ydata the X and Y data points for the lookup table The function returns the maximum absolute error as a variable errworst The inputs are as follows Input Value xdata x values for the lookup table ydata y values for the lookup table funcstr Function of x xmin Minimum input of interest xmax Maximum input of interest xdt Data type of x xscale Scaling for the x values ydt Data type of y yscale Scaling for the y values rndmeth Rounding mode supported by the blockset Toward Zero Nearest Floor Ceiling The fixpt_look1_func_approx function applies the ideal function to the points in xdata to produce ydata While this is is the easiest way to generate ydata you are not required to use these values for ydata as input for the 9 22 fixpt look1 _func plot fixpt_look1_func_approx function Choosing different values for ydata can in some cases produce a lookup table with a smaller maximum absolute error See Chapter 8 Producing Lookup Table Data for a tutorial on using the function fixpt_look1_func_plot For an example of the function seethe reference page for the function fixpt_look1_func_approx on page 9 14 See Also fixpt_look1_func_approx 9 23 fixpt restore links Purpose Syntax Description Remarks 9 24 Restore links for fixed point blocks res
385. ximum allowed error This tutorial shows you how to create function lookup tables using the function fixpt_look1_func_approx You can optimize the lookup tableto minimizethe number of data points the error or both You can also restrict the spacing of the breakpoints to be even or even powers of two in order to speed up computations using the table This tutorial also explains how to use the function fixpt_look1_func_plot to find the worst case error of a lookup table and plot the errors at all points The tutorial covers the following topics e Worst Case Error for a Lookup Table on page 8 3 explains how to use the function fixpt_look1_func_plot to find the worst case error and plot the fixed point approximation and the errors Creating Lookup Tables for a Sine Function on page 8 5 presents several examples that illustrate how to use the function fixpt_look1_func_approx to create lookup tables Summary of the Lookup Table Functions on page 8 19 E ffect of Spacing on Speed Error and Memory Usage on page 8 20 explains how restricting the spacing affects computational speed and memory usage W orst Case Error fora Lookup Table Worst Case Error for a Lookup Table This section explains the worst case error of a lookup table and how to find the worst case error using the function fixpt_look1_func_plot It gives a simple example of the worst case error of a lookup table for the square root function Theerr
386. ximum and minimum values logged in FixPtSimRanges For example a RangeFactor value of 1 55 specifies that a range at least 55 percent larger is desired A value of 0 85 specifies that a range up to 15 percent smaller is acceptable You should be aware that the scaling is not exact for the radix point only case since the range is given approximately by a power of two The lower limit is exact but the upper limit is always one bit below a power of two For example if the maximum logged value is 5 and the minimum logged value is 0 5 then any RangeFactor from 4 5 to slightly under 8 5 would produce the same radix point since these limits are less than a factor of two from each other The radix point selected will produce a range from 8 to 8 minus a bit autofix exp See Also 3 Theglobal variable FixPtSimRanges is retrieved from the workspace This is the variable that holds the maximum and minimum simulation values 4 Theworkspaceis searched for the variables SlopeBits and BiasBits which specify the number of bits to use in representing slopes and biases If these variables are not found then they are automatically created with default values of 7 and 8 respectively 5 All blocks that logged maximum and minimum simulation data are processed 6 All blocks that do not have their scaling locked are automatically scaled If the data type class is FIX then radix point only scaling is performed If the data type class is INT then
387. y Function Specify whether the block outputs the minimum or the maximum Initial condition Initial condition Input Ports Any data type supported by the blockset Output Port Same data type as the input u Direct Feedthrough Yes Scalar Expansion Yes MinMax MultiPort Switch Purpose Library Description Y A SH Switch output between different inputs based on the value of the first input Select The MultiPort Switch block is a masked S function that passes through the data input specified by the first top input The first input is called the control input while the rest of the inputs are called data inputs If the control input is an integer value then the specified data input is passed through tothe output For example if the control input is 1 then the first data input is passed through to the output If the control input is not an integer value the block truncates the value to an integer by rounding to floor If the truncated control input is less than 1 or greater than the number of input ports an out of bounds error is returned The block inputs can be scalar or vector Y ou specify the number of data inputs with the Number of input ports parameter The block output is determined by these rules e f you specify only one data input and that input is a vector the block behaves as an index selector and not as a multi port switch The block output is the vector element that corresponds t
388. y the data type via the dialog box Propagated scaling Use the parameter list to propagate the scaling via the dialog box or inherit the scaling from the reference signals Use the edit field to specify the scaling via the dialog box Override data type s with doubles If checked the data type is overridden with doubles Inheriting Data Type Information If the Propagated data type parameter is Inherit via propagation rule then these dialog box parameters are available to you 1 2 If any reference input is single output is single h 1 3 Is Signed IsSigned or IsSigned2 y 1 4 1 Number of Bits Base max NumBits1 NumBits2 1 4 2 Number of Bits Multiplicative adjustment TEE 1 4 3 Number of Bits Additive adjustment 0 1 4 4 Number of Bits Allowable final values 8 16 32 The If any reference input is single output is parameter list can be single or double This parameter makes it easier to create designs that are easily retargeted from fixed point chips to floating point chips or visa versa Thels Signed parameter list specifies the sign of Prop The parameter values are described below Parameter Description Value IsSignedi Prop is a signed data type if Refl is a signed data type IsSigned2 Prop is a signed data type if Ref2 is a signed data type Data Type Propagation Parameter Description Value IsSigned1or Propis a signed data type if either Refl or Ref2 are signed
389. y a signal N sample periods Delay a scalar signal multiple sample periods and output all the delayed versions Delay a signal one sample period Delay a signal one sample period Delay a signal one sample period Delay a signal one sample period Delay a signal one sample period Delay a signal one sample period Delay a signal one sample periodt Delay a signal one sample period Support calculations that have feedback and depend on the current input 10 15 10 Block Reference 10 16 Delays amp Holds Unit Delay With Preview Enabled Resettable Unit Delay With Preview Enabled Resettable External RV Unit Delay With Preview Resettable Unit Delay With Preview Resettable External RV Zero Order Hold Support calculations that have feedback and depend on the current input Support calculations that have feedback and depend on the current input Support calculations that have feedback and depend on the current input Support calculations that have feedback and depend on the current input Implement a zero order hold of one sample period Edge Detect Detect Change Detect Decrease Detect Fall Negative Detect Fall Nonpositive Detect Increase Detect a change in a signal s value Detect a decrease in a signal s value Detect a falling edge when the signal s value decreases to a strictly negative value and ts previous value was nonnegative Detect a falli
390. y data type and scaling parameter configured to Inherit via back propagation The block has three inputs Ref1 and Ref2 are the reference inputs while the Prop input back propagates the data type and scaling information gathered from the reference inputs This information is then passed on to other fixed point blocks The block provides you with many choices for propagating data type and scaling information For example you can e Use the number of bits from the Ref1 reference signal or use the number of bits from widest reference signal e Use the range from the Ref2 reference signal or use the range of the reference signal with the greatest range e Usea bias of zero regardless of the biases used by the reference signals e Use the precision of the reference signal with the least precision You specify how data type information is propagated with the Propagated data type parameter list If the parameter list is configured as Specify via dialog then you manually specify the data type via the Propagated data type edit field Refer to Selecting the Data Type on page 10 4 to learn how to specify the data type If the parameter list is configured as Inherit via propagation rule then you must use the parameters described in Inheriting Data Type Information on page 10 52 Y ou specify how scaling information is propagated with the Propagated scaling parameter list If the parameter list is configured as Specify via dialog th
391. y via dialog y Output data type ex sfix 16 uint 8 float single 36 bit signed fractional data type with 4 Prec a type with _ guard bits The total word size is 40 bits utputscalna Slope pe Bia ey 2 Iv Lock output seating Sut 1 nit change it Round toward Floor X IV Saturate to max or min when overflows occur Saturate overflows TF Override data type s with doubles IV Log minimums and maximums 4 Cancel Help Limitations on Range Saturation and Wrapping Saturation and wrapping describe a particular way that some processors deal with overflow conditions For example Analog Device s ADSP 2100 family of processors supports either of these modes If a register has a saturation mode of operation then an overflow condition is set to the maximum positive or negative value allowed Conversely if a register has a wrapping mode of operation an overflow condition is set tothe appropriate value within the range of the representation Example Saturation and Wrapping Consider an 8 bit unsigned word with radix point only scaling of 2 Suppose this data type must represent a sine wave that ranges from 4 to 4 For values between 0 and 4 the word can represent these numbers without regard to overflow This is not the case with negative numbers If overflows saturate all negative values are set to zero which is the smallest number representable by the data type The saturation of overflows is
392. you may find that the structures presented here look different from those in the fixed point filter design literature For each realization form an example is provided using the transfer function shown below Ho dz 14 2 2z 1 4 1 8572 0 5773 1 0 5z 1 0 84z 2 0 09z 3 _ _ 1 0 524 14 17z4 z2 1 0 1z 1 1 0 6z 1 0 9z7 2 3 4639 1 0916 3 0086z 1 5 5556 1 0 1z1 1 0 6z 1 0 9z 2 5 3 5 Realization Structures Direct Form Il 5 4 In general a direct form realization refers to a structure where the coefficients of the transfer function appear directly as gain blocks The direct form II realization method is presented as using the minimal number of delay elements which is equal to n the order of the transfer function denominator The canonical direct form II is presented as Standard Programming in Discrete TimeControl Systems by Ogata It is known as the Control Canonical Form in Digital Control of Dynamic Systems by Franklin Powell and Workman You can derive the canonical direct form II realization by writing the discrete time transfer function with input e z and output u z as CTO ez h z ez 1 Kk ab x gt ese m Lita eh a in ote eS u z h 2 h z e z The block diagram for u z h z is shown below gt b b h z N zt cle 71 Ei Az 1 N b u z u Z _ 1 m A by b Z
393. ype a sfix 16 a Class FIX IsSigned 1 MantBits 16 float sfrac sint ufix ufrac uint 9 31 sfrac Purpose Syntax Description Example See Also 9 32 Create a MATLAB structure describing a signed fractional data type a sfrac TotalBits a sfrac TotalBits GuardBits sfrac TotalBits returns a MATLAB structure that describes the data type of a signed fractional number with a word size given by TotalBits sfrac TotalBits GuardBits returns a MATLAB structure that describes the data type of a signed fractional number The total word size is given by TotalBits with GuardBits bits located to the left of the sign bit sfrac is automatically called when a signed fractional data type is specified in a block dialog box The default radix point for this data type is assumed to lie immediately to the right of the sign bit If guard bits are specified they lie to the left of the radix point in addition to the sign bit Define an 8 bit signed fractional data type with 4 guard bits Note that the range of this number is 24 16 to 1 22 8 24 15 875 a sfrac 8 4 a Class FRAC IsSigned 1 MantBits 8 GuardBits 4 float sfix sint ufix ufrac uint show fix ptsimranges Purpose Display the logged maximum and minimum values from the last fixed point simulation Description Theshowfixptsimranges script displays the logged maximum and minimum values from the last fixed point si
394. ype supported by the blockset Direct Feedthrough Yes Scalar Expansion Yes Rate Limiter Purpose Library Description Parameters and Dialog Box Characteristics Limit the rising and falling rates of the signal Nonlinear TheRateLimiter block isa masked block that limits the rising and falling rates of the signal Use the Rising slew rate parameter to set the limit on the rising rate of the signal Use the Falling slew rate parameter to set the limit on the falling rate of the signal Block Parameters Rate Limiter r Fixed Point Rate Limiter mask link Limit rising and falling rates of signals Parameters Rising slew rate fe Falling slew rate q FF Cancel Help Apply Rising slew rate Limit on the rising rate of the signal Falling slew rate Limit on the falling rate of the signal Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough Yes Scalar Expansion Yes 10 169 Rate Limiter Dynamic Purpose Limit the rising and falling rates of the signal Library Nonlinear Description The Rate Limiter Dynamic block is a masked block that limits the rising and falling rates of the signal up u P The external signal up sets the upper limit on the rising rate of the signal The external signal lo sets the lower limit on the falling rate of the signal Parameters and Dialog Box Block Parameters Rate Limiter Dynamic
395. ys converted before any arithmetic operations are performed Additionally parameters are always converted offline using round to nearest and saturation Offline conversions are discussed below For information about parameter conversions for a specific block refer to Chapter 10 Block Reference Offline Conversions An offline conversion is a conversion performed by your development platform for example the processor on your PC and not by the fixed point processor you are targeting For example suppose you are using a PC to develop a program to run on a fixed point processor and you need the fixed point processor to compute oabi e y Z u cu over and over again If a b and c are constant parameters it is inefficient for the fixed point processor to compute ab c every time Instead the PC s processor should compute ab c offline one time and the fixed point processor computes only C u This eliminates two costly fixed point arithmetic operations Signal Conversions Consider the conversion of a real world value from one Fixed Point Blockset data type to another Ideally the values before and after the conversion are equal Va Vb 4 27 4 Arithmetic O perations 4 28 where Vp is the input value and V is the output value To see how the conversion is implemented the two ideal values are replaced by the general slope bias encoding scheme described in Scaling on page 3 5 Solving for the output
396. z Parameters and Dialog Box Conversions Characteristics 10 112 Delay a signal N sample periods Delays amp Holds The Integer Delay block delays its input by N sample periods The block accepts one input and generates one output both of which can be scalar or vector If the input is a vector all elements of the vector are delayed by the same sample period Block Parameters Integer Delay r Fixed Point Integer Delay mask link Delay a signal N sample periods Parameters Initial condition PO Sample time E AA Number of delays 4 Cancel Help Apply Initial condition The initial output of the simulation Sample time Sample time Number of delays The number of periods to delay the input signal The Initial condition parameter is converted from a double to the input data type offline using round to nearest and saturation Input Port Any data type supported by the blockset Output Port Same as the input Direct Feedthrough No Scalar Expansion Of input or initial conditions Integrator Backward Purpose Library Description KTsz b z 1 Remarks Parameters and Dialog Box Perform discrete time integration of a signal using the backward method Calculus Thelntegrator Backward block performs a discrete time integration of a signal using the backward method The block multiplies the input by the weighted sample time and adds the result to the cumulative sum since time
Download Pdf Manuals
Related Search
Related Contents
PAR 36 PAR 56 PAR 64 LED PAR user manual Edsal 630 Instructions / Assembly HRC 20 - 30 - 40 Cisco 10-ft Low Loss Cable USER'S MANUAL GLIMMPSE User Manual Copyright © All rights reserved.
Failed to retrieve file