Вы находитесь на странице: 1из 30

University of Twente

EEMCS / Electrical Engineering


Control Engineering

PID controller in FPGA

Armen Karapetian

Pre-doctoral assignment

Supervisors:
J. van Amerongen
dr.ir. J.F. Broenink
ir. M.A. Groothuis

November 2006

Report nr. 035CE2006


Control Engineering
EE-Math-CS
University of Twente
P.O.Box 217
7500 AE Enschede
The Netherlands
i

Abstract
This project is a visibility and test study on the implementation of a PID controller on FPGA (Field-
Programmable Gate Array). An algorithm to support the design of FPGA-hosted controllers semi-
automatically was developed during the project.
The project was started with an existing 20-sim model of a PID controller for the Linix setup and
ended with a model in VHDL (Hardware Description Language) code. A stepwise design flow
described in the report was used to achieve a correct realization in form of control-computer code.
Each step of design phase was closed with a verifying simulation. Due to incomplete software VHDL
design is ended with simulation and executable for FPGA code is not tested on hardware. However,
the VHDL code is simulated. A test version of an IEEE fixed point package, written in VHDL, was
used for the implementation of the PID controller in VHDL code.
20-sim was used as development software. After extensive analysis of different ways of numbers
representation and rounding methods an extension to 20-sim was made to test the accuracy of models
in fixed point format. For future design of controllers the time saving design algorithm which is
developed during this project can be used.

Samenvatting
Dit project is een zichtbaarheid en test studie naar de implementatie van een PID regelaar in FPGA
(Field-Programmable Gate Array). Tijdens het project een algoritme is ontwikkeld ter ondersteuning
van een semiautomatische methode voor het ontwerp van regelaars in FPGA.
Het project is begonnen met een bestaand model van een PID regelaar voor de Linix setup in 20-sim
en beindigd met een model in VHDL (Hardware Description Language) code. De stapsgewijze
design flow beschreven in dit verslag is gebruikt voor en correcte realisatie in de vorm van een regel-
computer code. Elke stap in de ontwerp fase is afgesloten met een verificatie simulatie. Ten gevolge
van een niet complete software, het VHDL ontwerp is beindigd met simulatie en de uitvoerbare op
FPGA code is niet getest in hardware. Nochtans, de VHDL code is gesimuleerd. Test versie van een
IEEE fixed point package in VHDL is gebruikt voor de implementatie van de PID regelaar in VHDL
code.
20-sim is gebruikt als ontwikkelings software. Na een uitgebreide analyse van verschillende manieren
van nummer representaties en afrondings methoden, 20-sim is uitgebreid voor het testen van precisie
van fixed point modellen. Het tijdbesparend algoritme, dat is ontwikkeld tijdens het project kan in
toekomstige ontwerpen gebruikt worden.

Control Engineering
ii PID controller in FPFA

Preface
This report describes my Pre Doctoral assignment of Electrical Engineering study at the University of
Twente.
I would like to thank Marcel Groothuis and Jan Broenink for providing me with this interesting
assignment and being always helpful when I had problems.
I would also thank Bert Molenkamp for being always ready to answer my questions about fixed point
package.

Armen Karapetian
Enschede, October 2006.

University of Twente
iii

Control Engineering
iv PID controller in FPFA

Contents

1 Introduction ................................................................................................................................... 1
1.1 Design trajectory .................................................................................................................... 1
1.2 FPGA ..................................................................................................................................... 1
1.3 Goal of the project.................................................................................................................. 2
1.4 Project design flow................................................................................................................. 3
1.5 Report outline......................................................................................................................... 3
2 Background .................................................................................................................................... 5
2.1 Floating point ......................................................................................................................... 5
2.2 Fixed point ............................................................................................................................. 6
2.3 Integer .................................................................................................................................... 8
2.4 Conclusions............................................................................................................................ 8
3 Design in 20-sim............................................................................................................................. 9
3.1 Preparation ............................................................................................................................. 9
3.2 Fixed point extension in 20-sim............................................................................................. 9
3.3 20-sim models ........................................................................................................................ 9
3.4 Simulation results................................................................................................................. 11
3.5 Conclusions.......................................................................................................................... 12
4 VHDL design................................................................................................................................ 13
4.1 Fixed point package ............................................................................................................. 13
4.1.1 Rounding.......................................................................................................................... 13
4.1.2 Conversions ..................................................................................................................... 14
4.1.3 Sizing rules ...................................................................................................................... 14
4.2 From C to VHDL ................................................................................................................. 15
4.3 ModelSim simulation results ................................................................................................ 16
4.3.1 Test on overflow .............................................................................................................. 17
4.4 Results comparison .............................................................................................................. 17
4.5 Implementation on an FPGA ............................................................................................... 19
4.6 Conclusions.......................................................................................................................... 19
5 Conclusions and Recommendations........................................................................................... 21
5.1 Conclusions.......................................................................................................................... 21
5.2 Recommendations................................................................................................................ 21
Appendix I Fixed point dll template in 20-sim................................................................................ 22
Appendix II Simulations in ModelSim ............................................................................................. 23
Literature ............................................................................................................................................. 24

University of Twente
1

1 Introduction
This chapter begins with introduction of design trajectory traditionally used during controller design.
Then background information on FPGA is given with focus on features which are important for this
project. The assignment and the design trajectory which was followed during the project will be also
discussed in this chapter.

1.1 Design trajectory


To achieve a good realization in form of control-computer code, stepwise refinement process as
described in Figure 1 is needed (Broenink and Hilderink, 2001). Simulations play an important role in
the verification procedure. This should be done after each design step.

Physical Control ECS


System Law Implementation Realization
Modeling Design

Verification Verification Verification Validation


by by by and
Simulation Simulation Simulation / Testing
Model Checking

Figure 1: Design trajectory for embedded control systems

Steps of design trajectory:


Physical system modeling: Dynamic behavior of plant
Control Law Design: Model of controller. Devises are ideal
ECS Implementation: Effects of hardware are taken into account. The controller law is translated
into computer code
Realization: Implementation phase to real embedded system.
Different parts of an ECS can be developed separately, provided that the overall model is competent
for testing. This implies that development process can be organized as a concurrent engineering
activity. For modern system development, this is an essential feature.
The ECS implementation can be realized on different hardware. Till now this was done in most of the
cases on CPU, microcontroller or DSP. These are specific processors. There is a trend towards
applying more programmable devices such as FPGAs to be more flexible during the design, but also to
create possibilities for upgrading.

1.2 FPGA
The controller will be designed for a 200K gate Xilinx Spartan 2 FPGA. Xilinx Spartan 2 does not
have a floating point unit on board. This FPGA is used on the MESA 4I65- general purpose
programmable I/O card for the PC/104-PLUS bus. The FPGA configuration is downloadable from the
PC, allowing creation of almost any kind of specialized I/O function, even including micro-controller
in FPGA.
Spartan 2 (see Figure 2) FPGA features:
5,292 logical cells with 200,000 system gates
System clock 200 MHz (33 MHz PCI clock, 50 MHz crystal oscillator and 4xPLL up to 200
MHZ)
Total distributed 75,264 bits RAM
Unlimited reprogrammability
16 selectable I/O standards
Four dedicated DLLs (Delay- Locked Loops)
Flexible CLBs (Configurable Logic Blocks)

Control Engineering
2 PID controller in FPGA

Figure 2: Basic Spartan-2 Family FPGA Block Diagram


In earlier projects the Spartan-2 FPGA was configured for DC motor control using the PC for the
controller calculations. For this project the following existing VHDL code block can be used:
12 bits PWM generator
32 bits Encoder counter
General purpose bidirectional I/O
PCI address decoder
This information is essential when the design step from Control law to ECS implementation (see
Figure 1) will be realized.

1.3 Goal of the project


As was mentioned in previous section there is a trend towards applying FPGAs as an ECS
implementation. This was the motivation to start the project. Futuremore the Xilinx Spartan 2 was
already used at Control Engineering Lab for I/O interfacing. So combining the Control Law and I/O
interfacing in one FPGA is also interesting.
The goal of the project is to implement a PID controller, designed in 20-sim, in a FPGA. To make it
more clear the start is a given PID controller modeled in 20-sim and the result is a VHDL code for a
DC motor control implemented on a FPGA Xilinxs Spartan 2.
FPGA technology gives the possibility to implement high-speed controllers with high flexibility,
because of high sampling rates and low cost. The FPGAs available for this project have 200,000 gates
and no floating point unit on board. This is why the design of a controller must be based on integer or
fixed point mathematics.
Because of the parallel structure of a FPGA, a several controllers can work independent on one FPGA
at the same time. Also by implementing different controllers in a parallel for same application, it could
be easy to switch between the controllers to adapt the system to changing environmental parameters.
With reconfigurable hardware, it is possible to design an application-specific hardware along with the
high flexibility of software solutions. Particularly for controllers, parallelism can be used as needed
and the implementation can be changed if required.
Modern controller design methods try to support the design of controllers at least semi-automatically.
The need for a transparent and straightforward design process often leads to software implementation
of controllers, that is, microprocessor programs specified in a high-level language using floating point
arithmetic. This approach is inappropriate for applications with a high sampling rate.

University of Twente
Introduction 3

Another aim of the project, is to support the design trajectory for controller design by giving the
possibility to generate the controller semi-automatically, starting in 20-sim and ending with proper
VHDL code for FPGA usage.

1.4 Project design flow


For design of a PID controller in FPGA the scheme of Figure 1 was used. This section describes
detailed the design flow of this project where the step between Control law design and Realization is
divided in several steps.
In Figure 3, the project design flow of this Predoc project is illustrated. Small steps are made during
design to control the effects of changes in model. After each step verifications with simulations are
done.

Model in Scaled Scaled and Model in Code


floating Rounded fixed Target
Model generation
point Model point
20-sim VHDL

Figure 3: Project Design Flow

The design of a PID controller is started with a floating-point controller model in 20-sim. For this
project, an existing controller and plant model were used. 20-sim does not have a tool to design a
model with fixed point arithmetic. For this purpose the program was extended with C code generation
for fixed point values. The C code in fixed point format is generated and then used for simulations. In
that way model of controller in fixed point format was tested.
In next three steps of design the ideal model is replaced with hardware dependent models. First of all
the input and output signals of controller are scaled for a specific FPGA configuration. Then these
signals are rounded to make the model more close to real hardware. In the last design step in 20-sim
the fixed point model is used, because the calculations in FPGA will be realized with a fixed point
math. Only now, all hardware effects are taken into account.
Going towards fixed point realization the same simulation results as in floating point model must be
achieved with minimal cost function, where the cost function is the length of a number used for
representation of signals in fixed point format.
When the design which is supported with 20-sim is ready, the minimal resolution of signals in fixed
point format is founded. This resolution is needed to have a proper controller behavior. To write the
code of controller in VHDL the structure of controller in 20-sim is used. The resolution of signals
from 20-sim model in fixed point is preserved. When the design of controller in VHDL is ended the
simulation result in 20-sim and ModelSim (VHDL simulation and debug environment) should be
compared for the last check.
The last step of design is synthesis of VHDL code in FPGA and test on real target.

1.5 Report outline


Chapter 2 discusses the background information on floating and fixed point math. Chapters 3 and 4
describe the design of controller first in 20-sim and then in VHDL. Both chapters conclude with
simulation results. Also the results of all simulations are compared in chapter 4.
Issues during synthesis are discussed in chapter 5.
At the end of report some conclusions and recommendations are made.

Control Engineering
5

2 Background
As was mentioned earlier, the Xilinx Spartan 2 does not have a floating point unit on board. This is
why fixed-point number representation must be used for this FPGA and not the traditional one used
for computersfloating point representation.
The issues which arrive with different representation ways are: loss of precision, overflow and
underflow.
For better understanding the problems with different ways of number representation, this chapter also
discus how numbers could be represented and what the issues which could arrive are.

2.1 Floating point


Real numbers could be represented on computers in a several ways. The floating point representation
is the most commonly used solution and basically represents reals in scientific notation. (Cooling,
2003)
Floating point numbers have following representation: M*be
M is the mantissa
b is the radix
e is the exponent.
For example, 123.456 could be represented as 1.23456 102.
Floating-point employs a sort of "sliding window" of precision appropriate to the scale of the number.
This allows it to represent numbers from 1,000,000,000,000 to 0.000,000,000,000,000,1 with ease.
The following Table 1 shows the layout for single (32-bit) and double (64-bit) precision floating-point
values. The number of bits for each field are shown (bit ranges are in square brackets).

Sign Exponent Fraction Bias

Single Precision 1 [31] 8 [30-23] 23 [22-00] 127

Double Precision 1 [63] 11 [62-52] 52 [51-00] 1023

Table 1: Layout of floating point

In the IEEE single-precision representation of a real number, one bit is reserved for the sign, and it is
set to 0 for a positive number and to 1 for a negative one. A representation of the exponent is stored in
the next eight bits, and the remaining twenty-three bits are occupied by a representation of the fraction
of the number.
The exponent, which is a signed integer in the range from -126 to 127, is represented neither as a
signed magnitude nor as a twos-complement number, but as a biased value. The idea here is that the
integers in the desired range of exponents are first adjusted by adding a fixed bias to each one. The
bias is chosen to be large enough to convert every integer in the range into a positive integer, which is
then stored as a binary numeral. The IEEE single-precision representation uses a bias of 127.
For example, the exponent -5 is represented by the eight-bit pattern (01111010)2, which is the binary
numeral for 122, since -5 + 127 = 122. The least exponent, -126, is represented by (00000001)2 (since
-126 + 127 = 1); the greatest exponent, 127, is represented by the binary numeral for 254,
(11111110)2.
The mantissa represents the precision bits of the number. It is composed of an implicit leading bit and
the fraction bits.
For double precision, the exponent field is 11 bits, and has a bias of 1023 (Hollasch, 2005).

Control Engineering
6 PID controller in FPGA

2.2 Fixed point


A fixed point number is a value with an integer and fractional part, where the integer and fractional
part are described by a fixed range of binary digits (Maxfield and Brown, 2005). Positive and negative
values can also be represented as fixed point numbers. Where positive and negative numbers are
represented by the same notation, one bit is used to hold the sign of the number (see Table 2).

Position
Bit Index Bit index
of radix point

11 10 9 8 7 6 5 4 3 2 1 0 1 2 3 4

Sign Integer part Fractional part

Table 2: Fixed point representation

For binary values fixed point representation will be as illustrated in Figure 4. In this figure given an
example of 8-bit binary sign-magnitude fixed-point representation comprising a sign bit, three integer
bits, and four fractional bits.
Because binary representation and rounding algorithms are techniques commonly used in hardware
implementations constructed out of physical logic gates, extra attention is paid to these techniques.

Figure 4: Binary fixed point representation

Mathematically Figure 4 generally can be represented as:


(X2 X1 X0 . X-1 X-2)2 = X2*22 + X1*21 + X0*20 + X-1*2-1 + X-2*2-2 + X-3*2-3 (1)
In case of the particular example in Figure 4, specified three integer bits that can be used to represent
an integer in the range 0 to 7. Thus, the combination of the sign bit and the three integer bits allows
representing positive and negative integers in the range -7 through +7. There is no precision loss in
integer part because all numbers can be represented by combining bits of the integer part (Figure 5
left).

University of Twente
Background 7

Figure 5: Integer (left) and fractional (right) part

An overflow will occurs when the result of an arithmetic operation is too large to fit into the fixed
representation of a fixed point number. In the example if the number is out of range -7 through +7, this
number could not be represented. It is common in fixed point calculations to use for numbers which
are out of range the largest possible value.
The representation of fractional part is illustrated in Figure 5 (right). The fractional portion of the 8-bit
field: the first fractional bit is used to represent 1/2 = 0.5; the second fractional bit is used to represent
0.5/2 = 0.25; the third fractional bit is used to represent 0.25/2 = 0.125, and the fourth fractional bit is
used to represent 0.125/2 = 0.0625. Thus, four bit field allows representing fractional values in the
range 0.0 through 0.9375 as shown in Figure 5 (right) (of course, more fractional bits would allow to
represent more precise fractional values). If number is smaller then 0.0625 an underflow will occur.
Underflow will occur when the result of an arithmetic operation is too small to fit into the fixed
representation of a fixed point number. In this case all positive numbers smaller than 0.0625 will be
represented as 0.0625.
It is now visible that the precision of the numbers representation is dependent on numbers of bits of
fractional and integer parts. In other words, an error is generated during the calculations. The size of
the error depends on number of bits used for representation and whether numbers are truncated or
rounded. Truncation cuts off the less significant digit of the true numbers to represent them. Rounding
adjusts the true value to nearest possible for representation number.
Truncation:

Figure 6: Truncation

As example, consider a number is a sign-magnitude binary value of 0101.0100, which equates to


+5.25 in decimal. If simply truncate this by removing the fractional field, result will be an integer
value of 0101 in binary, or +5 in decimal. Similarly, consider another value of 0101.1100, which

Control Engineering
8 PID controller in FPGA

equates to 5.75 in decimal, then truncating the fractional part results in an integer value of 0101 in
binary, or 5 in decimal (see Figure 6).
Rounding to nearest:

Figure 7: Rounding to nearest

For rounding to nearest, first 0.5 is added to the original value and then truncated (see Figure 7). In
case of positive values this algorithm rounds to the next integer for fractional values of 0.5 and higher.
For example, +5.5 is rounded to +6. For negative, -5.5 is rounded to -6.
It is clear that truncation can generate an error as great as a least significant digit. For example if this
value is 1, giving an error range of 0 - 1. With rounding this maximum is reduced by one half, giving
an error range of 0 - 0.5.
Summering the theory discussed above, the advantages and disadvantages of fixed point arithmetic
are:
Advantages:
Arithmetic and logical operations may be performed on fixed point numbers using integer
arithmetic which is quicker and supported in FPGA.
A fixed point number representation uses less memory to store values. Low costs during
implementation.
Disadvantages:
It is easy for an arithmetic operation to produce an "overflow" or "underflow".
A fixed point number has a limited integer range.
A fixed point number has limited accuracy. A suitable representation must be chosen for different
needs.

2.3 Integer
If a number is represented in integer format the rules of fixed point calculations are applicable to it.
Integer is in fixed point format a number with the length of fractional part equal to null. No extra focus
needed on this topic.

2.4 Conclusions
Using the information shown in this chapter the stepwise design (see Figure 3) was started.
Implementation of the ideas of fixed point number representation and rounding to nearest is discussed
in next chapter. This chapter deals with design in 20-sim.

University of Twente
9

3 Design in 20-sim
The effects of fixed point computation which are prototyped in 20-sim are discussed in this chapter. A
basic controller is used as a running example. Some steps as preparation for design and a fixed point
extension for 20-sim which were needed for this stage of design trajectory are also mentioned in this
chapter.

3.1 Preparation
Before the design of controller was started the software which will be used during the project should
be chosen. There are two possibilities: Simulink or 20-sim. Simulink has the functionality of testing
models with fixed point mathematics and code generation in VHDL is supported using external tools,
but to use the fixed point facilities, a license is needed. The license for fixed point facilities of
Simulink was not directly available, so the design in 20-sim was started. Furthermore, a running
example of a basic controller (Linix PID) was also modeled in 20-sim.
Different tests were done, to check the working of 20-sim when values of signals are rounded. All
math operations which were used in next stage of design were tested. Because 20-sim is based on
floating point math, it was reasonable to check what is really happened when rounding is externally
applied (signals changed from real to integer). 20-sim works as expected.

3.2 Fixed point extension in 20-sim


To make the design process semi-automatic an extension was made for 20-sim. This extension gives a
possibility to translate a model in floating point to fixed point C code in one step. With that extension
the designer can test a models behavior in a fixed point format. The math of computer calculations in
20-sim stays in floating point.
This functionality is achieved with a FixedP class and, for this purpose changed version of the 20-sim
template for C code generation (see Appendix I). This was done because 20-sim itself always
calculates in floating point, even when integers are used.
Two parameters are used for conversion to fixed point: INTEG and FRAC. These parameters define
the length of integer and fractional parts of a fixed point number. Sum of INTEG and FRAC are the
cost function. Because we want to achieve same result as in simulations in floating point with minimal
resolution of integer and partial parts in fixed point.
The length in bits of the integer and the fractional parts can be chosen by the designer. This should be
done in C code generated from the model. The working of FixedP class is based on the fixed point
theory discussed in chapter 2. Numbers are represented with powers of two and rounding to nearest
technique is applied. When an overflow occurs, the maximal possible value is written to the number.

3.3 20-sim models


After all preparations are finished the design of controller can be started. In Figure 8 the four steps of
design in 20-sim which were introduced in chapter 1 are illustrated (see Figure 3).

Model in Scaled and Model in


Scaled
floating Rounded fixed
Model
point Model point
20-sim

Figure 8: Design flow in 20-sim


During the design and simulation in 20-sim, the model in Figure 9 was created. Each submodel
indicates one of the design steps.

Control Engineering
10 PID controller in FPGA

1. Ideal model

Discrete
-1 D
Converted Z A
Real Delay1 PWM Plant
Scaled/Rounded Controller

Sample1 Encoder

2. Scaled model

-1 D
Scaling Z A
Delay2 DA2
1 Plant2
K Cont_sc K

K
setpoint in rad (angle) Sample2 Encoder2
16,33 rad

3. Scaled and Rounded model


SetpointGenerator

-1 D
Z A
Scaling & Rounding
Delay3 DA3
Plant3
K Cont_round 1
K

K Difference1
Sample3 Encoder3

4. Model in fixed-point

-1 D
Scaling & Rounding dll Z A
Delay4 DA4
Plant4
K Cont_fix_dll 1
K

K Difference2
Sample4 Encoder4

Figure 9: 20-sim models

Four independent models are illustrated in this figure, they are explained below:
1. Ideal model
The first model is an ideal model of a DC motor (plant) and a PID controller. All signal values are in
type real. This is the given model.
2. Scaled model
Because we have to use this model on specific FPGA (Xilinx Spartan 2) hardware, scaling is needed.
Input and output signals are scaled, to have the ranges supported in the FPGA. The second model is a
copy of the Ideal model with an extra submodel: Scaling. This submodel exists of two multipliers and
one divider. Property of multipliers K is to scale the inputs of controller (encoder and setpoint signals)

University of Twente
Design in 20-sim 11

for a particular hardware. The divider has the same functionality, making the PWM output of
controller in ranges acceptable in hardware which will be used in realization phase.
After scaling the controller is tuned for the new input values. Because the inputs of the controller are
changed from radians to pulses per revolution (from 2 radians to 2000 pulses), the parameters of the
controller are changed to achieve the same behavior of plant as in first model. This second model is
used during all simulations in 20-sim as a reference point. A good result is achieved if the simulation
results (Plant outputs) of Scaled and rounded model and model in fixed point differ within one percent
from this one.
3. Scaled and rounded model
In the third model all inputs and outputs of the PID controller are rounded to integer values. Signal
types of Encod_out, Setpnt_out and PWM_in in submodel Scaling&Rounding are chosen as integers.
This is done to achieve more realistic situation, where the input signals of an FPGA are integers. But
still all calculations in controller are done with floating point math.
4. Model in fixed point
The fourth model is a C code version of a controller generated in 20-sim using the designed fixed
point template. This C code is generated from the third model. The starting point was a resolution of
seven bits for integer and fraction part. But this was not enough to achieve a good result, with
difference between output signals of Plant2 and Plant4 (Difference 2) compared to reference model
smaller then one percent. After some simulations it was clear what are the needed resolutions and
length of fractional part. The resolution of both integer and fractional parts must be at least 13 bits.
This gives the Difference 2 compared to output signal of Plant2 smaller then one percent.

3.4 Simulation results


In this section, the simulation results of all four models are illustrated. The top signal in Figure 10
shows the set point signal, followed by the positions and PWM signals of the four models with the
same order as in Figure 9. After each new model is added the simulation was repeated. Results were
compared. Profiles of all Plant positions must be the same. End position should be achieved quickly
and without overshoot and oscillations. That is true for all four simulations done (see Figure 10,
Position 1-4).
The output of the PID controller in the scaled model fluctuates less than in the ideal model. The
controller is tuned good. The PWM outputs of PID2, PID3 and PID4 are nearly identical. It was also
necessary that after each new stage these signals stay the same.

Control Engineering
12 PID controller in FPGA

model

10 Set point
0

10 Position1 {rad}
0

10 Position2 {rad}
0

10 Position3 {rad}
0

10 Position4 {rad}
0
2
0 PID1
-2
2
0 PID2
-2
2
0 PID3
-2
2
0 PID4
-2

0.004
0 Difference1
-0.004
0.01

0 Difference2
-0.01
0 1 2 3 4 5 6 7 8
time {s}

Figure 10: Simulation results in 20-sim

Difference1 in Figure 10 illustrates the difference between Position2 and Position3. It shows the
rounding fault. More important is Difference2 that indicates difference between output signals of
Plant2 and Plant4 (Difference2 = Position2 Position4), because in the last model the fixed point
values were used in the controller calculations. Maximum of Difference2 that was detected with total
resolution of 26 bits is nearly 0.05 % of maximal Plant2 output signal. The Difference2 is small
enough and VHDL design can be started.

3.5 Conclusions
The design in 20-sim is ended. All hardware specificities as input and output length, the fixed point
number representation in FPGA are taken into account. For next phase of design an important result-
the minimal length of integer and fractional parts of controller input signals (13 bits) is founded.
Next chapter describes the design in VHDL.

University of Twente
13

4 VHDL design
This chapter describes the design of PID controller in VHDL. This stage of design consists of two
steps: code generation and implementation on target, which are illustrated in Figure 11.

Code
Target
generation

VHDL

Figure 11: Design flow in VHDL


As was mentioned earlier, the major problem for implementation in a FPGA is that FPGAs cannot
calculate with floating point without external support code or fixed point unit onboard. That why, for
signal conversion and fixed point calculations, an experimental version of a fixed-point package was
used.
This way of design was chosen, because, first of all it is time saving. Second, it is proposed by the
VHDL design group to make this fixed point package an IEEE standard. If this package becomes a
standard, there will be already experience using it.

4.1 Fixed point package


This package is a step between integer math and floating point. It has the advantage of being almost as
fast as numeric_std (designed for integer values), but it is able to represent numbers that are less than
one. A fixed point number has an assigned width and as assigned location of decimal point. Because it
is based on integer math, it is highly efficient.
The fixed point package has a vast range of functions for rounding, conversion and sizing.

4.1.1 Rounding
The VHDL function resize can be used to fix the size of the output. The rounding and saturate rules
are also applied in the resize function. The syntax of this function is illustrated in Code block 1.

a <= resize((inp1*input2), length); or a <= resize((inp1*input2) ), integ, -frac);

Code block 1: Resize

The length and (integ + frac) are widths of resized output.


The data widths in the fixed point package are designed so that there is no possibility of an overflow.
To handle the overflow different possibilities are developed in fixed point package.

a <= resize ( arg => a + 1,


left_index => ahigh,
right_index => alow,
round_style => fixed_truncate,
overflow_style => fixed_wrap) ;

Code block 2: Rounding and truncation

The round_style default to fixed_round (true) that turn on round routines. If false
(fixed_truncate), the number is truncated. Rounding is done in similar way as rounding to nearest in
floating point math.

Control Engineering
14 PID controller in FPGA

Using guard bits more precise rounding is possible. Guard_bits default to fixed _guard_bits,
which by default is equal to three. These extra bits are added to the end of the numbers in division and
to_real functions to make the calculations more accurate. If guard is set to null, the rounding is
automatically turned of.
overflow_style defaults to fixed_saturate (true) that returns the maximum possible number, if the
number is too large to represent. If fixed_wrap (false) is chosen, the top bits will be truncated. Thus,
it is possible to get positive result when resizing a negative number in this mode.

4.1.2 Conversions
Conversion functions have been created for INTEGER, REAL, SIGNED, and UNSIGNED types.
These functions are important for the design of a controller, because all input and output signals of
controller are INTEGER types and the rest is in FIXED POINT.
This conversion function is illustrated in Code block 3.

a <= to_sfixed (inp1, integ, -frac);

Code block 3: Conversion to fixed point

Conversion function is used with a set of parameters. The construction of this function is similair to
resize. Returns inp1 sized into signed fixed point format with (integ+frag) width and integ
upper and frag lower indexes.
Fixed point package has a function to convert the FIXED POINT type to a std_logic_vector. The
length of vector can be chosen by the designer (see Code block 4).

a <= to_signed (inp1, length);

Code block 4: Conversion to STD_LOGIC_VECTOR

Returns inp1 sized into VHDL std_logic_vector format with length width.

4.1.3 Sizing rules


In Table 3 the sizing rules for operations used in the project are illustrated.

Operation Result range


A+B Max(Aleft, Bleft)+ 1 dowto Min( Aright, Bright)
AB Max(Aleft, Bleft)+ 1 dowto Min( Aright, Bright)
A*B Aleft+ Bleft+ 1 dowto Aright+ Bright
A/B Aleft- Bright+ 1 dowto Aright+ Bleft
Table 3: Sizing of unsigned fixed point

For example, if we multiply X by Y the result will be as illustrated in Code block 5.

signal X : ufixed ( 7 downto -3);


signal Y : ufixed ( 7 downto -3);
X * Y = ufixed (7 +7+ 1 downto -3+ (-3)) or X * Y = ufixed (15 downto -6)

Code block 5: Sizing after multiplication

Starting with fixed point number of length (7 downto -3) the result will have length

University of Twente
VHDL design 15

(15 downto -6).To keep the same length for all numbers in calculation function rezise can be used.
(Bishop, 2006)

4.2 From C to VHDL


Finally the code of PID controller is translated from C to VHDL. Using fixed point package the design
in VHDL became possible.
In Code block 6 code examples of 20-sim model and VHDL code are compared.

20-sim
factor = 1 / ( sample time + tauD * beta );
uD = factor * ( tauD * prev ( uD ) * beta + tauD * kp * ( error - prev ( error )) + sampletime * kp * error );
uI = prev( uI ) + sampletime * uD / tauI;
output =uI + uD;

VHDL
---Convert---
setpoint_fix <= to_sfixed(setpoin, integ, -frac);
encoder_fix <= to_sfixed(encoder, integ, -frac);
error <= resize((setpoint_fix-encoder_fix), integ, -frac);
---PID loop---
ud <= resize((factor*kp*(tau_d*(error-prev_error)) + step_size*error), integ, -frac);
ui <= resize (((step_size*ud*divdtau_i) + prev_ui), integ, -frac);

---PWM out---
PWM_fix <= resize ((ud + ui), integ, -frac);
PWM <= to_signed(PWM_fix, 12);
---Data in buffers---
prev_error <= error;
prev_ui <= ui;

Code block 6: 20-sim vs. VHDL

The number of bits for integer and the fractional part from simulation in 20-sim are used in VHDL.
Also the values of all parameters of PID controller and there structure in 20-sim and VHDL are the
same.
Before the controller begins calculations all input signals must be converted to fixed point format.
There for function to_sfixed is used with parameter integ = 13 and frac = 13.
The output signal PWM is also converted from fixed point to std_logic_vector of length 12. Length of
PWM depends on hardware configuration.
After each calculation when the result is written to other signal/variable, function resize is used to
fix the output size.

Control Engineering
16 PID controller in FPGA

4.3 ModelSim simulation results


In Figure 12 is the simulation of PID controller designed in VHDL illustrated.

Figure 12: Simulation results in ModelSim

This simulation was made to check the functionality of PID controller in VHDL and to compare the
results with 20-sim simulations. Each bit value of pwm_fix vector is shown in Figure 12. This is done
to illustrate how the fixed point value represented in this vector. Generalized representation is shown
in formula (1). In our case position of the radix point is between bit index 0 and -1. The value of
pwm_fix can be calculated as follows:
pwm_fix =
= 0*213+ 0*212+ 0*211+ 0*210+ 0*29+ 0*28+ 1*27+ 0*26+ 0*25+ 1*24+ 1*23+ 1*22+ 1*21+ 1*20+
+ 0*2-1+ 0*2-2+ 0*2-3+ 1*2-4+ 0*2-5+ 0*2-6+ 0*2-7+ 1*2-8+ 0*2-9+ 1*2-10+ 0*2-11+ 1*2-12+ 1*2-13=
= 159.0677490234375 (1)
After conversion pwm is the value of PWM signal send to motor. In Figure 12 this value is visible:
pwm = 159.

University of Twente
VHDL design 17

4.3.1 Test on overflow


Because the reaction of controller when overflow is occurred is one of the important behaviors, a
separate test is done to check this.

Figure 13: Overflow

During conversion of pwm_fix to pwm an overflow could arise. In FixedP class used in 20-sim when
overflow is occurs the maximal possible value will be written to signal. The same behavior we observe
during the simulation of controller with fixed point package (see Figure 13). The signal pwm_fix with
the length of integer and fraction part equal to 13 must be converted to signal pwm with maximum
length of 2047. From the right side of Figure 13 it is noticeable that the value of pwm_fix is large than
2047 and that the pwm gets the maximum possible value.

4.4 Results comparison


To compare results in 20-sim with ModelSim some changes were made in both models. The encoder
value is the reaction of Plant which is a submodel implemented in 20-sim. But it is impossible to
implement the Plant in a ModelSim simulation. To compare the results in 20-sim and in ModelSim,
the encoder value is therefore made equal to zero. In Table 4 PWM outputs of four controllers are
illustrated.
Setpoint Contr_sc Contr_fix_dll ModSim_Contr Difference Diff (%)
3 792.099 791.1121826172 790.37934140625 0.73284122 0.1
6 1584.198 1582.224365234 1582.81640625 -0.592041016 0.04
12 3168.396 3164.448730469 3161.6328125 2.815917969 0.09
16 4224.528 4219.265014648 4215.51365375 3.751360898 0.09
Table 4: Results comparison

The same model as shown in chapter 4 is used for this comparison test.
The first PWM output in Table 4 is Contr_sc- scaled controller (see Figure 9). Then the result of dll
fixed point model is illustrated. There is a difference in numerical value of PWM outputs of two
models, but this difference (as was illustrated in chapter 4) does not change the behavior of Plant.
In column ModSim_Contr the PWM signal of VHDL model is illustrated.
The column Difference illustrates the difference between last two models: dll model in 20-sim and
VHDL model.

Control Engineering
18 PID controller in FPGA

In the last column Diff is calculated as followed:


Diff = Difference*100/PWM Contr_fix_dll (%)
Difference is small and stays below 0.1 %.
Because of some differences in fixed point implementation in 20-sim and VHDL fixed point package,
the PWM output signals are not the same. It seems that in most of the cases the calculations of dll
model are more precisely than the calculations of fixed point package in VHDL. There could be
different reasons why are the results not exactly the same.
To find out why the results are differing, some tests were done. First of all the controller calculations
which were done in one formula now are done step by step as illustrated in Code block 7. This is done
to check the working of resize function. Because it was not clear if fixed point package uses extra
bits for precision, when all calculations are done in one formula.

ud0 <= to_sfixed((factor*kp), voor, -achter);


ud1 <= resize((step_size*error), voor, -achter);
ud2 <= resize((error-prev_error) , voor, -achter);
ud3 <= resize((tau_d*ud2), voor, -achter);
ud4 <= resize((ud0*ud3), voor, -achter);
ud <= resize((ud4+ud1), voor, -achter);
ui0 <=resize((step_size*ud),voor, -achter);
ui1 <=resize((ui0/tau_i), voor, -achter);
ui <=resize((ui1 + prev_ui), voor, -achter);
PWM_fix <= resize ((ud + ui), voor, -achter);

Code block 7: Splitted formula of controller

Then different values for guarded bits were used and simulations with and without divisions in
calculations of controller were done. The results with setpoint = 16 (FixP result was 4219.265014648)
are illustrated in Table 5.

0 guard bits 3 guard bits


One formula In steps One formula In steps
With 4215.514892578125 4219.25927734375 4215.5142822265625 4215.6341552734375
division
Without 4215.5145263671875 4215.5145263671875 4215.5145263671875 4215.5145263671875
division
Table 5: ModelSim test results

If we compare the results of Table 5 with exact value of 4224.528 which is calculated in floating point
without rounding, the conclusion will be that the result with 0 guard bits and steps of calculations
gives more precise result then the rest. But it is impossible, to obtain more precise result using less
precision in numbers representation and calculations.
The general conclusion is that the error during calculations helps to obtain nearest to exact, but not
more precisely result. Also in this design phase became visible that VHDL fixed point package has a
lot of functionality that is not represented in 20-sim extension which was made in the beginning of
project to test the behavior of the models in fixed point format.

University of Twente
VHDL design 19

4.5 Implementation on an FPGA


Last step of the design of controller is implementation on FPGA. As was mentioned in chapter 2,
Xilinx Spartan 2 FPGA is chosen for this project as the only one available at Control Engineering
Department. Because this FPGA in other projects was used for DC motor control, the configuration
used in previous projects invpwmenc was extended with controller in fixed point. The invpwmenc
had functional blocks to read the input signal (Encoder and Setpoint inputs) and to write to output
signals (PWM output) which were used for current project. Also code block needed for
communication: general purpose bidirectional I/O and PCI address decoder were used. Rest of the
functional blocks was deleted to save the recourses for controller. Then the controller design in fixed
point was added to the configuration.
The last step of these design phase- synthesis of VHDL code to FPGA was done. The proper settings
were chosen for implementation on Xilinx Spartan 2 FPGA. But this part of design was not achievable
with current used at department Xilinx ISE software.
The problem was that the Xilinx ISE does not support synthesis of math_real library. This library is
used in fixed point package.
The synthesis of simplified controller model with fixed point package for Xilinx Spartan 2 was
achieved using LeonardoSpectrum software. Confirming the synthesizability of VHDL fixed point
package. Synthesis is tested at Computer Science Department, because there is no license for this
software at Control Engineering Department.

4.6 Conclusions
Due to unavailability of proper software the last step of design process was not achievable. However,
the important parts of design in VHDL are completed. The VHDL code of PID controller using the
fixed point package is detailed tested. Tests show small difference in results of computations based on
VHDL fixed point package and extension made for 20-sim. The synthesis of VHDL fixed point
package for FPGA is realized using LeonardoSpectrum software.
The semiautomatic design process is possible with VHDL fixed point package and LeonardoSpectrum
software.

Control Engineering
21

5 Conclusions and Recommendations


5.1 Conclusions
It is now possible, using the design steps and extensions made during this project, to design a
controller which is based on fixed point math semi-automatically.
20-sim and Xilinx ISE software were chosen for this project. The other possibility was to use Simulink
(with fixed point extension and VHDL code generation) instead of 20-sim, but a license is needed for
these tools.
There is a difference in exact implementation of conversion and round functions in template designed
for 20-sim and in fixed point package used in VHDL. But the idea of numbers representation in
powers of two which used in fixed point package is also applied in a 20-sim extension. The rounding
style in the VHDL package and in 20-sim is based on round to nearest. The behavior on overflow is
also the same.
Because the project is started with model in 20-sim and later the VHDL fixed point package was used
in design, not all functionality of the package is included in 20-sim fixed point extension.

5.2 Recommendations
If in future 20-sim in combination with fixed point package in VHDL will be used for development of
models with fixed point math, the following extensions are recommended:
1. It is also recommended to use LeonardoSpectrum software for hardware synthesis of fixed point
package. The license for LeonardoSpectrum is needed.
2. Fixed point math support in 20-sim with the identical functionality as VHDL fixed point package.
This will give the designer a possibility to simulate the model which in later stage should only be
translated in VHDL.
3. VHDL code generation. If the functionality of the fixed point math in 20-sim will be based on
fixed point package in VHDL the difference in the code will be minimal as illustrated in Code
block 6.

Control Engineering
22 PID controller in FPGA

Appendix I Fixed point dll template in 20-sim


Steps which should be done to use fixed point extension for 20-sim simulations:
1) Code from Code block 8 must be added to 20-sim Targets.ini file.

[20simDLLstatic]
targetName="20sim Static Dll"
iconFile="20sim.ico"
description="Generate C++ Code for a static DLL-call to be used in 20-sim"
templateDirectory="20simDLLstatic"
templateFiles=%SUBMODEL_NAME%.cpp;%SUBMODEL_NAME%.h;%SUBMODEL_NAME%.info;
templateFiles=xxfuncs.cpp;xxfuncs.h;xxinteg.cpp;xxinteg.h;xxinverse.cpp;xxinverse.h
templateFiles=xxmatrix.cpp;xxmatrix.h;xxmodel.h;xxtypes.h
templateFiles=%SUBMODEL_NAME%.dsw;%SUBMODEL_NAME%.dsp;trace.cpp;trace.h
targetDirectory="c:\temp\%SUBMODEL_NAME%"
postCommand=""

Code block 8: Addition to target.ini

2) Add to existing library ccode directory 20simDLLstatic, developed for fixed point purpose.
3) Follow steps for C code generations in 20-sim. From target list chose 20sim Static Dll. Now
the C code is generated.
4) In file xxtype.h the length of fixed point numbers could be selected. INTEG is the length of
integer part and FRAC is the length of fractional part. Default values of INTEG and FRAC are
set to 13.
5) Use 20-sim help menu for implementation of the dll models. Handlings are the same.
Model can be tested now.

University of Twente
23

Appendix II Simulations in ModelSim


To simulate the VHDL code in ModelSim, first of all the length of integer and fractional parts must be
chosen. This should be done in VHDL controller model and in tbn_pid the test bench files. When the
proper values are chosen this files must be compiled.
Now the simulation can be started with choosing Start simulation in menu of ModelSim. From the
window Simulate go to library work and chose the test bench file tbn_pid and click to ok. Parameters
for visualization in a wave must be chosen. Give the simulation time, the results of simulation are
available now.

Control Engineering
Literature
Broenink J. F and G.H. Hilderink (2001), Structured Approach to Embedded Control implementation,
Proc. 2001 IEEE International Conference on Control Applications, Mexico City, Mexico.
Bishop, D. (2006), Fixed point package.
Cooling, J.E. (2003), Software engineering for real-time systems, ISBN: ISBN 0-201-59620-2.
Hollasch, S., (2005),"IEEE Standard 754 Floating Point Numbers".
Maxfield, C. and A.Brown (October 2005), The Definitive Guide to How Computers Do Math:
Featuring the Virtual DIY Calculator.
Chang, K.C. (1999), Digital system design with VHDL and synthesis: an integrated approach, ISBN:
0-7695-0023-4.
Laan, G. (1998), Aan de slag met C++, ISBN: 90-395-1084-9.
Mano, M.M. (1997), Logic and computer design fundamentals, ISBN: 0-13-182098-2.
Zvolinski, M. (2000), Digital system design with VHDL, ISBN: 0-201-36063-2.
The Mathworks,(2005), Fixed-point toolbox.
Molenkamp, B. (1997), VHDL, VHDL 87/93 en voorbeelden, ISBN: 90-802634-3-5.

University of Twente

Вам также может понравиться