Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ......

148
lektronik abor Circuit and System Design for DSP Principles and Practices Using Matlab and VHDL Prof. Dr. Martin J. W. Schubert, Electronics Laboratory, OTH Regensburg, Regensburg, Germany

Transcript of Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ......

Page 1: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

lektronikabor

Circuit and System Design for DSP

Principles and Practices Using Matlab and VHDL

Prof. Dr. Martin J. W. Schubert, Electronics Laboratory,

OTH Regensburg, Regensburg, Germany

Page 2: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 2 -

Circuit and System Design for DSP

Principles and Practices Using Matlab and VHDL Abstract. An comprehensive example of an A/D and D/A conversion system is used to illustrate several aspects of digital signal processing, digital circuit design, A/D and D/A conversion and analog circuit design for signal conditioning. Advantage is taken from the numerical power of VHDL, Matlab and Spice.

1 Introduction 1.1 Objectives and Organization of this Document This document is intended for students learning time-discrete Signal processing, A/D and D/A conversion as well as electronic design automation using VHDL. It is a comprehensive example that teaches different aspects on the same system. Students within course System Concepts (SK) get a top-level understanding of digital signal processing (DSP) systems, e.g. how to trade speed versus resolution, using ΔΣ converters as work-around to avoid aliasing problems and expensive A/D or D/A converters, and how to manage the required data rate changes. Students of course Electronic Design Automation (RED: Rechnergestützter Entwurf Digital) concentrate on the questions how to translate the theory learned in SK into real-life circuitry. There is no need to make SK and RED at the same time, but formulae given RED will be better understood knowing SK, e.g. how to compute impulse responses of digital filters. Students learning A/D or D/A Converters (ADA) are focused on these data converters in chapter 2, introduce some non-linearity as detailed in chapter 5 and may develop some own Matlab tools to model and measure quality criteria related to A/D and D/A converters such as differential and integral non-linearity (DNL/INL), spurious free dynamic range (SFDR), total harmonic distortion (THD) of effective number of bits (ENOB). Last but not least, students learning analog circuit design (SC: Schaltungstechnik) get key circuits, respective formulae and applications for circuits performing analog signal conditioning. These circuits are offered as ready-to-use recipe, detailed explanation of their operation is given in the author’s lectures of course Schaltungstechnik (SC).

Page 3: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 3 -

Color code of this document: Black text is addressed to everybody. Grey text is useful information (e.g. concerning mathematics) without relevance for exams. Blue text indicates exercises / solutions. Green text is addressed to students learning A/D and D/A conversion only. Pink is addressed to students learning signal processing theory, Brown text is addressed to students learning VHDL-based electronic design automation

only. The organization of this document is as follows: Section 1 is this Introduction, Section 2 makes the user familiar with VHDL related hardware: DE2, DA2 and DS2, boards, Section 3 introduces the A/D/A Conversion (ADAC) system used as example, Section 4 details advanced VHDL modeling techniques for the ADAC model, Section 5 teaches linear and non-linear scaling for Signal Conditioning purposes, Section 6 details Quantization from a mathematical point of view, Section 7 applies sections 5 and 6 to Matlab based A/D and D/A converter models, Section 8 describes Sampling Rate Issues (SK) on a high-level point of view, Section 9 presents Sampling Rate Issues (RED) from circuit designer’s FSM point of view, Section 10 draws relevant Conclusion and Section 11 offers some References

Page 4: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 4 -

1.2 Modeling Levels There are different levels of system design. In this tutorial we use the top 3, i.e. specification, cycle based and event driven, according to the waterfall or V models. Table 1.2: Levels of Modeling Digital Systems

Level Tools Comments Specification Words, Figs.,

Pseudo-C On the top level specification, working with words, figures and so called pseudo-C, i.e. not suitable for simulation, C-like expressions to sketch algorithms.

Cycle Based Matlab, System C/C++

Top-level verification, 300-1000 x faster than VHDL: Assuming synchronously clocked FSM design we can model memory as bit vector mem and next-state logic as function f_ns(stimuli,mem). Then we can compute clock cycle i as mem(i+1) = f_ns(stimuli(i),mem(i)).

Event Driven, Concurrent, Data Flow

VHDL, Verilog Simulation of gates and registers respecting gate delays. This is also called “data flow” level, as energy conservation is lost.

Simultaneous, Conservative

Spice Suitable up to 100 nodes only, as for any time point at any node a solution for all nodes has to be computed. Uses equations based on energy conservation.

Device Pisces 3D-simulation of single devices. After process simulation is done, 3-dimensional voltage and current densities are computed within a device model, typically with finite elements.

Process Suprem 3D-simulation of the device production process, e.g. oxidation, etching, ion implantation, etc..

Page 5: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 5 -

2 Hardware Available Hardware and Software for Hands-on Training The course makes you familiar with the Terasic's DE2 board [1] using Altera's Cyclone II FPGA [2]. More documentation is found e.g. at [3]-[5]. It is assumed that you have Altera’s Quartus II 8.1 software DE2 user manual [3] and the board’s schematics [4]. The last version of Quartus supporting Cyclone II FPGAs is Quartus II 13.1 which can be obtained from Altera. At OTH Regensburg, Quartus II 8.1 and 13.1 can be obtained from the school’s internal network [6]. The DE2-baord is employed to operate the self-made DA2 board, which is concerned with some basic A/D and D/A conversion design techniques. The DS2 grand child board assembles A/D and D/A converters on DA2 board to form a 1st or 2nd order ΔΣ modulator. Use of VHDL VHDL is not case sensitive. In the following KEYWORDS will be written in ALL CAPITAL LETTERS and user defined names in lowercase letters. Exception: Capitalized initials are used for composed self-made names, e.g. AddressBus or DataBus. Self-made data types begin with t_, e.g. t_StateVector. Acknowledgements The author would like to thank Terasic Technologies [1] for admission to use screen copies of Terasic documentation for teaching purposes in this lectures. At 19.09.2014 08:49, Terasic - Dong Liu wrote:

Dear Martin, Thank you for using DE2 board to teach VHDL. Yes, you can open all DE2 design resources for teaching purpose. Thank you! Best Regards, Doreen Liu

Page 6: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 6 -

2.1 DE2 Board

2.1.1 Document DE2_Introduction_box.pdf

This subchapter can be done without the hardware. Have the Altera documentation available or look it up in the internet. DE2 board features: Which FPGA (with how many pin-package) is employed? ............................................................ Specifications: What is the accurate name of the FPGA on the board? (You will have to select it in the Quartus II software) ............................................................

2.1.2 Document DE2_UserManual.pdf (from Internet)

Get an orientation: Look at the Contents and Read the headlines of the five chapters. See Fig. 2.1 of the User Manual (as copied below from [3]):

->>> Docum. ERROR: JP1=GPIO_0 and JP2=GPIO_1 are exchanged in Fig. 2.1 above! Check the board on the image above: Where is the power-on switch, 9V DC Power in, USB Blaster Port, Run/Prog switch, LCD display module, the 7-segment displays, the 18 red and 9 green LEDs, the 18 toggle switches and 4 push buttons, the Cyclone II FPGA and the expansion headers JP1 and JP2, corresponding to GPIO_0 and GPIO_1, respectively? (On the DE2-70 Board we have the GPIO_x names only.)

Page 7: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 7 -

2.1.2.1 Questions Related to the FPGA

How many phase-locked loops (PLLs) does the FPGA have? ............ How many multipliers with how many bits in / out does the FPGA have? You’ll find the I/O bit widths in document → ..\Datasheets\Cyclone_II\cyc2_cii5v1_01.pdf on the DE2-CD. You’ll find it in the internet or at OTHR in file CD_DE2_for_Quartus7.2.zip at K:\SB\Hardware\Altera\DE2_Board_Altera-Cyclone2-EPC2C35\CD_DE2_for_Quartus7.2. ............................................................ The FPGA is connected with a Ball-Grid-Array (BGA). How many pins does it have? .... Organized in how many rows and columns? ............................... (You may find the answer later in the Quartus II software with Assignments → Pins after correct settings of Assignments → Device...) 2.1.2.2 Questions Related to the LEDs and Switches

See chapter "Using the LEDs and Switches" in the User Manual and check signal names with the definitions in file DE2_pin_assignments.csv on the DE2-CD [5]. What are the names of the signals connected to the 18 toggle switches ? ........... What are the names of the signals connected to the 4 push buttons switches ? ........... What are the names of the signals connected to the 18 red LEDs ? ................ What are the names of the signals connected to the green LEDs ? ................ Which level (High/Low) will turn a red LED on? ........... Which level (High/Low) will turn a green LED on? ........... 2.1.2.3 Questions Related to the 7-Segment (7seg) Displays

See chapter "Using the 7-Segment Displays" in the User Manual. What are the names of the signals connected to the 7-segment (7seg) displays ? ............................................................... Which level (High/Low) will turn a LED of the 7-segment display on? ........... Undriven 7-seg.-LEDs are ON. → The FPGA sets undriven output pins to state ........

Page 8: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 8 -

2.1.2.4 Questions Related to the Expansion Headers

Fig. 4.10 from DE2 User Manual [3] shows an extraction of the schematic diagram. (For complete schematics see file DE2_schematics.pdf [4].) The schematics is drawn in unreadable

Page 9: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 9 -

parts. Complete the figure below to deliver a connectedly schematics for the circuitry from the FPGA to Pins 1 and 3 of both, JP1 (=GPIO_0) and JP2 (=GPIO_1). Label all elements: resistors incl. values, diodes, pins at the expansion headers and the FPGA, supply voltages, wire names and their VHDL signal names as defined in the DE2_pin_assignments.csv file.

Fig. 2.1.2.4(a): Cutout of DE2_schematics.pdf [4]. Fig. 2.1.2.4(a) shows a cutout of the DE2 schematics [4]. From left to right: Wire name, chip-pin-name, intended purpose. For us it is the bridge from wire name to pin name. for example wire GPIO_B25 is connected to pin K23. To find this by yourself use the "find" function in Acrobat Reader to find strings like "GPIO_B25" or "K23".

Page 10: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 10 -

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ABCDEFGHIJKLMNOPQRSTUVWXYZ

AAABACADAEAF

1

1

JP2 / GPIO_1

JP1 / GPIO_0

TopView–WireBondAltera-Cyclone2, P2C35F672C6

Figure 2.1.2.4(b): protection circuitry between chip and GPIO expansion header pin.

Page 11: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 11 -

2.1.3 Getting started with Operating the DE2 Board

2.1.3.1 Observe the Board

Check the DE2 board in your hands: Where is the power-on switch, 9V DC Power in, USB Blaster Port, Run/Prog switch, LCD display module, the 7-segment displays, the 18 red and 9 green LEDs, the 18 toggle switches and 4 push buttons, the Cyclone II FPGA and the expansion headers JP1 and JP2? What is the labeling mistake in Fig. 2.1 on page 6? Correction? ..................... Find on the DE2 board all devices that you draw in the figure above. Where are D5 and D41? ............................................................... Connect the power cable to the power plug and switch the red power button ON. All display elements should show some activity now due to a start-up procedure. 2.1.3.2 Installing and Starting the Quartus II Software

(Who needs much more detailed explanations than given in this subchapter is referred to file tut_quartus_intro_vhdl.pdf (30 pages) within DE2-CD\DE2_tutorials\.) First of all we need some preconditions: Create an empty directory on your Windows operating system, name it de2_test. Start Quartus II 8.1 on your computer.

Comment 1: In CIP pools of OTH Regensburg you can start Quartus II version 8.1 and 13.1. Quartus II 13.1 is the last Quartus version that can handle Cyclone II FPGAs, to not use a later version for this boards. Comment 2: In OTHR CIP pools you must activate the USB Blaster (see below) with Quartus II 8.1, because Quartus II 13.1 would require admin rights to do so. After activation with Quartus II 8.1 you can proceed with version 13.1.

Select menu point Create a New Project (New PROJECT Wizard) → Next → “What is the working directory of the project?“: Navigate to…\de2_test” “What is the name of the project?“: → de2_test. Top-level entity name in the 3rd line: de2_test (must be identical with the project name). Click on “Finish”. Exit Quartus II 8.1 Look into your directory de2_test. There is a subdirectory db and the three files

..........................................................

Double click left on the Quatus project file de2_test.qpf. You should now be at the same point as before exiting Quartus II.

Quartus II: File → New → VHDL File

Page 12: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 12 -

Copy entity de2_test from listing 2.1.3.2 into this file. Check: The last characters should be "...con_de2_test;".

Click on save button ( a disc, third symbol from right in the top menu), accept file name de2_test.

Compilation should work now: Processing → Start Compilation. You should see Infos and warnings, but no errors.

After some time you should see: "Full Compilation was successful (xxx warnings"). Click in the Project Navigator window on entry de2_test to see your VHDL code again. Look at the synthesized VHDL code: Quartus II: Tools -> Netlist -> RTL Viewer Listing 2.1.3.2: VHDL test file

-- For Board: Altera DE2 with FPGA Cyclone II EP2C35F672C6 LIBRARY ieee; USE ieee.std_logic_1164.ALL,ieee.std_logic_signed.ALL; ENTITY de2_test IS PORT(CLOCK_50,CLOCK_27:IN std_logic; key:IN std_logic_vector(3 DOWNTO 0); -- low when pressed sw:IN std_logic_vector(17 DOWNTO 0); -- low when pulled down ledg:BUFFER std_logic_vector(8 DOWNTO 0); -- high active ledr:BUFFER std_logic_vector(17 DOWNTO 0); -- high active hex0,hex1,hex2,hex3,hex4,hex5,hex6,hex7:OUT std_logic_vector(0 TO 6); gpio_0:BUFFER std_logic_vector(35 DOWNTO 0); gpio_1:INOUT std_logic_vector(35 DOWNTO 0) ); END ENTITY de2_test; ARCHITECTURE rtl_de2_test OF de2_test IS TYPE t_7seg IS ARRAY(0 TO 15) OF std_logic_vector(0 TO 6); CONSTANT c7seg:t_7seg:=("1111110", "0110000", "1101101", "1111001", "0110011", "1011011", "1011111", "1110000", "1111111", "1110011", "1110111", "0011111", "1001110", "0111101", "1001111", "1000111"); BEGIN gpio_1(17 DOWNTO 0) <= sw; ledr(17 DOWNTO 0) <= sw(17 DOWNTO 0); ledg( 7 DOWNTO 4) <= key(3 DOWNTO 0); ledg( 3 DOWNTO 0) <= key(3 DOWNTO 0); ledg(8) <= sw(0); p_check_hex:PROCESS(sw(0)) BEGIN IF sw(0)='0' THEN hex0<=c7seg(0); hex1<=c7seg(1); hex2<=c7seg(2); hex3<=c7seg(3); hex4<=c7seg(4); hex5<=c7seg(5); hex6<=c7seg(6); hex7<=c7seg(7); ELSE hex0<=c7seg(8); hex1<=c7seg(9); hex2<=c7seg(10); hex3<=c7seg(11); hex4<=c7seg(12); hex5<=c7seg(13); hex6<=c7seg(14); hex7<=c7seg(15); END IF; END PROCESS p_check_hex; END ARCHITECTURE rtl_de2_test; CONFIGURATION con_de2_test OF de2_test IS FOR rtl_de2_test END FOR; END CONFIGURATION con_de2_test;

save: de2_test.vhd → de2_test_sol0.vhd

Note that we have no connection to the DE2 board at this point.

Page 13: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 13 -

2.1.3.3 Connecting the DE2 Hardware: Installing the USB Blaster

Connect the DE2 board’s USB Blaster Port via USB cable caple to your PC. Set the Run/Prog-Switch on Run, connect the USB-Blaster Port of the Board to an USB

slot of your computer. (May be a The New Hardware Wizard appears.) To install the USB-Blaster for a stand-alone computer follow the instructions of

tut_initialDE2.pdf. (You have to install the usb_blaster by leading the system to path <Quartus_insatallation_directory>\quartus\drivers\usb-blaster.)

In the Electronics Laboratory of OTH Regensburg you need to install the USB-Blaster with Quartus II 8.1. Quartus II 13.1 is also available. It is the last Quartus version supporting Cyclone II FPGAs, but it requires admin rights to install the USB blaster. After blaster installation with version 8.1 you can use version 13.1.

Quartus II: Tools → Programmer →Hardware Setup. Double click left on USB-Blaster until you see this tring in the window Currently selected hardware. Then click → Close.

In the Programmer’s window Hardware setup... you should now see the string “USB-Blaster [USB-0]”.

Within the Programmer you should now see the file de2_test.sof, a binary file obtained by compilation, in a line with activated checkbox Program / Configure. The switch left to the 7-segment displays is set to RUN.

Quartus II Programmer → Start. You should now get an error message! This is because we must tell Quartus II which hardware has to be programmed! 2.1.3.4 Running the DE2 Hardware doing the Necessary Assiningnments

Copy file DE2_pin_assignments.csv into your directory de2_test. You’ll find that file either in the internet, e.g.[5], or under Hardware at the author’s home page https://hps.hs-regensburg.de/~scm39115/homepage/education/courses/red/red.htm.

Quartus II: Assignments → Device... → Family: → Cyclone II Device Name: → EP2C35F672C6 → OK

Quartus II: Assignments → Pins: You see now the device setting above, but no pin names assigned → close window.

Quartus II: Processing → Start Cmpilation. You should get a successful compilation! Quartus II: Tools → Programmer → Start.

Blue LED LOAD on the DE2 board should turn on for a while and then the LED GOOD. Observe the DE2 boad immediately after pressing Programmer button Start. It should do something. But the programmed board behaves randomly because the pins are not yet assigned. Switching SWx (x=0...17) shouldn’t change anything.

Quartus II: Assignments → Import Assignments → ... <naviage to file> ... → DE2_pin_assignments.csv → Open → OK.

Quartus II: Assignments → Pins: You now see pin map with pins filled. Quartus II: Assignments → Assignment Editor: You now see a bitg list of assignments. Compile and program file de2_test.sof into the FPGA. Now switch SWx should enlighten

LEDRx (x=0...17) and SW0 should change the 7-segment display. Congratulations! You got it! Your board is ready to be tested now!

Page 14: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 14 -

2.1.3.5 Testing Soft- and Hardware

After successful download of file de2_test.sof into the FPGA we want to understand its functionality the VHDL code lines. The statements ledr(17 DOWNTO 0) <= sw(17 DOWNTO 0); ledg( 7 DOWNTO 4) <= key(3 DOWNTO 0); ledg( 3 DOWNTO 0) <= key(3 DOWNTO 0); allow to switch all red LEDs on and off using the toggle switches SW0…SW17 below the respective LEDs LEDR0…LEDR17. Try it! Does it work? Pushbuttons KEY0…KEY3 should allow to switch off the green LEDs LEDG0…LEDG3. When pushing KEY# (# = 0…3), then signal key(#) goes to state ............... Not only LEDs are driven by the switches, also 18 pins of the expansion header JP2 (=GPIO_1) by line gpio_1(17 DOWNTO 0) <= sw; Which expansion header pin is driven by toggle switch SW0? ..................... The 7-segment (7seg) displays should show their index if SW0='0' or index+8 if SW0='1'. This is caused by the code lines IF sw(0)='0' THEN hex0<=c7seg(0); hex1<=c7seg(1); hex2<=c7seg(2); hex3<=c7seg(3); hex4<=c7seg(4); hex5<=c7seg(5); hex6<=c7seg(6); hex7<=c7seg(7); ELSE hex0<=c7seg(8); hex1<=c7seg(9); hex2<=c7seg(10); hex3<=c7seg(11); hex4<=c7seg(12); hex5<=c7seg(13); hex6<=c7seg(14); hex7<=c7seg(15); END IF; But something is wrong with the hex-displays! What? Repair it using VHDL operator NOT for bit-vectors! (e.g. not_vector <= NOT vector;)

save: de2_test.vhd → de2_test_sol1.vhd

Hint: Save files *.vhd, *.qpf and *.qsf. All other files can be rebuild by compilation with Quartus II. Saving file *.sof allows for programming without new compilation.

Page 15: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 15 -

2.2 Getting Started with Daughter Board DA2

2.2.1 The DA2 Daughter-Board Hardware

DAC1outMAX4234

VCC5

CP0

100nF

2K

LT1712 VCC33

CP7

100nF

2K

VCC33LT1712

VCC33

VCC33

AD

C(7

:0) = g

pio

(35

:28)

gnd

1F

line_in

TRS connector

TRS_in_Right

TRS_in_Left

20K

TRS_in_Left_C

MAX4234

VCC5

2K

CP_in_P

VCC5

n5 n6

n4

A31

A29

A31A33A39

A37A36

C2

C16

A32

A30

A27

A38

A40

A35A34

C1

C3

C5

C7

C9

C11

C13

C15

100

nF

A28

n720K

DA

C2

(7:0) =

gp

io(19,1

7,15

:10

)

DAC2

DAC2out_b

MAX4234

VCC5DAC2out

DAC3out

DAC3

DA

C3

(7:0) =

gp

io(27

:20)

DAC3out_bDAC3out_b

MAX4234

VCC5

2R

2R

2R

2R

R

R

R

DA

C1

(7:0

) = g

pio

(9:3

,1)

R=

10K

DAC1

2 x 100Faluminumelectrolyt

line_out (green)

DAC1out_b

TRS out Right

TRS out Left

TRS connector

C3 =

10 n

F

2R

Rx=8K

Rx

Rx

Rx

Rx

Rx

Rx

Rx

Rx

Rx

Rx

Rx

Rx

Rx

Rx

Rx

Rx

Rx=8K

A1

A3

A5A7

A9

A11A13

A15

A17

A19A21

A23

A25

A2

A4

A6

A8

A10

A12

A14

A16

A18

A20

A22

A24

A26

DAC2out_b

DAC1out_bn1

n2

n3

2R

2R

2R

2R

R

R

R

R

= D

E2

/ JPx-p

in(3

2:3

1,2

8:2

3), x=

1,2

= D

E2

/ JPx-p

in(1

0:4

,2), x=

1,2

= D

E2

/ JPx-p

in(2

2,2

0,1

8:1

3), x=

1,2

DiffOut

VCC5

20K

20K20K

MAX4232 MAX4232

20K

gnd

20KDiff_ref

Diff_ref_b

Diff_in_M

Diff_in_P

B1

B3

B7

B5

B2

4

B8

B6

VCC5

VCC5

OA5

OA6

R48

= D

E2

/ JPx-p

in(4

0:3

3), x=

1,2

OA1

OA2

OA3

OA4

R9R19

R1 4.7F

CP

erf

# (

#=

0...

7)

C2 =

10 n

F

C1 =

1 nF

Fig. 2.2.1-1: Schematics of the DA2 daughter board

Page 16: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 16 -

10 nF

10 nF

100nF

1 nF

DAC2out

DAC3out_b

CP in P

TRS out LeftTRS out Right

TRS_in_Right

TRS_in_Leftn6

n5

n4

TRS_in_Left_C

DAC1out_b

1

3

5

7

2

4

6

8

9

11

13

15

17

10

12

14

16

18

19

21

23

20

22

24

25

27

29

31

33

35

37

39

26

28

30

32

34

36

38

40

Connector A

n1

DAC1out

n2

n3

DAC3out

DAC3out_b

DAC2out_b

n7

Connector C0

1

2

3

4

5

6

7

0

1

2

3

4

5

6

7

1

3

5

7

9

11

13

15

2

4

6

8

10

12

14

16

CP out (7:0)CP ref (7 : 0)

Connector B

Pins 1, 3, 19, 21 of GPIO-Header:

1

3

19

21

1

3

5

7

9

11

13

15

2

4

6

8

10

12

14

16

Connector GND

Diff Ref

Diff Out

Diff Ref b

Diff In M

Diff in P

8

6

4

2

7

5

3

1

Fig. 2.2.1-2: Connectors of the DA2 daughter board

Fig. 2.2.1-1 shows the DA2 daughter board schematics.

Fig. 2.2.1-2 illustrates the DA2 board from the Santa-Cruz connector point of view.

Fig. 2.2.1-3(a) is related to the user header of the DE2 board and maps the GPIO labels to the Santa-Cruz connector pins.

Fig. 2.2.1-3(b) is related to the user header of the DE2-70 board and maps the GPIO labels to the Santa-Cruz connector pins.

Disconnect DS2 grandchild board under DA2 daughter board to avoid “strange” effects when working with it in this chapter. This may be done in different ways, for example:

On DS2 grandchild board (see Fig. 2.3.1) jumpers must not connect pin E1 which drives pin A31=CP_in_P of DA2. Set jumpers on DS2 to connect E3-E4, E5-E6.

Completely disconnect DS2 grandchild board from DA2 board please take care not to loose the small DS2 board.

Set grandchild board into the unconnected parking plugs of DA2 board, which is the row with the bigger distance to the DA2 board.

Page 17: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 17 -

This tutorial is made for the DE2 board. However, the user-header pins are assigned such, that compatibility to the DE2-70 board is supported. Therefore pins 1, 3, 19, 21 of the user header remain unused. They are made available on the DE2 daughter board. DE2-board users can employ them arbitrarily. DE2-70-board users can observe the PLL behavior with these pins.

(a) User header of DE2 board (a) User header of DE2-70 board

Fig. 2.2.1-3: User header configurations of DE2 and DE2-70 boards, copied from the respective user manuals.

Page 18: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 18 -

Fig. 2.2.1-4: DA2 board schematics (by Markus Buchhart, 2010)

Page 19: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 19 -

Fig. 2.2.1-5: DA2 board (top) top and (bottom) bottom layer layout (by M. Buchhart, 2010)

Page 20: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 20 -

2.2.2 Digital-to-Analog Converters (DACs)

2.2.2.1 Flash-DAC Theory

G2U2

G3U3

G4U4

G5U5

G6U6

G7U7

G1U1

G0U0

DAC#out, #=2,3

Gsum

Usrc

DAC#out

(b) (c)

0 1 2 3 4 5 6 7 8

(a)

Figure 2.2.2.1: (a) A 9-level thermometric code, (b) Flash DAC and (c) its equivalent model

In the figure above we have

72

0

1L

jjsumout GGZ and j

L

jsrc U

Gsum

GU j

72

0

.

DAC2 and DAC3 in Fig. 2.2.1-1 deliver L=9 levels output from L-1=8-bit thermometric code to pins labeled DAC2out and DAC3out, respectively. What is their output resistance for ideal voltage sources and 8K-resistors? ........................................... Compute UDAC#out9 = f(L,VCC) with L input voltages being at VCC and the others at GND=0V? Rj=8K for j=1...L-2=9. Label the 9 voltage levels in the figure below for VCC=VCC33=3.3V. Figure 3.2.2: Minimum DAC output step: DA = ....................... L=9 level DAC output voltage formula: UDAC#out = ..................... with #=2,3. Amplification in V/bit: ADA = ..................... 0 1 2 3 4 5 6 7 8 L

0

3.3 V

Page 21: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 21 -

These L=9 level DAC with L-1=8 bits thermometric code seems to be not very efficient as 8 bits could be translated into 256 levels. However, combined with oversampling techniques such as dynamic element matching (DEM) and delta-sigma (ΔΣ) modulation this kind of DAC can represent an arbitrary number of levels with incredible accuracy. 2.2.2.2 R2R-DAC Theory

Fig. 2.2.2.2: R2R DAC

2R

R

2R

R

2R

R

2R

R

2R

R

2R

R

2R

R

2R

Uout

a0 a1 a2 a3 a4 a5 a6 a7'0'

2R

The R2R ladder DAC with output DAC1out delivers an output voltage of

871

01 2

jNoB

jjoutDAC UU

with Uj being VCC33=3.3V or GND=0V as can be seen e.g. from script on A/D/A Converters [7] or Schaltungstechnik [8]. The output impedance of the R2R-DAC in Fig. 2.2.1-1 is R. For measurement & test applications the inaccuracy of the most significant bit (MSB) must be less than or equal to the half of the least significant bit (LSB). For 1% resistors this would be 6 bits, corresponding to an impact of 2-6=1/641.56%. In other situations, e.g. processing acoustic signals, this holds true for the most significant used bit. Quiet passages of music may use only some LSBs. 2.2.2.3 Connecting the DA2 Daughter Board

Remove all jumpers from grandchild board DS2 attached below daughter board DA2. Connect the DA2 daughter board to the JP2 = GPIO_1 expansion header of the DE2 board. Thus it will be controlled by signals gpio_1(35…0). Within your Windows operating system do the following: Copy directory de2_test generated within the previous chapter and rename it to de2_dac. Delete all files within directory de2_dac with exception of de2_test.vhd. Rename the last version of de2_test.vhd to de2_dac.vhd. Open de2_dac.vhd and rename all strings "de2_test" to "de2_dac". Restart Quartus II and create within directory de2_dac a new project named de2_dac.

(FPGA is still Cyclone II – EP2C35F672C6, and do not forget to import pin-assignments from file DE2_pin_assignments.csv.)

Compile de2_dac.vhd and download de2_dac.sof to your DE2 board. At this point the board should do exactly the same as it did for project de2_test in the

previous chapter. Does it? save: de2_dac.vhd → de2_adc_dac_sol0.vhd

Page 22: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 22 -

2.2.2.4 Driving the DACs

Copy all 36 signals of gpio_1 to gpio_0 for monitoring reasons (, as we cannot directly measure the pins of gpio_1 covered by the 40-pin-connector). To do so include the following code line somewhere in the concurrent code: (see Table 4.3.4.1for GPIO usage) -- copy gpio_1 to gpio_0 for monitoring reasons gpio_0 <= gpio_1;

Include the code lines below somewhere in the concurrent code of the architecture: SIGNAL dac1dout256,dac2dout9,dac3dout9:std_logic_vector(7 DOWNTO 0); ... -- set drivers to the 3 DACs dac1dout256 <= sw(7 DOWNTO 0); -- input to 256-level DAC 1 dac2dout9 <= sw(7 DOWNTO 0); -- input to 9-level DAC 2 dac3dout9 <= sw(7 DOWNTO 0); -- input to 9-level DAC 3

We avoid to use pins 1, 3, 19, 21 of the user headers for reasons of compatibility with the DE2-70 board’s user header, because the DE2-70 assigns these pins to a PLL as shown in Fig. 2.2.1-3(b). Consequently, working with the top-level entity de2_test we avoid using signals gpio_#(.......) , gpio_#(.......) , gpio_#(.......) , gpio_#(.......), # = 0,1 Attach daughter-board DA2 to the 40-pin connector JP2 (=GPIO_1) of the DE2-board. Modify other drivers to signal gpio_1(...) such, that:

signal dac1dout256 controls the output voltage of the analog signal DAC1out on DA2 board,

signal dac2dout9 controls the output voltage of the analog signal DAC2out on DA2 board,

signal dac3dout9 controls the output voltage of the analog signal DAC3out on DA2 board. To do so replace line gpio_1(17 DOWNTO 0) <= sw;

by the following statements, compile the new code and download into the FPGA: -- drive DAC1: gpio_1( 9 DOWNTO 3) <= dac1dout256( ); gpio_1( 1) <= dac1dout256( ); -- drive DAC2: gpio_1(19) <= dac2dout9( ); gpio_1(17) <= dac2dout9( ); gpio_1(15 DOWNTO 10) <= dac2dout9( ); -- drive DAC3: gpio_1( ) <= dac3dout9;

save: de2_adc_dac.vhd → de2_adc_dac_sol1.vhd

Page 23: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 23 -

2.2.2.5 Testing DAC1

Fig. 2.2.2.5: Test setup for DAC1.

Zout1

Usrc1

DAC1outA1

multimeter

sw(7:0) A3 A6

2.2.2.5.1 Measuring the Equivalent Inner Source Voltage Usrc1

Connect a voltmeter to output of DAC1, which is drawn as source voltage and output impedance in Fig. 2.2.2.5. As the voltmeter has a high input impedance, we measure DAC1’s equivalent source voltage Usrc1. Use switches sw0 ... sw7 for the following questions: VDD theoretically: 3.3V, (available e.g. at pin 29 of GPIO 1,2) , measured ........... Usrc1 for DAC1 varies in ........... steps from a minimum voltage of ..............V to a theoretical max. voltage of .......................... , measured ......... The resolution is theoretically: .................., , measured ........ Look into the data sheet of the max423x operational amplifier: Common mode input voltage range: .....................................

Typical output voltage swing at RL=200: ..................................... Input bias current: ..................................... Input offset voltage: typical: ............ max: .... ............ On DA2 board: Set jumper A3-A4. Does buffer OA1 drive DAC1out_b? ................. Input offset voltage of amplifier OA1 (measure e.g. between pins A1–A7)? .............. 2.2.2.5.2 Measuring the Equivalent Output Impedance Zout1

Expected output impedance from Fig. 2.2.1-1: Zout1,ideal = ............................ Method A: Set any voltage Usrc1>0V (e.g. VDD/2=1.65V), measure it: Usrc1 = .......... Switch from voltmeter to ampere-meter and measure the output current: Iout1 = ........... The output impedance is Zout1 = Usrc1 / Iout1 = ...................... Method B: Set voltage Usrc1=0V and measure with an Ohm-meter versus ground: Zout1 = .............

Page 24: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 24 -

2.2.2.6 Testing DAC2 OA2 o.k.? ..... , Offset voltage: .........

Fig. 2.2.2.6: Test setup for DAC2.

Zout2

Usrc2

DAC2outA15

multimeter

sw(7:0) A14 A17

2.2.2.6.1 Measuring the Equivalent Inner Source Voltage Usrc2

Use switches sw0 ... sw7 for the following questions: Usrc2 for DAC2 varies in ........... steps from a minimum voltage of .....0.......V to a theoretical max. voltage of ......................... , measured .......... The resolution is theoretically: ......................... , measured .......... 2.2.2.6.2 Measuring the Equivalent Output Impedance Zout2

Expected output impedance from Fig. 2.2.1-1: Zout2,ideal = .................. Method A: Set any voltage Usrc1>0V (e.g. VDD/2=1.65V), measure it: Usrc2 = ......... Switch from voltmeter to ampere-meter and measure the output current: Iout2 = .......... The output impedance is Zout2 = Usrc2 / Iout2 = .................. Method B: Set voltage Usrc2=0V and measure with an Ohm-meter versus ground: Zout2 = ............. 2.2.2.7 Testing DAC3 OA3 o.k.? ...... , Offset voltage: .........

2.2.2.7.1 Measuring the Equivalent Inner Source Voltage Usrc3

Remove DS2 grandchild board under this DA2 board or remove jumper E1-E3 on it (→ see Fig. 2.3.1). Use switches sw0 ... sw7 for the following questions: Usrc3 for DAC3 varies in ........... steps from a minimum voltage of .............V to a theoretical max. voltage of .......................... , measured .......... The resolution is theoretically: .......................... , measured .......... 2.2.2.7.2 Measuring the Equivalent Output Impedance Zout3

Expected output impedance from Fig. 2.2.1-1: Zout3,ideal = ..................... The measured output impedance is Zout3 = ..................................

Page 25: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 25 -

2.2.3 Analog-to-Digital Converter (ADC)

Within your Windows operating system do the following: Copy directory de2_dac generated within the previous chapter and rename it to

de2_adc_flash. Delete all files within directory de2_adc_flash with exception of de2_dac.vhd. Rename de2_dac.vhd to de2_adc_flash.vhd. Open de2_adc_flash.vhd and rename all strings "de2_dac" to "de2_adc_flash". Restart Quartus II and create within directory de2_adc_flash a new project de2_adc_flash. Compile de2_adc_flash.vhd and download de2_adc_flash.sof to your DE2 board. At this point the board should do exactly the same as it did for project de2_dac in the

previous chapter. Does it? save: de2_adc_flash.vhd → de2_adc_flash_sol0.vhd

2.2.3.1 Trimming the Flash-ADC

The 8 threshold voltages are labeled on the board with CPref0,...,CPref7 (test points C2, C4, ... C16). Compute the 8 thresholds in Fig. 2.2.3.1(b) and turn the 8 potis to the computed values. CPref0 gets the lowest threshold, increasing with index Cpref7 gets the highest threshold. The positive 8 comparators inputs the are connected and labeled CP_in_P having several test points. Ideally, the Flash-ADC would have an infinite impedance and zero input current. However, most comparators have input bias currents. Look into the LT1712 data sheet. What is its typical input bias current? ............ What is the typical input bias current of the total Flash-ADC? ....................

Page 26: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 26 -

Fig. 2.2.3.1(a): Basic principle of a flash ADC. The m:n decoder logic can be realized as simple summation of the comparator’s output bits.

Write the formula VT,i=f(i=0...7,VCC) for the 8 required threshold voltages of the comparators delivering the L-1=8 bit decision into Fig. 2.2.3.1. Write the VT,i to the right side of the figure. Figure 2.2.3.1(b): Remember: L=9 level DAC output voltage formula: UDAC#out = iꞏDA, i=0...L-1 Find: L=9 level DAC input threshold formula using Uref=VCC=3.3V, i=0...L-2. VT,i = ............... with AD = .......... Amplification in bit/V: AAD = ...............

0 1 2 3 7 8 L0

3.3

2.8875

2.475

2.0625

1.65

1.2375

0.825

0.4125

UDACout VT,x

UADCin /

Page 27: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 27 -

2.2.3.2 Using DAC3out as Voltage Source

A31

A32

A27 A28

A31

CP_in_P

FlashADC

(9-Level)

C2C4C6...C16

8 adc_in(7:0)

1Zout3A22 A23 A25

Usrc3=VDD/2

DAC3out9sw(7:0)

Figure 2.2.3.2: Using DAC3out as Voltage Source Remove DS2 grandchild board under DA2 board or remove its jumper E1-E3 (Fig. 2.3.1). Set U(DAC3out) to VDD/2, using for example sw(7…0)="00001111", and measure the

voltage at test point A25. Write U(DAC3out) in box "unconnected" in table 2.2.3.2-1. Connect U(DAC3out) to the Flash-ADC’s input CP_in_P (that must not have other

connections) by shorting pins A25 and A27. Write U(DAC3out) in box "DAC3out=CP_in_P " of table 2.2.3.2-1.

Table 2.2.3.2: Impact of comparator’s input bias currents on output impedance of DAC3.

DAC3out: unconnected DAC3out=CP_in_P Difference U(DAC3out): How do you explain the voltage jump when pins A25 and A27 shorted? ......................................................................... .........................................................................

Read the comparator’s outputs to the FPGA. Declare SIGNAL adc_din:std_logic_vector(7 DownTo 0) and include the statement adc_din <= gpio_1(.......................); Monitor the ADC’s output using the green LEDs by modifying their driver to (other drivers must be removed!): ledg(7 DOWNTO 0) <= adc_din; -- output to the green diodes

save: de2_adc_flash.vhd → de2_adc_flash_sol1.vhd

Table 2.2.3 lists the actual assignments of switches, LEDs and gpio signals. Measure the voltage DAC3out and observe the green diodes. What correlation do you observe between the number of switches sw(7...0) driving logical HIGH state and the number of green LEDs turned on? .........................................................................

Page 28: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 28 -

2.2.3.3 Waveform Generation

Goal of this subchapter is to assemble the circuit in Fig. 2.2.3.3, quantize a sinusoidal test tone with the Flash-ADC and get the curves of Fig. 2.2.3.4 on the oscilloscope.

A31

A32

A27 A28

gnd

1F

line_in

TRS connector

TRS_in_Right

TRS_in_Left

20K

TRS_in_Left_C

MAX4234

VCC5

2K

VCC5

n5n6

n4

A31

A33

A39

A37

A36

A38

A40

A35

A34

n720K

OA4

R9R19

R1 4.7F

CP_in_P

FlashADC

(9-Level)

C2C4C6...C16

8 adc_in(7:0)

1

Fig. 2.2.3.3: Signal path: feed 250mV to TRS_in_Left (A34), amplifiy x 10 to CP_in_P Feed a 1000 Hz sinusoidal signal with some 250mV peak-peak to node TRS_in_Left (A34). Observe on node n5 (A39) a 10 times bigger amplitude. Use poti R1 for DC balancing and poti R9 for amplitude adjustument. Prefer a waveform generator with settable amplitude to the PC’s soundcard. The latter has minor performance with respect to output impedance and frequency and allows for different amplitude manipulations, so that the user is insecure about the da facto output amplitude. Use Oscilloscope DSO-X2024 as wavform generator: Press button Wave Gen, then use buttons below the screen to select your settings. Right: PC screen shot: Settings of Timo Esser’s Test Tone Generator [10], [11] driving the PC soundcard 1KHz sinusoidal.

Page 29: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 29 -

A. Program DE2 board with VHDL Source Code: To output the information of the 9-level Flash-DAC immediately via DAC2 and DAC3, replace the code lines dac2dout9 <= sw(7 DOWNTO 0); -- input to 9-level DAC 2 dac3dout9 <= sw(7 DOWNTO 0); -- input to 9-level DAC 3

with dac2dout9 <= adc_din dac3dout9 <= adc_din

save: de2_adc_flash.vhd → de2_adc_flash_sol2.vhd

into the actual VHDL code, compile with Quartus II and download it into the Cyclone II FPGA on the DE2 board. Connect CH2 of your oscilloscope with DAC3out (e.g. test point A25). This curves corresponds to the green staircase line in Fig. 2.2.3.4(b). B. Circuit Assembly according to Fig. 2.2.3.3(a) on the DA2 daughter board: Hint: TRS = Tipp-Ring-Sleeve connectors are the ones typically used for speakers. 1. Remove jumper A25–A27 to disconnect DAC3out from CP_in_P. 2. Use -meter (between test points A33-A39) to adjust R19 to ca. 100 . 3. Shorten (jumper) test points A31-A33 to drive CP_in_P with OpAmp OA4 through R19. 4. Shorten (jumper) test points A35-A37 to drive OpAmp OA4’s IN+ with the soundcard. 5. Use poti R1 to set CP_in_P to a DC bias voltage of VDD/2=1,65V. 6. Drive a sinusoidal signal of ca. 250 mVpp to TRS_in_left. (A34) 7. Connect your oscilloscope’s CH1 to CP_in_P (A27) and CH4 to TRS_in_Left_C (A36). 8. Use poti R9 to adjust the amplification of OA4 to a factor 10 or 20dB. (See D.) C. Test Tone Generation: Prefer hardware to generate test tones. If not available you can use your sound card. Software is free available in the internet, e.g. Test Tone Generator [10], [11]. (a) After a quick installation you will see the window shown in Fig. 2.2.3.3(b). (b) Set the tone duration to 9999s, a sinusoidal 1000Hz tone and some –21dBFS to get a

peak-to-peak output amplitude of ca 250 mVpp. Click the ON button. (c) Connect your PC’s soundcard output (green) with the DA2 boards TRS line-in jack. D. With the Oscilloscope:

I. Oscilloscope: CH1 has 500mV/dev and CH4 has 50mV/dev. II. According to point B.7 above CH1 has to show the 10 x amplified signal of CH4.

III. Use poti R9 to adjust the curves at CH1 and CH4 to the same amplitude. IV. U(CP_in_P) shown at oscillator channel CH1 corresponds to the yellow sinusoidal curve

of the screen-shot in Fig. 2.2.3.4(b). V. Get the sinusoidal (yellow) and staircase (blue) curves shown in Fig. 2.2.3.4(b) on your

oscilloscope. Adjust generator’s amplitude and DC-balance poti R1 to get Fig. 2.2.3.4(b). If the sinusoidal tone works well, drive on DA2 board DAC3out and additionally DAC2out via the buffer amplifier OA2 to DAC2out_b and connect this to TRS out Left. Plug a speaker to the DA2 board’s TRS line_out jack. Do you hear the test tone? .........

Disconnect the Test Tone Generator and play some music. Sound quality? ..........

8 levels correspond to 3 bits. Our 9 levels correspond to ld(9) = ln(9)/ln(2) = ........ bits.

Page 30: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 30 -

2.2.3.4 Measuring the Quantization Noise

Goal of this subchapter is to make the difference (= quantization noise) between input and output curve visible as shown in the bottom (green) curve of Fig. 2.2.3.4(b).

DiffOut

VCC5

20K

20K20K

MAX4232 MAX4232

20K

gnd

20KDiff_ref

Diff_ref_b

Diff_in_M

Diff_in_P

B1

B3

B7

B5

B2

4

B8

B6

VCC5

VCC5

OA5

OA6

R48

DAC3out_bA19 A20

CP_in_PA27 A28 ...

OsciCH 1

OsciCH 2

OsciCH 3

(a) Top: Circuit assembled on DA2 board.

(b) Right: Oscilloscope screen shot: (i) yellow + sinus.: CP_in_P, (ii) blue in 9 levels: DAC3out, (iii) green, bottom: Difference =quantization noise: U(B7,B3).

Figure 2.2.3.4: Measuring quanti-

zation noise We now want to measure the effective quantization-noise voltage, which is the red curve in Fig. 2.2.3.4(b), computed as difference between the green and the yellow curve. We should have the sinusoidal (yellow) and staircase (green) curves of Fig. 2.2.3.4(b) on the scope. Possibility A: Measure with the Oscilloscope DSO-X 2024A Compute the Quantization noise by the oscilloscope’s math menu:

Compute difference: Math Function f(t), Operator subtract CH1 – CH2 Measure computed rms voltage: Meas Type AC-RMS Zyk

Possibility B: Using the hardware shown in Fig. 2.2.3.4(a) Adjust poti R48 such that U(Diff_ref_b)=VDD/2=1.65V. Connect CP_in_P to Diff_in_P and DAC3out_b to Diff_in_M. Display U(DiffOut) on oscilloscope as shown with the bottom (red) curve in

Fig. 2.2.3.4(b). Note: To get the 1.65V DC biasing voltage out of the quantization noise measurement you have to either use the AC feed-in mode on the scope (see figure) or to measure between points DiffOut and Diff_ref_b.

Mathematically: 12

8/3.3

12

V

= Measured:

. .............. ..............

Page 31: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 31 -

2.3 Getting Started with Grandchild Board DS2

2.3.1 The DS2 Grandchild-Board Hardware

1

3

5

7

9

2

4

6

8

10

11

JP2

JP1

JP3

(b) Connector E

UB

OUT2

IN1

Uin

to D

A2

, A

31

A25

, from

DA

2

s3s2

s1

Vcc

gnd

s4

s5 s6

externalconnctions

analog mode and1st order system

configured to digital mode and2nd order modulator

A25

, from

DA

2

s3

to D

A2

, A

31

s2

(c) Connector E (d) Connector E

1

3

5

7

9

2

4

6

8

10

11

JP2

JP1

JP3

1

3

5

7

9

2

4

6

8

10

11

JP2

JP1

JP3

OUT2

R2Uin

C2R1

C1

OA2OA1

Rb1Rb2

OUT2 OUT1

1storder

2ndorder

OA4

OA3

100K

100K 71K

100K

Rb Ra

100K 100K

UB

UB UB

JP2

to D

A2

, A

31

s1

s2

159pF159pF

UB

VCC

gnd

s4

s5, s6

max4234 max4234

max4234

max4234

Rd

Rc

100K

100K

A33

, from

DA

2

JP1

A25

, from

DA

2

s3

JP3

E1 E2

E3 E4

E5 E6

E7 E8

E10

E9

E11 IN1IN2

(a) DS2-Board Schematics: analog system or modulator, configurable of 1st and 2nd order

Ufb

,in

Uout

Fig. 2.3.1-1: (1) DS2-Board Schematics, cutoff frequency is fg=10KHz. Draw in Fig. 2.3.1-1(c) a jumper to set a 1st order system. Pins: ........ , a jumper to connect on the DS2 board Uout Ufb,in : ........ . Draw in Fig. 2.3.1-1(d) a jumper to set a 2nd order system. Pins: ........ , a jumper to connect DE2 board’s Uout DA2/A31: ........ , a jumper to connect DE2 board’s Ufb,in DA2/A25: ........ .

Page 32: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 32 -

The DS2 grandchild board is plugged under the DS2 daughter board in the plug-line near the DA2 board. This automatically connects wires drawn green in Fig. 2.3.3. The upper plug-line is intended for disconnected parking the DS2 board.

Fig 2.3.1-2: Eagle schematics

Fig 2.3.1-3: Eagle Layout: (a) Top view, (b) Bottom view

Page 33: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 33 -

2.3.2 Testing the DS2 Analog Board in a Stand-Alone Mode

We now want to operate the DS2 board as stand-alone 1st or 2nd order analog system with lowpass characteristics Set jumper E3-E4 on DS2 board. The DS2 board gets its input signal from pin A33 which is wired to E10 of the DS2 board. This connection is sketched as green wire W1 in Fig. 2.3.3. Wires W2 and W3 remain disconnected in this subsection. Do not set jumpers to E1 and E2 to avoid driving into the DA2 board. A 1st order system is obtained by connecting E10-E9, and a 2nd order system is obtained by connecting E10-E11. Note: The computer’s sound card might have problems to generate frequencies >22KHz. Use other signal generators if available, e.g. “Gen Out” output of DSO-X Oscilloscope. Fig. 2.3.1-1(c) should sketch the jumpers to obtain a 1st order analog system. Realize these settings with jumpers on the DS2 board. We want to feed a 2 Vpp sinusoidal Signal into the DS2 board’s Uin. To do so, we feed

some 200 mVpp into the DA2-board’s Pin A34 or TRS connector, bridge A35-A37. Adjust input voltage to pin A34 such, that you get some the yellow input curves Uin with 2 Vpp shown in Fig. 2.3.2 at pin A39 and the green output curves at pin E5. (Hint: Observation is easier if signals are in phase, i.e. if you set 2nd order system on DS-Board.)

Cutoff frequency of this analog lowpass is 10KHz. Measure the output signal at pin E5 or E6 for fin = 1KHz, 10KHz and 100KHz. What amplifications do you observe? 1st order: 1 KHz: A = ..... dB, 10 KHz: A = ... dB, 100 KHz: A = ..... dB,

Modify a single Jumper such, that we have a 2nd order analog system. Feed Uin as detailed above and measure amplifications at pin E5 or E6: 2nd order: 1 KHz: A = ..... dB, 10 KHz: A = ... dB, 100 KHz: A = ..... dB,

(a) at 1 KHz at 2nd order system (b) at 10 KHz at 2nd order system Fig. 2.3.2: Adjust DS2 board input voltage (yellow) to fit to the screen, observe output (green)

Page 34: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 34 -

2.3.3 Testing DS2 Board as Submodule of DA2 Board

Fig. 2.3.3: Schematics and jumper situation Let’s make the same measurement as in sub-chapter and Fig.2.3.2, but now the loop is not closed by jumper E3-E4 on DS2 board, but by jumper A25-A27 on DA2 board. Remove jumper E3-E4 on DS2 board. Set A25-A27 on the DA2 board. (In this mode output amplifier OA1 of the DS2 board simply overrides the 1KΩ-output impedance of DAC3, as we cannot disconnect DAC3. Sketch jumper settings it in Fig. 2.3.3 let and right. Fig. 2.3.1-1(d) should sketch the jumpers to obtain an a 2nd order system on DS2 board with DS2/Uout = DA2/A27 and DS2/Ufb,in =DA2/A25. Realize this with the following jumper settings: To connect the wire W2 to Uout of DS2 board set jumper E1-E3 on the DS2 board. To connect the wire W3 to Ufb,in of DS2 board set jumper E2-E4 on the DS2 board.

To connect the DS2 board’s Uout with its Ufb,in set jumper A25-A27 on DA2 board. (In this mode DS2 board’s Uout overrides DAC3’s output resistance.) Experimental verification: We should get the same results as in the subchapter before: 1st order: 1 KHz: A = ..... dB, 10 KHz: A = ..... dB, 100 KHz: A = ..... dB,

2nd order: 1 KHz: A = ..... dB, 10 KHz: A = ..... dB, 100 KHz: A = ..... dB.

Page 35: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 35 -

3 ADAC: A/D and D/A Conversion System 3.1 ADAC System Overview (a) Top level system Overview. ADC digitalanalog analog DAC

(b): The complete system: A ΔΣ-ADC feeds DAC1 and DAC2

Modulator Demodulator(digital lowpass)

Q

9 level,green

DAC118

8

Upsamplingusing sinc filters

digital modulator

DAC2 R

C

Uout2lowpass

Uin

yellow

redwhite

blue

DigSig

DigSig

fS2

fS0

fS1 fS1fS2

fS0 = fS1 = 10 fS2

Ananog-to-Digital Converter (ADC)

9 level8 8

Uout1

9 level

Uout2,C

Fig 3.1: A/D – D/A Conversion System overview. The complete system under consideration is illustrated in Fig. 3.1(b) and 3.2. Input Uin (yellow) is fed to a ΔΣ ADC consisting of modulator and demodulator connected by quantized signal Q (green). It delivers signal DigSig, which is translated directly to Uout1 (blue) by the 256-level R2R-DAC named DAC1, and indirectly to Uout2 (red) by the 9-level DAC named DAC2, and after smoothing to Uout2,C (white).

Page 36: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 36 -

3.2 Simulation Using ModelSim

Fig. 3.2: Complete system simulated with ModelSim. For the following simulation and synthesis load and unzip file adac.zip [16], [17]. You get directory <treename>/adac/ModelSim/testbenches/tb_de2_adac/

where you find the files tb_de2_adac.vhd % VHDL testbench wave.do % controls the wave window (graphics output) of ModelSim work.do % compiles all files for the students

Start ModelSim simulator, use Files → Change Directory to navigate into directory tb_de2_adac. After executing Files → Quit here you can navigate more easily to this directory using Files → Recent Directories. With ModeSim working directory set to tb_de2_adac type into the transcript window > do work.do

The do-command processes commands within file work.do, which uses the graphics command file wave.do. You should get the result shown in Fig. 3.2. Questions: ΔΣ converters are said to be accurate but slow, slow because of the big modulator’s delay. This statement is both true and wrong. Argue with Fig. 3.2! .............................................................. ..............................................................

Page 37: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 37 -

3.3 Principles of ΔΣ A/D and D/A Conversion

3.3.1 Goals of ΔΣ Modulation

A delta-sigma (ΔΣ) system consists of a modulator / demodulator combination. Modulator: The modulator translates signal resolution to speed (expressed as oversampling). In this example we will use a L level quantizer, corresponding to an effective number of bits of ENOB = ld(L) 2ENOB=L. We can set L by toggle switches sw(17:16)="00", "01","10", "11" to L = 2sw(17:16)+1 = 2, 3, 5, 9 corresponding to ENOB = ld(9) =1, 1.6, 2.3, 3.2. The logarithm dualis can be computed as ld(x)=ln(x)/ln(2) or with Matlab as log2(x). Demodulator: The demodulating lowpass re-translates speed to resolution. For DC applications simple averaging is enough. If we want to average busy signals a lowpass delivers constant amplification for all baseband frequencies. ΔΣ D/A Converter: The most important modulator type particularly for DACs is the 1-bit resolution type (i.e. 2 levels only). This is because loads can be driven with theoretically 100% energy efficiency using a simple switch: Few power is lost in the switches: Either there is no current through or no voltage across them. A speaker or headphone can be driven with a ΔΣ modulated bitstream with near 100% energy efficiency. The demodulating lowpasses in these example is the physical mass of the speaker. A/D Converter: A further important goal of oversampling ADCs is the avoidance of analog anti-aliasing filters. The unavoidable lowpass filtering is shifted into the digital domain. When oversampling is employed to avoid anti-aliasing filtering, then ΔΣ modulation might make sense to yield more accuracy. 3.3.2 Principle of ΔΣ Modulation

O LOutputInput

Modulator Demodulator

System

lowpass,order > O

integrator quantizer

Q

Fig 3.3.2: Principle of ΔΣ Modulation: An Oth order integrator and a quantizer within a loop Fig. 3.3.2 illustrates the basic principle of ΔΣ modulation: A loop of an Oth order integrator followed by a L - level quantizer. On the one hand, the quantizer makes the signal less accurate, on the other hand, the accuracy is preserved as average of the faster clocked loop.

Page 38: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 38 -

Consequently, demodulation is forming the average of the quantized data stream Q. This averaging within base-band frequencies is performed by the lowpass. As illustrated in Fig. 3.3.2 the "delta" (Δ) is the difference between input signal and quantized output signal Q. The integrator, symbolized by the Greek letter "sigma" (Σ), sums all deviations between input signal and Q while the loop seeks to minimize this sum. 3.3.3 Using ΔΣ Modulation for D/A Conversion

(a)

O LUoutDin

Digital Modulator Demodulator

Digital-to-Ananlog Converter (DAC)

nL-levelDAC

integrator quantizer analoglowpass,order > O

Q UQ

(b)

Digital Modulator

(upsampling and digital-to-digital modulation with-

in Altera FPGA)

DAC2(9 level)

lowpass8

fS2 fS1=10fS2

DQR

C

Uout2

redwhite9 level

Uout2,C

Fig 3.3.3: (a) Using ΔΣ Modulation for D/A Conversion. (b) Realization in this lab. Fig 3.3.3 illustrates the principle of using an ΔΣ modulator for D/A conversion. We have a completely digital modulator with digital input Din and digital output DQ. The quantizer can be realized by simply omitting some of the lower significant bits, in the extreme situation DQ is one bit only. To compensate for the loss of lower significant bits we have an increased clock output speed fS1 = K1ꞏfS2. The DAC is required to translate the output signal from digital to analog domain. In this lab we have K1 = 10 (consequently fS1 = 10ꞏfS2). In this lab DAC2 of the DA2 board is fed with an 8-bit / 9-level thermometric code. Its possible states are "00000000" , "00000001", "00000011", "00000111", "00001111", "00011111", "00111111", "01111111", "11111111". The output levels are shown as red curves in Figs. 3.2 and 3.4. In this lab the Digital-to-digital (D/D) modulator has a 1st order integrator. Consequently, the demodulator would require at least 2nd order lowpass to exploit possible signal-to-noise ratio (SNR). Here we yielded optically acceptable results with a simulated 1st order RC lowpass, shown as white curve in Fig. 3.2.

Page 39: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 39 -

3.3.4 Using ΔΣ Modulation for A/D Conversion

(a)

O DoutUin

Modulator Demodulator

Analog-to-Digital Converter (ADC)

n

digitallowpass,order > O

L - levelDAC

L - levelADC

mQ

(b)

(c)

JP2

E10

E9

E11 FlashADC

DAC3

2nd

1st order

IN1IN2 OUT2 OUT1

Uin E1E3

s1

s3

s2

JP2

E10

E9

E11

2nd

1st order

IN1IN2 OUT2 OUT1

Uin E1

E2

E3

E4

s1

s3

s2

E6

E5

E5 Q

9 Level

DS2 board DA2 board

E2E4E6

Uout

Ufb,in

Ufb,in

Uout

Fig 3.3.4-1: (a) Principle of using ΔΣ Modulation for A/D Conversion. (b) Analog integrator loop of DS2 board. (c) Incorporation of ADC and DAC makes analog loop to ΔΣ modulator. To build a ΔΣ modulator for A/D conversion we use an analog integrator of Oth order and an ADC as quantizer that translates Uout of the analog integrator to the quantized digital output Q of the modulator. As the difference Δ has to be computed in the analog domain, a DAC is required to re-translate the digital output Q to the analog feedback signal Ufb,in. In this lab we use according to Figs. 3.3.4-1 (a) and (b) a jumper on pins E9, E10, E11 to switch the order O of the integrator and consequently the order of the modulator between O=1 and O=2.

Page 40: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 40 -

Fig. 3.3.4-1(b) illustrates the integrator system operating as analog lowpass of 1st or 2nd order. In Fig. 3.3.4-1(c) we make it a ΔΣ modulator by incorporation of the Flash-ADC (on DA2 board) as quantizer into the loop. This requires to re-translate the digital signal into an analog signal, which is done by DAC3 in the feedback branch. To do and to check: DS2 board: Input voltage Ufb,in is connected to DA2-baord’s DAC3 output by wire W3 in

Fig. 3.3.4-2. Do: Confirm that jumper E2-E4 on DS2 board is set acc. to Fig. 2.3.1(d). DS2 board: Output voltage Uout is connected to DA2-baord’s Flash-ADC input CP_in_p

by wire W2 in Fig. 3.3.4-2. Confirm jumper E1-E3 on DS2 is set acc. to Fig. 2.3.1(d). DA2 board: Do: Complete input signal path: Set a jumper on connector A to connect

TRS_in_left_C to n4. Plot the jumper in both left and right side of Fig. 3.3.4-2. DA2 board: Check: Remind that the AC input signal must proceed from n4 to n5 with

amplification of 10. Amplification can be adjusted with poti R9. DA2 board: Check: Remind that a sinusoidal signal with peak-to-peak amplitude of

300 mV on n4 must deliver a sinusoidal signal of 3V peak-to-peak on n5. Center waveforms to VCC/2=1.65V with Poti R1 if necessary.

Fig. 3.3.4-2: Schematics and jumper situation

Page 41: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 41 -

3.4 Hardware Test Using Quartus II 8.1 DE2 board: Make sure that only jumper A35-A37 is set on connector A DS2 board: Connected by the jumpers E1-E3 and E2-E4. Set ΣΔ order, e.g. jumper E10-E11. The green wires in Fig. 3.3.4-2 are automatically connected by plugging in the DS2 board. PC: Start Quartus II, you have two possibilities to accomplish that: (i) In directory <tree>\adac\QuartusII81\de2_adac\ double-click on file ci_de2_adac.qpf. (ii) Start Quartus II, navigate using File Open Project ... ci_de2_adac.qpf. Make sure that Hardware Setup is USB Blaster. Select: Tool → Programmer → Add File... → ci_de2_adac_demo.sof Make sure that only flag Program/Configure is set in the programmer, then click Start. Let’s now work get the oscillogram shown in Fig. 3.4. The channels were selected to

match the colors of the ModelSim simulation shown in Fig. 3.2.

Fig 3.4: Oscillogram: Uin (yellow) and Q=Ufb,in (green) of DS2 board, Uout1 (blue), Uout2 (red). The curves seen in the oscillogram in Fig. 3.4 are: CH1: Top yellow smooth curve: Uin to DS2 board, measured at pin DA2/A39 = DS2/s1,

the rectangular curve got oscillations from DA2-board OpAmp OA4. CH2: Top green 9-level curve = ΔΣ modulator’s output Q from flash-ADC, measured as

output of DAC3 (pin DA2/A25) = input Ufb,in of DS2 board. CH3: Blue: Output of R2R-DAC named DAC1 (pin DA2/A1), 256-level, being the

visualization of ΔΣ -ADC output DigSig. The time delay of 65 cycles of sampling clock fS2 is due to the ΔΣ -demodulator (=lowpass).

CH4: Lower red 9-level curve: Output Uout2 of ΔΣ DAC named DAC2 (pin DA2/A17). Input was the ADC’s output DigSig (blue). The time delay compared to CH3 is due to the interpolating sinc4 filter.

Page 42: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 42 -

Check for keys:

Set Switches sw(17:0)="11 0000 0000 0000 0101" on DE2 Board. Test reset signal key(0), global enable signal key(1) while sw(3)='0'. Test manual clock key(2) when sw(3)='1'. (Probably not much to see.)

Check for switches: (See Table 4.3.4.1 for detailed functionality) Start with Switches sw(17:0)="11 0000 0000 0000 0111" on DE2 Board. sw(2:0): Play with switches sw(2:0). They set the sampling frequency of the system

according to fs0=10sw(2:0). The system will use fS0=fS1=10fS2. A good setting is sw(2:0) = 1012 = 510. Then fS0=fS1=105Hz=100KHz and fS2=10KHz allowing to sample waveforms up to fS2/2 = 5KHz. Lower clock rates are problematic to hear sound, and higher sampling rates cause problems with parasitic capacitances.

sw(17:16)="11": Switches sw(17:16) set the number of levels of the Flash-ADC to L = 2sw(17:16)+1. Consequently, sw(17:16)="11" → L=9, "10" → L=5, "01" → L=3, "00" → L=2. (While the Flash-ADC always delivers 9 levels, L is reduced by logic in the VHDL code. In Figs. 3.2 and 3.4 we used L=9 levels.

Set all the other toggle switches to zero: sw(15:3) ="0...000". Check for DA2 board:

Feed a sinusoidal 1KHz signal with amplitude of 200mVpp to TRS_in_Left (pin A34). You may use the sound card of your computer or a waveform generator. This signal should appear with a DC offset of VCC/2=1.65V at pin A34 (=n4). Offset correction can be done with potentiometer R1.

CH1: top, yellow: Signal Uin of Fig. 3.1: Then switch your input waveform from a sinusoidal to a rectangular, still having 2Vpp. Now V(n5) should deliver the yellow curve shown in Fig. 3.4. It must be centered around VCC/2=1.65V, range 0.65V - 2.65V. Adjust amplification of factor 10 with poti R9 if necessary.

CH2: top, green: Quantized signal Q of Fig. 3.1: Connect channel 2 of your oscilloscope to pin A25 of DA2. You should get the top green 9-level curve measured at pin DA2/. This is the ΔΣ modulator’s output Q fed to DAC3 delivering = Ufb,in of DS2 board. Observe impact of switches sw(17:16) on the number of levels of this waveform.

CH3: mean, blue: Signal DigSig of Fig. 3.1: Connect channel 3 of your oscilloscope to pin A1 of DA2. This is the output of the R2R-DAC named DAC1, featuring 256-levels, which visualizes the ΔΣ –ADC’s output DigSig. The time delay of 65 cycles of sampling clock fS2 is due to the ΔΣ –demodulating low-pass. Note that sampling frequency is fs2 = fs0/10.

CH4: bottom, red: Signal Uout2 of Fig. 3.1: Connect channel 4 of your oscilloscope to pin A17 of DA2. This is UDAC2out, the output of DAC2. The input signal of DAC2 was obtained from the blue signal DigSig by speeding its sampling rate up by a factor 10 to obtain fs1=10fs2. With this higher sampling rate it was ΔΣ modulated and fed to DAC2. The time delay compared to CH3 is due to the interpolating sinc4 filter, necessary after up-sampling.

Page 43: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 43 -

Exercises: Observe Fig. 3.4. Is the ΔΣ modulator fast (green following yellow curve)? ...yes.... Observe Uout1 (DAC1out, blue). Who swallowed the rectangular edges of Uin (yellow)? .............................................................. Observe from Fig. 3.4 if the modulator is operated at 1st or 2nd order. To do so keep in mind, that a 1st order modulator will never do jumps over 2 Δ’s without significant jumps of the input signal. .............................................................. ..............................................................

Page 44: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 44 -

4 VHDL Model for ADA Conversion System This chapter is for students learning Electronic Design Automation only (course RED/PRED). It assumes some basic knowledge in VHDL, is not suitable for VHDL beginners.

4.1 ADAC System File Structure

Matlab

ModelSim

tb_counter

Testbenches

binary_libs

tb_de2_adac

tb_de2_engen

behavioral da2_board.vhd

QuartusII81

VHDL

ADAC

ci_de2_engen

ci_counter

ci_de2_adac

counter

filter

oscillator

optimizations

tb_counter.vhd

tb_de2_engen.vhd

tb_de2_adac.vhd

counter.vhd

de2_engen.vhd

ci_counter.vhd

ci_de2_engen.vhd

ci_e2_adac.vhd

+f_counter.m tb_counter.m

DE2_pin_assignments.csv

de2_adac.vhd

adac_bin

engen_bin

Fig. 4.1: Used directory structure and VHDL file system of the ADAC project. The binary libraries adac_bin and engen_bin are created temporarily by ModelSim and may be deleted after finishing simulation.

Page 45: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 45 -

Fig. 4.1 shows the file system used in this tutorial. The A/D and D/A Conversion (ADAC) project consists of a delta-sigma analog-to-digital converter (ΔΣ ADC) followed by a delta-sigma digital-to-analog converter (ΔΣ ADC), as illustrated in Fig. 3.1. Notation. In UNIX and Linux a single point “.” stands for this directory, two points “..” stand for parent directory of this directory and “/directory_name” stands for subdirectory directory_name. Simulation and Synthesis. HDL Simulation runs a hardware description language (HDL) model on a simulator. HDL Synthesis compiles a HDL model to a binary file suitable for download into a

specified hardware. For synthesis (V)HDL language elements are strongly restricted and depend on available libraries.

Non-synthesizeable models are said to be behavioral. Writing behavioral models are written due to three main reasons: (1) Testbenches, with e.g. a clock source made as “clock<= NOT clock AFTER 5 ns;” (2) High level model before details are worked out. (3) Free simulation model intended to stimulate customers to by the synthesizable one.

Expressions RTL (register transfer level) descriptions are understood as synthesizable. Behavioral descriptions are understood to be non-synthesizable, i.e. for simulation only.

Fig. 4.1 shows four main subdirectories of this project: Matlab: This directory contains Matlab models, used to proof concepts on top level. VHDL: This directory contains synthesizable VHDL models. They will be used by both tools ModelSim and Quartus II. In these VHDL models names of synthesizable architectures begin with prefix “rtl_”, names of behavioral architectures begin with prefix “beh_”. ModelSim: This directory contains files that are specific to the ModelSim simulator. The subdirectory ./tb_<modulname> will typically contain the following files: work.do TCL/Tk command file. Typing “do work.do” in the ModelSim

transcript window runs the complete example. wave.do defines the graphics window. tb_<modulname>.vhd Testbench to test module <modulename>.

The behavioral architecture names begin with suffix “beh_tb_”. QuartusII81: This directory contains files that are specific to the Quartus II 8.1 software tool. The subdirectory ./<modulname> will typically contain the following 2 or 3 files:

<modulname>.qpf Quartus project file of module <modulename>. <modulname>.qsf Quartus specification file of module <modulename>. <modulname>.sof optionally: Binary output file from successful synthesis. It can

be downloaded into the Cyclone II FPGA. No need to save this file, because clicking

Page 46: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 46 -

the Quartus II compile button will generate it again if – and only if – the corresponding VHDL files in directory ../../VHDL are available.

4.2 Tools for VHDL Simulation and Synthesis

4.2.1 Getting Familiar with the ModelSim VHDL Simulator

4.2.1.1 Getting Started with the ModelSim VHDL Simulator

Start ModelSim, decline Jumpstart window with Close button. Next it is important to navigate ModelSim into the desired working directory in which new files will be created: File Change Directory <directory_name>

Type command “dir” into the transfer window to get listed the files in your actual working directory. Close ModelSim, restart it, close Jumpstart window. With menu command File Recent Directory <directory_name>

You can easily go back to recent directories within that you closed the ModelSim. Navigate With ModelSim to directory <tree>\adac\ModelSim\testbenches\tb_counter\. Being in folder adac you can also use the change directory (cd) command in the transcript window (note the Linux use of slash “/” instead of backslash “\”): cd <tree>/adac/ModelSim/testbenches/tb_counter/ In the transcript window any activity is logged in form of equivalent commands, also activities from the menu control. The language of these commands is the script language Tcl/Tk. Lines beginning wit a # are comment lines. You can copy these logged Tcl/Tk lines into a file with extension <filename>.do and then run the script with command do <filename>.do

In our ModelSim subdirectories we have typically one VHDL testbench and two do files: tb_<entity_name>.vhd # VHDL testbench for entity <entity_name> work.do # Tcl/Tk commands running the testbench wave.do # Tcl/Tk for graphics window, called from work.do With ModelSim working directory set to <>\adac\Modelsim\tb_counter\ type dir into the transfer window. ModelSim should list files tb_counter.vhd, work.do, wave.do. Type “do work.do” into the transcript window. You should see a wave window as shown in Fig. 4.2.1.

Page 47: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 47 -

Fig. 4.2.1: Wave window delivered by ModelSim. From Listings 4.2.1 (a) and (b). Open file work.do. You can do within ModelSim writing “edit work.do” into the Transcript window or with an ASCII editor. We find the Tcl/Tk code shown in Listing 4.2.1.1. Listing 4.2.1.1 : contents of file work.do within ModelSim subdirectory tb_counter

1. vlib work 2. vmap work work 3. vcom -work work ../../../VHDL/counter.vhd 4. vcom -work work tb_counter.vhd 5. #vsim work.tb_counter(beh_tb_counter); 6. vsim work.cfg_tb_counter 7. do wave.do 8. run 1 us Line 1 creates the working library work and generates a warning if it already exists. Line 2 maps the logical VHDL symbol work to the physical working library work. Line 3 compiles file ../../../VHDL/counter.vhd into the working library work. Line 4 compiles testbench tb_counter.vhd into the working library work. Line 5 is a comment line as it begins with a # in its first column Line 6 loads the design unit cfg_tb_counter from library work. Line 7 calls the Tcl/Tk file wave.do that prepares the graphics window Line 8 runs the simulation for 1 micro second simulation time.

Page 48: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 48 -

4.2.1.2 The VHDL Testbench

The VHDL Testbench contains an entity, an architecture and a configuration as shown in listing 72.1.2 Listing 4.2.1.2: contents of file tb_counter within ModelSim subdirectory tb_counter

1. ENTITY tb_counter IS 2. END ENTITY tb_counter; 3. 4. LIBRARY ieee;USE ieee.std_logic_1164.ALL; 5. ARCHITECTURE beh_tb_counter OF tb_counter IS 6. CONSTANT cPeriod:NATURAL:=10; 7. SIGNAL reset,clock,EnableIn:std_logic:='0'; 8. SIGNAL count0,count1,count2:NATURAL RANGE 0 TO cPeriod-1; 9. SIGNAL EnableOut0,EnableOut1,EnableOut2:std_logic; 10. -- 11. COMPONENT counter IS 12. GENERIC(cPeriod:POSITIVE:=10); 13. PORT(reset,clock:IN std_logic; 14. EnableIn:IN std_logic; 15. EnableOut:BUFFER std_logic; 16. count:BUFFER NATURAL RANGE 0 TO cPeriod-1 17. ); 18. END COMPONENT counter; 19. -- FOR ALL:counter USE CONFIGURATION work.cfg_counter; 20. CONSTANT fclk:REAL:=50.0E6; 21. BEGIN 22. clock <= NOT clock AFTER sec/(2.0*fclk); 23. reset <= '0', '1' AFTER 12 ns; 24. EnableIn <= '1', '0' AFTER 355 ns, '1' AFTER 545 ns; 25. i_cnt0:counter GENERIC MAP(cPeriod) 26. PORT MAP(reset,clock,EnableIn,EnableOut0,count0); 27. i_cnt1:counter GENERIC MAP(cPeriod) 28. PORT MAP(reset,clock,EnableIn,EnableOut1,count1); 29. i_cnt2:counter GENERIC MAP(cPeriod) 30. PORT MAP(reset,clock,EnableIn,EnableOut2,count2); 31. END ARCHITECTURE beh_tb_counter; 32. 33. CONFIGURATION cfg_tb_counter OF tb_counter IS 34. FOR beh_tb_counter 35. FOR i_cnt0:counter USE ENTITY work.counter(rtl_counter_fsm0); 36. END FOR; 37. FOR i_cnt1:counter USE ENTITY work.counter(rtl_counter_fsm1_dn); 38. END FOR; 39. FOR OTHERS:counter USE CONFIGURATION work.cfg_counter; 40. END FOR; 41. END FOR; 42. END CONFIGURATION cfg_tb_counter;

Page 49: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 49 -

4.2.1.3 Working Within the ModelSim Environment

Graphics: wave Window

Move the cursor in the wave window with your mouse pointer. You will see that the values of the signals in the objects window will show the signal value under the cursor. Adding a new signal in this window requires to save the wave-window command file wave.do and recompile the design. Graphics data from ModelSim simulation is stored in file vsim.wlf created in your active directory. If this file is available you can open it from the menu with File Open vsim.wlf. After typing do wave.do into the transcript window you get back your graphics format. Delete undesired signals in the window with Delete button of your keyboard. Exercise wave window 1: Edit the Wave Window Run do work.do in directory.../tb_counter/ to get Fig. 4.2.1. Edit the wave window: Delete signals from wave window: Click with left mouse button on signal names in the

wave window and then press Delete button of your keyboard. Add signals back to wave window: Draw deleted signals with your mouse (holding left

mouse button) Objects window to wave window. You should see their data now. Add signals to wave window that have not been there during simulation: There is no

data save in vsim.wlf for signals that were not in the wave window during simulation. Simulate again!

Exercise wave window : Save the Wave Window Specification File wave.do After changing the wave window in ModelSim rerun the simulation (type do work.do). See no changes? You have to save the wave.do file before: Click into the wave window

to activate it, then click on Save-File button in the menu bar and acknowledge overwriting of wave.do.

Run simulation again. Do you see the modifications now? (Should!) Exercise wave window 3: Rebuild the Wave Window After running do work.do in directory.../tb_counter/ you get Fig. 4.2.1. Close ModelSim,

delete all newly created files except vsim.wlf. To rebuild the wave window as shown in Fig. 4.2.1:

Restart ModelSim, go to directory .../tb_counter/ open file vsim.wlf type do wave.do into the transcript window delete redundant information in the wave window

Workspace window

Check for the workspace window. It has views Library, sim, Files and Memories. Click on Library view and open library work. You will see all the design units you have compiled into this working library. Click on entity counter to see the associated architectures. The one closest to the entity is the one used by default.

Page 50: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 50 -

At the bottom of the Workspace window click on view sim. You will see the Instance window. (Instantiations in hardware correspond to subprogram calls in software.) A double-click on particular design units in the Instance window opens the respective VHDL source code in the debug window. There, code Lines with red line numbers are executable. Click on the Single Step symbol in the menu bar to see the simulator stepping through the code. You can set breakpoints using right mouse button. Using the ModelSim ASCII Editor

Exercise: Set a breakpoint by double-click on a red VHDL code line and then type “run 1us” into

the transcript window. You can see the actual signal value of the code in the Objects window and proceed step by step clicking on the Step button.

At the bottom of the Workspace window click on view Files. You should find your files used under root sim. Click on any filename to see its content in the debugger window.

The ModelSim simulator will simulate any VHDL description that is compliant with the VHDL Language Reference Manual (LRM) – regardless if the code is synthesizeable or not.

Page 51: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 51 -

4.2.2 Getting Familiar with Quartus II 8.1 for VHDL Synthesis

Quartus II will compile VHDL code if – and only if – it can be synthesized it for the specified Altera target device. If compilation (specialists say analysis) was successful we can download the synthesized binary data from a file with extension *.sof into the target device. Compiled code can be simulated. However, as testbenches are behavioral we cannot compile them with Quartus II. Examples for non-synthesizable code for Altera FPGAs:

clock <= NOT clock AFTER 5 ns; Flipflop with clock signal dominant to reset signal

To simulate VHDL code with Quartus II we need to define the input signals in a very Altera specific manner as we cannot compile behavioral code of testbenches. Therefore, in this ADAC project simulation is done with ModelSim so that testbenches can be written in VHDL. Note: Quartus II 8.1 supports the Cyclone II FPGA on DE2 board. Quartus II 13.1 is the last Quartus version that supports Cyclone II FPGAs, later versions do not. In our Quartus II directories we have typically between 3 or 4 files: ci_<project_name>.vhd # VHDL configuration interface ci_<project_name>.qpf # Quartus project file ci_<project_name>.qsf # Quartus specification file ci_<project_name>.sof # Optional: Quartus output file ready for download FPGA Quartus II will generate many other files that can be deleted after compilation. With the first 3 files cited above you can do all the necessary compilation of available VHDL files. The *.sof file is ready for download into the Cyclone II FPGA without any further compilation. Exercise : Navigate under Windows to directory ADAC/QuartusII81/counter/. You will find the files ci_counter.qpf # Quartus project file ci_counter.qsf # Quartus specification file ci_couner.vhd # VHDL configuration interface The configuration interface ci_counter instantiates the counter as submodule cfg_counter: ci_counter(rtl_ci_counter) i:counter cfg_counter=counter(rtl_counter_fsm2_up); Use an ASCII Editor to look into Quartus II specification file counter.qsf, then open project file counter.qpf without making the ASCII editor the main program to open this file!

Page 52: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 52 -

Double-click on counter.qpf. Quartus II should come up. If not, open Quartus II and close it again, then double-click again on counter.qpf. It is a project file compiling component counter. Select from Quartus II main menu: Processing Start Compilation. This starts compilation of files ../../VHDL/counter.vhd ../../VHDL/cfg_counter.vhd ./ci_counter.vhd This can be seen by selecting in the main menu Project Add/Remove Files in Project. Double-click in window Project Navigator Files on entry counter to see the VHDL code. From main menu Tools Netlist Viewers RTL Viewer (where RTL stand for Register Transfer Level) you can see the synthesizer’s result of compiling the VHDL code into a circuit that can be downloaded into the FPGA. Look under Assignments Device for which target technology this compilation was done. Remember for later use: Device Family: .............................................. Device Selected: .............................................. Download the compiled binary code of this counter into the Cyclone II FPGA: Select from main menu Tools Programmer. Check in the top bar right to button Hardware Setup: It must be USB Blaster.Otherwise click on button Hardware Setup and install the USB Blaster. Then click on counter.sof, Flag Program/Configure must be set, and press button Start. All you see is some diodes darkening on the DE2 board. Congratulation! You have successfully synthesized module counter and downloaded it into the FPGA. Unfortunately, you have no access to it. Unfortunately, you have no access to the counter downloaded into your FPGA. We will fix that in the next exercise. Structural diagram: # this is comment cfg_counter(counter+rtl_counter_fsm2_up); # semi-colon ends hierarchy cfg_tb_counter(tb_counter+beh_tb_counter) # executable configuration i_cnt0:counter work.counter+rtl_counter_fsm0; i_cnt1:counter work.counter(rtl_counter_fsm1_dn); OTHERS:counter work.cfg_counter; tb_counter+beh_tb_counter #executable: entity tb_counter+beh_tb_counter i_cnt0:counter work.counter+rtl_counter_fsm0; # indented: sub-module i_cnt1:counter work.counter+rtl_counter_fsm1_dn; OTHERS:counter work.cfg_counter;

Page 53: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 53 -

4.3 Configuration: System Assembly

4.3.1 Configuration Declaration in VHDL

The VHDL configuration defines which design units will be used in our system. A VHDL design is made up of 3 basic design units: VHDL construct corresponds to physical significance ENTITY symbol description to the outer world ARCHITECTURE schematics inner realization of the symbol CONFIGURATION combination: which schematics fills which symbol An entity statement is declared as

ENTITY e IS ... END ENTITY e; and must be compiled before dedicated architectures, which are declared as

ARCHITECTURE rtl_a1 OF e IS ... BEGIN ... END ARCHITECTURE a1; ARCHITECTURE rtl_a2 OF e IS ... BEGIN ... END ARCHITECTURE a2; ARCHITECTURE rtl_a3 OF e IS ... BEGIN ... END ARCHITECTURE a3; Note that an architecture is dedicated to a particular entity, and that an entity can have an arbitrary number of assigned architectures. The configuration defines which architecture is associated with an entity. Configurations can be made in 3 ways:

1. Default configuration 2. Configuration Declaration 3. Configuration specification 1. Default configuration If no explicit configuration exists for an entity, the default configuration is used to fill an entity with the youngest (i.e. last compiled) architecture of this entity. 2. A configuration declaration is declared (a) flat as

CONFIGURATION cfg_e OF e IS FOR rtl_e END FOR; END CONFIGURATION cfg_e; (b) structural (i.e. hierarchical) as

CONFIGURATION cfg_e OF e IS FOR rtl_e FOR label1:e1 USE ENTITY work.e1(rtl_e1); END FOR; FOR label2:e1 USE ENTITY work.e1(rtl_e2); END FOR; FOR label3:e1 USE CONFIGURATION work.cfg_e1; END FOR; END FOR; END CONFIGURATION cfg_e;

Page 54: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 54 -

3. The configuration specification is a single statement within the declaration region of an architecture. Remind crib: SSS: Configuration Specification is a Single Statement. Example:

ARCHITECTURE rtl_e OF e IS FOR label1:e1 USE ENTITY work.e1(rtl_e1); FOR label2:e1 USE ENTITY work.e1(rtl_e2); FOR label3:e1 USE CONFIGURATION work.cfg_e1; BEGIN label1:e1 GENERIC MAP(...) PORT MAP(...); label2:e1 GENERIC MAP(...) PORT MAP(...); label3:e1 GENERIC MAP(...) PORT MAP(...); END ARCHITECTURE rtl_e; A configuration declaration is more flexible. Instantiation of a sub-module as entity(architecture) combination ends the configuration tree depth, while instantiation of a configuration allows for further sub-component instantiations in the cited configuration.

Page 55: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 55 -

4.3.2 Configuration of Enable-Flag Generator engen

4.3.2.1 Enable-Flag Generator engen Instantiates Module Counter

i_10MHz

clock

i_1MHz i_100KHz i_10KHz i_1KHz i_100Hz i_10Hz i_1Hz

enve

c(7)

5 10 10 10 10 10 10 10

cou

nts(6)

co

un

ts(5

)

co

un

ts(4

)

co

un

ts(3

)

co

un

ts(2

)

co

un

ts(1

)

co

un

ts(0

)

cou

nts(7)

enve

c(6)

enve

c(5)

enve

c4)

enve

c(3)

enve

c(2)

enve

c(1)

enve

c(0)

counter counter counter counter counter counter counter counter

clock

clock

clock

clock

clock

clock

clock

clock

reset reset reset reset reset reset reset resetEn

ab

le In

eIn eOut eIn eOut eIn eOut eIn eOut eIn eOut eIn eOut eIn eOut eIn eOut

envec(7:0)

Enable InEnableOut

NextStateLogic

StateMemory

NextCount count

count=cPeriod-1 ?maxflgcPeriod

reset

count

&

clock

(a) engen schematics

(b) counter schematics

&

0 -> 1

1 &

1

&

1

i_10MHz i_1MHz i_1Hz

(c) engen at critical carry flag

envec(7:0)

Fig. 4.3.2.1: Enable-flag generator engen delivering envec(x)=10x Hz @ fclock=50 MHz. (a) engen schematics, (b) counter schematics, (c) counter schematics at critical ripple carry. Fig. 4.3.2.1(a) shows the schematics of an enable-flag generator instantiating module counter. Flags on envec(x), x=0-7, occur with a frequency of 10x Hz and have a with of 1 clock cycle, that is of T=1/fclock=20ns at fclock=50MHz. Fig. 4.3.2.1(b) illustrates the inner schematics of a counter instance. Fig. 4.3.2.1(c) illustrates the critical path of engen. This is the path that fails first when the clock frequency is continuously increased: The fastest counting counter sets its EnableOut bit which then ripples through the counter chain to set envec(0) at the end. To measure the delay of envec(0) with respect to envec(7) we will use the engen instance within module de2_engen, which fits engen into the DE2 board environment.

Page 56: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 56 -

Listing 4.3.2.1(a) shows the corresponding VHDL entity and architecture. Listing 4.3.2.1(b) shows the corresponding configurations within file cfg_de2_engen.vhd. Before this file can be compiled, the file de2_engen.vhd containing module de2_engen must be compiled, which fits module engen into the DE2 board environment. Listing 4.3.2.1: VHDL model of enable-flag generator engen instantiating module counter

(a): Entity and architecture within file engen.vhd.

------------------------------------------------------------------------------- -- Module : engen -- Designer : Martin Schubert -- Date last modified: 11.11.2016 -- Purpose : enable-vector generator -- -- Constants : - -- Input-Signals : reset : std_logic, asynchonous, doninant reset -- clock : std_logic, 50MHz-clock signal -- EnableIn: std_logic, flipflops can toggle if enable='1' -- Output-Signals: envec:std_logic_vector(7:0) freq. of envec(i) = 10^i -------------------------------------------------------------------------------LIBRARY ieee; USE ieee.std_logic_1164.ALL; ENTITY engen IS GENERIC(cEnvecWidth:POSITIVE:=8); PORT(reset,clock,EnableIn:IN std_logic; envec:BUFFER std_logic_vector(cEnvecWidth-1 DOWNTO 0) ); END ENTITY engen; ------------------------------------------------------------------------------- -- Schematics : rtl_engen -- Designer : Martin Schubert -- Date last modified : 15.04.2011 -- Purpose : Schematics of Entity engen ------------------------------------------------------------------------------- ARCHITECTURE rtl_engen OF engen IS COMPONENT counter IS GENERIC(cPeriod:POSITIVE:=10;cResetValue:NATURAL:=0;cDelay:TIME:=0 ns); PORT(reset,clock:IN std_logic; EnableIn:IN std_logic; EnableOut:BUFFER std_logic; count:BUFFER NATURAL RANGE 0 TO cPeriod-1 ); END COMPONENT counter; TYPE count_vector IS ARRAY(NATURAL RANGE <>) OF NATURAL RANGE 0 TO 9; SIGNAL counts:count_vector(cEnvecWidth-1 DOWNTO 0); BEGIN -- i_10MHz :counter GENERIC MAP(cPeriod=> 5) PORT MAP(reset,clock,EnableIn,envec(7),counts(7)); i_1MHz :counter GENERIC MAP(cPeriod=>10) PORT MAP(reset,clock,envec(7),envec(6),counts(6)); i_100KHz:counter GENERIC MAP(cPeriod=>10) PORT MAP(reset,clock,envec(6),envec(5),counts(5)); i_10KHz :counter GENERIC MAP(cPeriod=>10) PORT MAP(reset,clock,envec(5),envec(4),counts(4)); i_1KHz :counter GENERIC MAP(cPeriod=>10) PORT MAP(reset,clock,envec(4),envec(3),counts(3)); i_100Hz :counter GENERIC MAP(cPeriod=>10) PORT MAP(reset,clock,envec(3),envec(2),counts(2)); i_10Hz :counter GENERIC MAP(cPeriod=>10) PORT MAP(reset,clock,envec(2),envec(1),counts(1)); i_1Hz :counter GENERIC MAP(cPeriod=>10) PORT MAP(reset,clock,envec(1),envec(0),counts(0)); -- END ARCHITECTURE rtl_engen; (b): Configuration declaration for entity engen instantiating module counter.

CONFIGURATION cfg_engen OF engen IS FOR rtl_engen FOR ALL:counter USE CONFIGURATION work.cfg_counter; END FOR; END FOR; END CONFIGURATION cfg_engen;

Page 57: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 57 -

4.3.2.2 Interface Module de2_engen fits engen into the DE2 board

i_cnt0

clock

i_cnt1 i_cnt2 i_cnt3 i_cnt4 i_cnt5 i_cnt6 i_cnt7

16 16 16 16 16 16 16 16

Co

un

tOu

t (0)

counter counter counter counter counter counter counter counter

clock

clock

clock

clock

clock

clock

clock

reset reset reset reset reset reset reset reset

Sampling Flag

eIn eOut eIn eOut eIn eOut eIn eOut eIn eOut eIn eOut eIn eOut eIn eOut

EnCountOut(7:0)

engenenvec(7:0)

EnableIn

clock

reset

key (0)

key (1)

sw(2:0)

mu

x8

display7seg

hex0 (0:6)hex1 (0:6)hex2 (0:6)hex3 (0:6)hex4 (0:6)hex5 (0:6)hex6 (0:6)hex7 (0:6)

CountOut (7:0)

3

Co

un

tOu

t (1)

Co

un

tOu

t (2)

Co

un

tOu

t (3)

Co

un

tOu

t (4)

Co

un

tOu

t (5)

Co

un

tOu

t (6)

Co

un

tOu

t (7)

HexDigits (7:0)

ShowFreq (7:0)8

8

8

sw(4)

8 x mu

x2

clock_50

key(2) 1

0

mu

x2sw(3)

clock

1

0

En

Co

untO

ut(6

)

En

Co

untO

ut(7

)

En

Co

untO

ut(5

)

En

Co

untO

ut(4

)

En

Co

untO

ut(3

)

En

Co

untO

ut(2)

En

Co

untO

ut(1

)

En

Co

untO

ut(0)

Fig. 4.3.2.2: Schematics of module de2_engen interfacing engen into the DE2 board. Listing 4.3.2.1 Configuration declaration statements within file cfg_de2_engen.vhd.

------------------------------------------------------------------------------- -- Module : de2_engen -- Designer : Martin Schubert -- Date last modified: 08.11.2016 -- Purpose : Fit enable generator on Terasic's DE2-Board with -- Altera FPGA Cyclone II EP2C35F672C6 -- -- I/O Signals : clock_50 : IN std_logic: 50MHz clock signal -- CLOCK_27 : IN std_logic: 27MHz clock signal -- key(3:0) : IN std_logic_vector: 4 monostable push buttons -- sw(17:0) : IN std_logic_vector: 18 bistable switches -- ledg(8:0) : BUFFER 9 green LEDs -- ledr(17:0) : BUFFER 18 red LEDs -- hex0...hex7 : control bits for hex display, low-active -- gpio_0(35:0): 36 general purpose I/O pins of user header J1 -- gpio_1(35:0): 36 general purpose I/O pins of user header J2 ------------------------------------------------------------------------------- LIBRARY ieee; USE ieee.std_logic_1164.ALL; ENTITY de2_engen IS PORT(CLOCK_50,CLOCK_27:IN std_logic; key:IN std_logic_vector(3 DOWNTO 0); -- low when pressed sw:IN std_logic_vector(17 DOWNTO 0); -- low when pulled down ledg:BUFFER std_logic_vector(8 DOWNTO 0); -- high active ledr:BUFFER std_logic_vector(17 DOWNTO 0); -- high active hex0,hex1,hex2,hex3,hex4,hex5,hex6,hex7:OUT std_logic_vector(0 TO 6); gpio_0:BUFFER std_logic_vector(35 DOWNTO 0); gpio_1:INOUT std_logic_vector(35 DOWNTO 0) ); END ENTITY de2_engen; LIBRARY ieee; USE ieee.std_logic_signed.conv_integer; USE ieee.std_logic_arith.conv_std_logic_vector; ARCHITECTURE rtl_de2_engen OF de2_engen IS CONSTANT cPeriod:NATURAL:=16; COMPONENT counter IS GENERIC(cPeriod:POSITIVE:=10;cResetValue:NATURAL:=0;cDelay:TIME:=0 ns); PORT(reset,clock:IN std_logic; EnableIn:IN std_logic; EnableOut:BUFFER std_logic; count:BUFFER NATURAL RANGE 0 TO cPeriod-1 ); END COMPONENT counter;

Page 58: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 58 -

-- COMPONENT display7seg IS PORT(i0,i1,i2,i3,i4,i5,i6,i7:IN NATURAL RANGE 0 TO 16; h0,h1,h2,h3,h4,h5,h6,h7:BUFFER std_logic_vector(0 TO 6) ); END COMPONENT display7seg; -- CONSTANT cEnvecWidth:POSITIVE:=8; SIGNAL EnCountOut,envec:std_logic_vector(cEnvecWidth-1 DOWNTO 0); SIGNAL EnCountOut_3,EnCountOut_30:std_logic; COMPONENT engen IS GENERIC(cEnvecWidth:POSITIVE:=8); PORT(reset,clock,EnableIn:IN std_logic; envec:BUFFER std_logic_vector(cEnvecWidth-1 DOWNTO 0) ); END COMPONENT engen; -- SIGNAL reset,clock,EnableIn,SamplingFlag:std_logic; SIGNAL selDigit:NATURAL RANGE 0 TO 7; SUBTYPE t_digit IS NATURAL RANGE 0 TO 16; -- 16 is dark TYPE t_digits IS ARRAY(NATURAL RANGE <>) OF t_digit; SIGNAL CountOut_3,CountOut_30:t_digit; SIGNAL CountOut,ShowFreq,digits:t_digits(7 DOWNTO 0); BEGIN -- reset <= key(0); EnableIn <= key(1); -- mux2: select clock source: manual or clock_50 MHz clock <= clock_50 WHEN sw(3)='0' ELSE key(2); -- manual clocking with key(2) -- -- enable generator i_engen:engen GENERIC MAP(cEnvecWidth) PORT MAP(reset,clock,EnableIn,envec); -- -- mux8: select 1 out of 8 eneable signals SamplingFlag <= envec(conv_integer('0' & sw(2 DOWNTO 0))); -- -- enabled counters i_cnt0 :counter GENERIC MAP(cPeriod) PORT MAP(reset,clock,SamplingFlag, EnCountOut(0),CountOut(0)); i_cnt1 :counter GENERIC MAP(cPeriod) PORT MAP(reset,clock,EnCountOut(0),EnCountOut(1),CountOut(1)); i_cnt2 :counter GENERIC MAP(cPeriod) PORT MAP(reset,clock,EnCountOut(1),EnCountOut(2),CountOut(2)); i_cnt3 :counter GENERIC MAP(cPeriod) PORT MAP(reset,clock,EnCountOut(2),EnCountOut_3 ,CountOut_3 ); i_cnt30:counter GENERIC MAP(cPeriod) PORT MAP(reset,clock,EnCountOut(2),EnCountOut_30,CountOut_30); i_cnt4 :counter GENERIC MAP(cPeriod) PORT MAP(reset,clock,EnCountOut(3),EnCountOut(4),CountOut(4)); i_cnt5 :counter GENERIC MAP(cPeriod) PORT MAP(reset,clock,EnCountOut(4),EnCountOut(5),CountOut(5)); i_cnt6 :counter GENERIC MAP(cPeriod) PORT MAP(reset,clock,EnCountOut(5),EnCountOut(6),CountOut(6)); i_cnt7 :counter GENERIC MAP(cPeriod) PORT MAP(reset,clock,EnCountOut(6),EnCountOut(7),CountOut(7)); -- CountOut(3) <= CountOut_3 WHEN key(3)='1' ELSE CountOut_30; EnCountOut(3) <= EnCountOut_3 WHEN key(3)='1' ELSE EnCountOut_30; i_display7seg:display7seg PORT MAP(digits(0),digits(1),digits(2),digits(3),digits(4),digits(5),digits(6),digits(7), hex0, hex1, hex2, hex3, hex4, hex5, hex6, hex7); -- -- control green LEDs ledg(8) <= key(2); selDigit <= CONV_INTEGER('0'&sw(7 DOWNTO 5)); ledg(7 DOWNTO 4) <= conv_std_logic_vector(CountOut(selDigit),4); ledg(3 DOWNTO 0) <= NOT key; -- -- control red LEDs p_ledr:PROCESS(key) BEGIN ledr <= sw; END PROCESS p_ledr; -- -- control 7-segment display driver: p_n:PROCESS(sw) VARIABLE v_swSelect:INTEGER RANGE 0 TO 7; BEGIN v_swSelect := CONV_INTEGER('0'&sw(2 DOWNTO 0)); l_digits: FOR i IN ShowFreq'RANGE LOOP IF i < v_swSelect THEN ShowFreq(i) <= 0; -- 7-seg-display = 0 ELSIF i = v_swSelect THEN ShowFreq(i) <= 1; -- 7-seg-display = 1 ELSE ShowFreq(i) <= 16; -- 7-seg-display dark END IF; END LOOP l_digits; END PROCESS p_n; -- -- 8 x mux2: 7seg display show frequnecy or count state digits <= ShowFreq WHEN sw(4)='0' ELSE CountOut; -- -- drive external pins: -- gpio signal name header.pin functionality channel color gpio_1( 0) <= SamplingFlag; -- JP2.1 : selected flag -> CH1 yellow gpio_1( 2) <= clock_50; -- JP2.3 : system clock -> CH2 green gpio_1(16) <= envec(7); -- JP2.19: fastest flag -> CH3 blue gpio_1(18) <= envec(0); -- JP2.21: slowest flag -> CH4 red gpio_0 <= gpio_1; -- copy JP2 -> JP1 -- END ARCHITECTURE rtl_de2_engen;

Page 59: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 59 -

4.3.2.3 Configuration of engen and de2_engen Using the ModelSim Simulator

File cfg_de2_engen.vhd contains the configuration of module de2_engen. Its source code is listed in listing 4.3.2.3. Listing 4.3.2.3 Configuration declaration statements within file cfg_de2_engen.vhd.

CONFIGURATION cfg_counter OF counter IS FOR rtl_counter_fsm2_up END FOR; END CONFIGURATION cfg_counter; CONFIGURATION cfg_engen OF engen IS FOR rtl_engen FOR ALL:counter USE CONFIGURATION work.cfg_counter; END FOR; END FOR; END CONFIGURATION cfg_engen; CONFIGURATION cfg_display7seg OF display7seg IS FOR rtl_display7seg END FOR; END CONFIGURATION cfg_display7seg; CONFIGURATION cfg_de2_engen OF de2_engen IS FOR rtl_de2_engen FOR i_display7seg:display7seg USE CONFIGURATION work.cfg_display7seg; END FOR; FOR i_engen:engen USE CONFIGURATION work.cfg_engen; END FOR; FOR i_cnt30:counter USE ENTITY work.counter(rtl_counter_fsm0); END FOR; FOR i_cnt0,i_cnt2,I_cnt4,i_cnt6:counter USE CONFIGURATION work.cfg_counter; END FOR; FOR OTHERS:counter USE ENTITY work.counter(rtl_counter_fsm1_dn); END FOR; --FOR OTHERS:counter USE ENTITY work.counter(rtl_counter_bcd_safe); END FOR; END FOR; END CONFIGURATION cfg_de2_engen; Exercise: What is the most critical path of this design? (Consider enable ripple flags!) ..............................................................

Page 60: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 60 -

4.3.2.4 Configuration of engen and de2_engen Using the ModelSim Simulator

Copy the directory system shown in Fig. 4.1. onto your local drive, hereinafter termed <>. Start ModelSim and navigate it to directory <>/adac/ModelSim/Testbenches/tb_de2_engen/ . To do so select from the ModelSim toolbar File Change Directory ... . In directory tb_de2_engen you find the files tb_de2_engen.vhd design units de2_engen + rtl_de2_engen + cfg_de2_engen work.do ModelSim Tcl commands wave.do ModelSim wave window commands (graphical settings

Run the Tcl file work.do by typing do work.do into ModelSim’s transcript window. You will get quite a boring graphics. Give the explanation in the exercise below. Exercise 1: We compute 1.25ms simulation time above. How much simulation time would we have to simulate to see one complete cycle of the 1Hz enable flag signal envec(0)? ............................................................. Exercise 2: Look into ModelSim’s In the workspace window / Library view and look into library work. What are the two top-level design units that we can load and simulate? ............................................................. ............................................................. Exercise 3: Click through ModelSim’s workspace window / sim view and check if you got the configurations as configured shown in listing 4.2.3.1. Do you? ................ Exercise 4: In file work.do change lines From To #vsim work.tb_de2_engen vsim work.tb_de2_engen vsim work.cfg_tb_de2_engen #vsim work.cfg_tb_de2_engen As # in the first column of Tcl commands indicates a comment line, we do now no more simulate the configuration cfg_tb_de2_engen but entity tb_de2_engen. Which default architecture is now loaded now for all counter modules? Why? ..............................................................

Page 61: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 61 -

4.3.2.5 Configuration of engen and de2_engen Using Quartus II for Synthesis

With free QUARTUS II software we cannot load a top-level configuration, and we cannot rely on which architecture of an entity will be loaded. But we can use configuration specification statements. To do so we use a VHDL file as configuration interface to get into the configuration tree. Structural diagram:

work.(ci_de2_engen+rtl_ci_de2_engen) i_fpga:engen_lib.cfg_de2_engen(de2_engen+rtl+de2_engen) i_engen:engen engen_lib.engen_lib.cfg_engen(=engen+rtl_engen) i_cnt1:counter engen_lib.counter+rtl_counter_1; OTHERS:counter engen_lib.cfg_counter(=counter+rlt_counter_2); Fig. 4.3.2.5: Hierarchy:

ci_de2_engen is required to switch structure control to the configuration tree.

de2_engen is necessary to fit engen into DE2 board.

engen is an enable-flag generator.

counter is a configurable counter module.

ci_de2_engen

rtl_ci_de2_engen

de2_engen

rtl_de2_engen

engen

rtl_engen

counter

rtl_counter_#

engen_lib.cfg_de2_engen

engen_lib.cfg_engen

engen_lib.cfg_counter

work.(ci_de2_engen+rtl_ci_de2_engen)

Listing 4.3.2.5 Configuration interface getting Quartus II into configuration cfg_de2_engen.

1. ENTITY ci_de2_engen IS 2. PORT(....); 3. END ENTITY ci_de2_engen; 4. 5. ARCHITECTURE rtl_ci_de2_engen OF ci_de2_engen IS 6. COMPONENT de2_engen IS 7. PORT(... ); 8. END COMPONENT de2_engen; 9. FOR i_fpga:de2_engen USE CONFIGURATION work.cfg_de2_engen; 10. BEGIN 11. i_fpga:de2_engen PORT MAP(...); 12. END ARCHITECTURE rtl_ci_de2_engen; Line 9. of listing 4.2.3.4 is the configuration specification which declares that for instantiation i_fgpa:de2_engen in line 11 the configuration work.cfg_de2_engen has to be used. Doing so we are in the configuration declaration tree.

Page 62: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 62 -

Exercise: Start Quartus II and create a project in directory <>\adac\QuartusII81\de2_engen\ . Project name and top-level entity name must be ci_de2_engen. This entity and its architecture as sketched in listing 4.3.2.5 is contained in file ci_de2_engen.vhd. Select Cyclone II device EPC2C35F672C6. After finishing that load the respective pin assignments from file DE2_pin_assignments.csv, that is located in the parent directory. Next we have to load from ../../VHDL/ the required VHDL files: from Project Add/remove Files in Project navigate to directory ..\..\VHDL\ and load files cfg_de2_engen.vhd, counter.vhd, de2_engen, engen.vhd , display.7seg.vhd. Don’t mind about compilation order, Quartus II selects the compilation order by itself. To do so, the user has to declare the top-level entity. Compile the project and load ci_de2_engen.sof into your Cyclone II FPGA on the DE2 board. The drawback of missing compilation order by latest compilation is that Quartus II accepts every module only once. An error message occurs if you compile a module twice. (By VHDL default, the youngest = last compiled should be used.)

Page 63: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 63 -

Checking for the switches (bi-stable, set not mentioned switches to '0')

In the following ... the VHDL range notations (a TO b) and (d DOWNTO c) are written as (a:b) and (d:c). 1 or all 8 digits of the 7-segment display are noticed as 7seg(i) or 7segs, respectively. Set sw (17:0)="00...0". What shows the 7-segment display? 7segs = ........... Play with sw(2:0). Correlation between sw(2:0) and displayed No.? 7segs = ........... The number seen on 7segs is the frequency of the enable flag named SamplingFlag delivered by enable generator engen. Set sw(4)='1'. Now 7segs show the state of the counter chain in de2_engen. By default, some counters should count up and some should count down. Control their counting speed with sw(2:0). Set sw(3)='1'. Now the clock Signal is connected to push-button key(3). To see the a change on the fastest digit on 7segs you have to perform 50 MHz / 10sw(2:0) clocks. Set sw(2:0)="111" and press repeatedly key(2) until you see a change on digit HEX0. Play with sw(7:5). They select which digit of the 7segs is driven as bits to ledg(7:4). Checking for the keys (mono-stable, not mentioned push-buttons are not pushed). Set sw(4:0)="10111"'. You should observe the states of the counters running up or down. Push key(0) What is its function? ..................... Push key(1) What is its function? ..................... Push key(2) while sw(3)='1'. What is function of key(2)? ..................... Push key(3). What is its function? ....................................... Checking for the LEDs. What is the control signal of the red LEDs? ledr(17:0) = ..................... What is the control signal of green LEDs(3:0)? ledg(3:0) = ..................... What is the control signal of green LEDs(7:4)? ledg(7:4) = ..................... What is the control signal of green LED(8)? ledg(8) = .....................

Page 64: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 64 -

Checking for the particular signal.

Within de2engen and de2_adac we find the statements

(a) -- drive external pins: (b) -- gpio signal name header.pin functionality channel color (c) gpio_1( 0) <= SamplingFlag; -- JP2.1 : selected flag -> CH1 yellow (d) gpio_1( 2) <= clock_50; -- JP2.3 : system clock -> CH2 green (e) gpio_1(16) <= envec(7); -- JP2.19: fastest flag -> CH3 blue (f) gpio_1(18) <= envec(0); -- JP2.21: slowest flag -> CH4 red (g) gpio_0 <= gpio_1; -- copy JP2 -> JP1 Make the oscillograms shown in Fig. 4.3.2.5 with sw(2:0)="000", so that SamplingFlag is envec(0) with delay of mux8. SamplingFlag is triggered with trigger level of 1.5V and shifted vertical until its yellow line crosses exactly the central cross of the screen (see Fig. part (b)). Check carefully for sensitivity of ground connection of your BNC measurement cables! Connect them to DA2 board plugged to JP2, which is copied to JP1 (see code line (g) above). What is the width of any enable flag? Why? .............................. Measure and compute the delay of an AND gate on the FPGA (from Fig. 4.2.3.4) .............................................................. .............................................................. Measure and compute the delay of the 8-input multiplexer of the FPGA (from Fig. 4.2.3.4) .............................................................. .............................................................. ..............................................................

(a) 200 ns = 10 clock cycles time section (b) 20 ns = 1 clock cycle time section

Fig. 4.3.2.5: Oscillograms of signals SamplingFlag, clock_50, envec(7) and envec(0).

Page 65: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 65 -

4.3.3 How to Grow a Configuration Tree

We want to configure the counters de2_engenengencounter. Start with flat configuration: The following structural diagram is no VHDL standard (, rather an invention of the author):

# text after # is comment, may be Times New Roman formatted cfg_de2_engen(de2_engen+ rtl_de2_engen); # semi colon: end of config tree depth Corresponding VHDL configuration declaration:

CONFIGURATION cfg_de2_engen OF de2_engen IS FOR rtl_de2_engen END FOR; END CONFIGURATION cfg_de2_engen; When this works use the instantiated engen module as entity(architecture): Structural diagram:

cfg_de2_engen(de2_engen+ rtl_de2_engen) # = configuration(entity+architecture) i_engen:engen work.engen+rtl_engen; Structural VHDL configuration declaration:

CONFIGURATION cfg_de2_engen OF de2_engen IS FOR rtl_de2_engen FOR i_engen:engen USE ENTITY work.engen(rtl_engen); END FOR; END FOR; END CONFIGURATION cfg_de2_engen; When this works declare configuration cfg_engen and use it for instance engen. An instantiated module (here cfg_engen) must have been compiled before it can be used by keyword USE. Structural diagram:

cfg_de2_engen(de2_engen+ rtl_de2_engen) i_engen:engen work.engen+rtl_engen ; Structural VHDL configuration declaration:

CONFIGURATION cfg_engen OF engen IS FOR rtl_engen END FOR; END CONFIGURATION cfg_engen; CONFIGURATION cfg_de2_engen OF de2_engen IS FOR rtl_de2_engen FOR i_engen:engen USE CONFIGURATION work.cfg_engen; END FOR; END FOR; END CONFIGURATION cfg_de2_engen; Question: What is the key difference with respect to deeper hierarchy between statements FOR i_e:e USE ENTITY work.e(rtl_e); FOR i_e:e USE CONFIGURATION work.cfg_e; .............................................................

Page 66: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 66 -

Exercise: Grow the configuration tree to configure the counters according to the structural diagrams. Structural diagram:

cfg_de2_engen(de2_engen+ rtl_de2_engen) i_engen:engen work.engen+rtl_engen ; ALL:counter work.counter+rtl_counter_fsm2_up; Structural VHDL configuration declaration (use an additional sheet of paper for hand writing):

Structural diagram:

cfg_de2_engen(de2_engen+ rtl_de2_engen) i_engen:engen work.cfg_engen(engen+rtl_engen); ALL:counter work.cfg(counter+rtl_counter_fsm2_up); Structural VHDL configuration declaration (use an additional sheet of paper for hand writing):

Page 67: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 67 -

4.3.4 ADAC Structural Configuration

4.3.4.1 Schematics of ADAC System fitted into DE2 Board: Module de2_adac [19]

Uadc,in Udac2,outcAdcOutWidth

ADC

cDacInWidth Ddac,in

DAC

(a)(b)

data rate: fs2

data rate:fs2 = fs0/cDsr

rate: fs1 = fs0rate: fs0

engen(enable-flags generator)

8 x mux2sw(2:0)

3

clock_50MHz

enable

clock

reset

101

10010

1100

101

MHzMHzKHzKHzKHzHzHzHz

eff

enable

d q

clock

reset

z-1d d

digital harmonic

oscillator cOscOutWidth

mux

User Logic

Freqclockenablereset

(c)

analog world analog world

c cEnableIn

cDsr=10

0000001

DsAdcOut

OscOut

cDsr

Udac1,outR2R DAC

(d)

SamplingRate

clock

SamplingRateSamplingRate

sw(7)

0

1

display7segshows freqeqncy(SamplingRate)

Fig. 4.3.4.1: (a) Top-level view, (b) flipflop schematics view and (c) flipflop DSP view, (d) 7-segment display.

Page 68: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 68 -

Table 4.3.4.1: DE2 Board User Interface

Element Function Comments

keys Mono-stable switches key(i) goes to '0' when pushed key(0) = reset global reset key(1) = EnableIn global enable key(2) clock<=key(2) when sw(3)='1' ELSE clock_50 (MHz) key(3) <unused>

switches Bi-stable switches, sw(i) goes to '0' when pushed away from board sw(2:0) set frequency of flag SamplingFlag f(SamplingFlag) = 10^sw(2:0) sw(3) '0' : adac-clock = clock_50(MHz) '1' : adac-clock = key(2), manual sw(4) '0' : display7seg = f(SamplingFlag) '1' : display7seg dark, user definable sw(5) '0' : ledg(7:0) = ΔΣ-ADC quant. out '1' : ledg(7:0) = ΔΣ-DAC output sw(6) '0' : DAC2 = ΔΣ-ADC quantizer out '1' : DAC2 = ΔΣ-DAC output sw(7) '0' : DAC1 = ΔΣ-ADC’s output '1' : DAC1 = oscillator’s output sw(10:8) set internal sinusoidal oscillator freq when sw(4)='1' sw(11) <unused> sw(12) inverts Delta-Sigma-Feedback: sw(12)='0' : dsfb<=NOT dsfb sw(13) controls Dyn. Elem. Mat. in qdem sw(13)='0'/'1' : DEM is off/on sw(14) Simul. DAC-nonlinearity in qdem sw(14)='0'/'1': nonlin-error off/on sw(15) Simul. Quantiz.-error in Flash ADC sw(15)='0'/'1' : quantiz. error off/on sw(17:16) controls quantization in qdem No.(output_levels)=2^sw(17:16)+1

Displays ledg(8) =key(2): state of manual clock green LED between 7-seg displays ledg(7:0) Quantizer output of ΔΣ ADC /DAC ADC : sw(4)='0', DAC : sw(4)='1' ledr(17:0) =sw(17:0) show stat of bi-stable switches hex7:hex0 display I/O sampling rate if sw4='0', user definable display if sw(4)='1'

GPIOs + Pins General Purpose Input Output gpio_0 JP1, gpio_1 JP2 gpio_1(0) JP1.pin1: OUT: clock_50 monitor 50 MHz system clock gpio_1(1) JP2.pin2: OUT: dac1dout(0) binary LSB driving DAC1 gpio_1(2) JP2.pin3: OUT SamplingFlag ='1' enables FFs to be clocked gpio_1(9:3) JP2.pin10:4: OUT: dac1dout(7:1) binary code driving DAC1 JP2.pin11,12: VCC5, GND Pin11: 5V, Pin12: ground gpio_1(15:10) JP2.pin18:13: OUT: doc2dout(5:0) thermometric code driving DAC2 gpio_1(16) JP2.pin19 free: compatibility to DE2-70 board gpio_1(17) JP2.pin20: OUT: doc2dout(6) thermometric code driving DAC2 gpio_1(18) JP2.pin21 free: compatibility to DE2-70 board gpio_1(19) JP2.pin22: OUT: doc2dout(t) thermometric code driving DAC2 gpio_1(25:20) JP2.pin28:23: OUT: doc3dout(5:0) thermometric code driving DAC3 JP2.pin29,30: VCC33, GND Pin29: 3.3V, Pin30: ground gpio_1(27:26) JP2.pin32:31: OUT: doc3dout(7:6) thermometric code driving DAC3 gpio_1(35:28) JP2.pin40:33: from_FlashAdc(7:0) 8bit / 9level thermometric code gpio_0(35:0) <= gpio_1(35:0), gpio_0 JP2 JP1, JP2: 40-pin user header

Page 69: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 69 -

4.3.4.2 Schematics of the A/D and D/A Conversion (ADAC) System [19]

Uadc,in Udac,out

Dadc,out

cAdcOutWidth

dsadc

cDacInWidth

Ddac,in DAC

U

Demo-dulator

dsdemod

Inter-polator

dsinterp

Modulator Mo-dulator

Demo-dulator

dsmod

da2_board

D Aanalog

lowpass

DAC

Analog(DA2 board)

Digital(DE2 board)

fs0 > fs2 fs1 > fs2fs2

UD D

(a)

(b)

D/A

A/D

dsmodad

ADC

dsdac

clockreset

DsAdcIn DsAdcOutcOutWidthcInWidth

dsadc cCtrlWidthctrl

enable1

clock

enable0

reset

DsDacIn DsDacOut

dsdac cCtrlWidthctrl

(c) (d)

Analog(DA2 board)

cInWidth cOutWidthcCtrlWidthcInWidth cOutWidthcDsr cCtrlWidth

cInWidth cOutWidth

dsfb

cUsr

Fig. 4.3.4.2-1: (a) Top-level view, (b) looking into ADC and DAC, (c) VHDL entity views. Lowpass as Σ Demodulator

fs0

sincS1fs0

digitallowpass

fs2

fs2

DsDemIn

SincDn

cInWidth

DsDemOut

cOutWidth

dsdemod

cMidWidth

filter

Fig. 4.3.4.2-2: dsdemod: sinc4 filter + down-sampling by factor 10 in SincDn, lowpass filter.

Page 70: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 70 -

Filter can be any band-pass or band–stop. This is defined by the filter coefficients. In this case of a Σ demodulator it has to be a lowpass. For more details see ADAC reference manual [19]. Resolved SincDn Decimation Filter (sinc4 Decimation)

fs0

sinc

fs2

cWidth2

sinc SincAcd

fs0 fs0

1 32

SincDnOut=sinc4

SincDnIn= sinc0

cInWidth cOutWidth

SincDn (sinc4 for down-sampling (decimation))

cWidth3cWidth1

sincsinc1 sinc2 sinc3

fs2

4

Fig. 4.3.4.2-3: SincDn: sinc4 decimation filter resolved: sinc4 with down-sampling. Interpolator Demodulator Using Sinc4 Interpolation Filter

fs0

sinc

fs2

cWidth2

sinc sinc

fs0 fs0

1 3 42

SincUpOutSincUpIn

cInWidth cOutWidth

SincUp (sinc4 for up-sampling (interpolation))

cWidth3

latchcinWidth

Fig. 4.3.4.2-4: SincUp: sinc4 interpolation (up-sampling) filter resolved.

Page 71: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 71 -

4.3.4.3 Structure of the A/D and D/A Conversion (ADAC) System

Top-level executable modules:

tb_de2_adac+beh_tb_de2_adac # for ModelSim: entity to load i_fpga: de2_adac+rtl_de2_adac; # module to be downloaded into FPGA i_da2 : da2_board+beh_da2_board; # behavioral model of DA2 board cfg_tb_de2_adac(tb_de2_adac+beh_tb_de2_adac) # 4 ModelSim: configuration 2 load i_fpga: cfg_de2_adac(de2_adac+rtl_de2_adac); # module 4 download into FPGA i_da2 : cfg_da2_board(da2_board+beh_da2_board); # behavioral model of DA2 board ci_de2_adac+rtl_ci_de2_adac(cfg_de2_adac) # 4 Quartus II: Configuration 2 download i_de2_adac: cfg_de2_adac(de2_adac+rtl_de2_adac); # module 4 download into FPGA

Structure common to all VHDL tools

de2_adac+rtl_de2_adac # adac project fitted in DE2 board enviroment b_user:BLOCK; # BLOCK statement : user defines top-level system configurations b_de2_io:BLOCK; # BLOCK statement containing the DE2-board’s I/O connections b_de2_in:BLOCK; # BLOCK statement containing the DE2-board’s input connections b_de2_out:BLOCK; # BLOCK statement containing the DE2-board’s output connections i_7seg:display+rtl_display; # driving the 7-segment display i_oscillator:oscillator+rtl_oscillator; # oscillator to generate sin test signal for DAC b_adac:BLOCK; # BLOCK statement containing the A/D and D/A conversion i_engen:engen+rtl_engen # enable-flag generator, controls effetive sampling speed i_<F>Hz:counter:cfg_counter; # <F>=10M|1M|100K|10K|1K|100|10|1, counter config. Counter+rtl_counter_fsm2_up | # counting up, 2-processes FSM-loop, | is OR rtl_counter_fsm1_dn | # counting down, 1-process FSM-loop rtl_counter_fsm0 | # empty architecture rtl_counter_bcd_safe| # bcd counter, optimized for safety rtl_counter_bcd_fast; # bcd counter, optimized for low cost i_adc:dsadc+rtl_dsadc # complete Σ ADC (ADC=A/D Converter) i_dsadc:dsmodad+rtl_dsmodad # digital part of Σ modulator of ADC i_counter:counter+rtl_counter_???; # counter to realize decimation ratio i_qdem:qdem+rtl_qdem; # Quantization and DEM (dynamic element matching) i_t2b:bits2bin+rtl_bits2bin; # translates thermometricbin code i_dsdemod:dsdemod+rtl_dsdemod # Σ demodulator = decimating lowpass system i_sincdn:SincDn+rtl_SincDn # total sinc filters for downsampling (decimation) i_sinc1,i_sinc2,i_sinc3:sinc+ # single sinc filters: rtl_SincComb # comb filter architecture rtl_SincSum_canon1_fsm1 | # 1st canonic direct struct, 1-process FSM-loop rtl_SincSum_canon1_fsm2 | # 1st canonic direct struct, 2-process FSM-loop rtl_SincSum_canon2_fsm1 | # 2nd canonic direct struct, 1-process FSM-loop rtl_SincSum_canon2_fsm2; # 2nd canonic direct struct, 2-process FSM-loop i_sinc4:SincAcd+rtl_SincAcd; # last sinc filter, accumulat & dump decimation i_filter:filter+ # digital lowpass filter at decimated clock speed rtl_filter_canon1_fsm1 | # 1st canonic direct struct, 1-process FSM-loop rtl_filter_canon1_fsm2 | # 1st canonic direct struct, 2-process FSM-loop rtl_filter_canon2_fsm1 | # 2nd canonic direct struct, 1-process FSM-loop rtl_filter_canon2_fsm2; # 2nd canonic direct struct, 2-process FSM-loop i_dac:dsdac+rtl_dsdac # Σ DAC (=D/A converter) i_up:SincUp+rtl_SincUp # total sinc filters for upsampling (interpolation) i_sinc2,i_sinc3,i_sinc4:sinc+ # sincle simc filters for upsampling rtl_SincComb rtl_SincSum_canonX_fsmY; # X, Y = 1,2 i_ds:dsmod+rtl_dsmod_order1 # Σ modulator, here of of 1st order i_quant:quantizer+rtl_quantizer; # quantizer Σ modulator

Page 72: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 72 -

4.3.4.4 Exercise: (required for the filter design tasks)

Open a 1st directory window and navigate to <>\adac\ModelSim\testbenches\tb_adac\ . Start ModelSim, navigate it in this directory. Type do work.do into the transcript window. ModelSim should deliver the simulation shown in Fig. 3.2. Open a 2nd directory window and navigate to <>\adac\QuartusII81\de2_adac\ . Start Quartus II and navigate it to this directory. Create a project ci_de2_adac using the VHDL file with same name as top-level entity. Quartus should compile the system without problems. In case you download ci_de2_adac.sof into the Cyclone II FPGA of the DE2 board you should be able to generate the oscillogram shown in Fig. 3.4. Open a 3rd dir. window and navigate it to <>\adac\VHDL\ Here you’ll find module sinc with 5 architectures: ENTITY sinc ARCHTITECTURE rtl_SincComb OF sinc ARCHTITECTURE rtl_SincSum_canon1_fsm1 OF sinc ARCHTITECTURE rtl_SincSum_canon1_fsm2 OF sinc ARCHTITECTURE rtl_SincSum_canon2_fsm1 OF sinc ARCHTITECTURE rtl_SincSum_canon2_fsm2 OF sinc Furthermore there is file cfg_de2_adac.vhd as shown in Listing 4.4.3. Open this file and modify it such, that you can configure (a) which of the 5 architectures of entity sinc will be used in module dsadc, (b) which of the 5 architectures of entity filter will be used in module dsadc, (c) which of the 5 architectures of entity sinc will be used in module dsdac. While modifying the configuration file cfg_de2_adac, confirm after any modification that it works well for both ModelSim and acknowledge from time to time that Quartus II can compile it, too. Hints: 1. With ModelSim compile the system once with work.do and then with work_short.do. 2. Architectures rtl_SincSum_canon1_fsm2 and rtl_SincSum_canon2_fsm1 are be empty until now.

Page 73: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 73 -

Listing 4.3.4.4: VHDL source code of configuration cfg_de2_adac acc. to structural diagram CONFIGURATION cfg_counter OF counter IS FOR rtl_counter_fsm2_up END FOR; -- FOR rtl_counter_fsm0_dn END FOR; -- FOR rtl_counter_fsm1_dn END FOR; -- FOR rtl_counter_bcd_safe END FOR; -- FOR rtl_counter_bcd_cheap END FOR; END CONFIGURATION cfg_counter; CONFIGURATION cfg_engen OF engen IS FOR rtl_engen FOR ALL:counter USE CONFIGURATION work.cfg_counter; END FOR; END FOR; END CONFIGURATION cfg_engen; LIBRARY adac_lib; CONFIGURATION cfg_sinc OF sinc IS FOR rtl_SincComb --FOR rtl_SincSum_canon1_fsm1 --FOR rtl_SincSum_canon1_fsm2 --FOR rtl_SincSum_canon2_fsm1 --FOR rtl_SincSum_canon2_fsm2 END FOR; END CONFIGURATION cfg_sinc; -- configuring Delta-Sigma ADC: ------------------------------- LIBRARY adac_lib; CONFIGURATION cfg_dsadc OF dsadc IS FOR rtl_dsadc FOR i_counter:counter USE CONFIGURATION adac_lib.cfg_counter; END FOR; END FOR; END CONFIGURATION cfg_dsadc; -- configuring Delta-Sigma DAC: ------------------------------- LIBRARY adac_lib; CONFIGURATION cfg_dsmod OF dsmod IS FOR rtl_dsmod_order1 END FOR; END CONFIGURATION cfg_dsmod; LIBRARY adac_lib; CONFIGURATION cfg_dsdac OF dsdac IS FOR rtl_dsdac FOR i_ds:dsmod USE CONFIGURATION adac_lib.cfg_dsmod; END FOR; END FOR; END CONFIGURATION cfg_dsdac; -- total digital System Assembly: --------------------------------- LIBRARY adac_lib; CONFIGURATION cfg_de2_adac OF de2_adac IS FOR rtl_de2_adac FOR i_engen:engen USE CONFIGURATION adac_lib.cfg_engen; END FOR; FOR b_adac FOR i_adc:dsadc USE CONFIGURATION adac_lib.cfg_dsadc; END FOR; FOR i_dac:dsdac USE CONFIGURATION adac_lib.cfg_dsdac; END FOR; END FOR; FOR b_user END FOR; FOR b_de2_io FOR b_de2_in END FOR; FOR b_de2_out FOR i_display7seg:display7seg USE ENTITY adac_lib.display7seg(rtl_display7seg); END FOR; END FOR; END FOR; FOR i_oscillator:oscillator USE ENTITY adac_lib.oscillator(rtl_oscillator); END FOR; END FOR; END CONFIGURATION cfg_de2_adac;

Page 74: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 74 -

4.4 Finite State Machine Design with VHDL

4.4.1 Modeling Combinational Logic and Memory with VHDL

Use things like adders and multipliers from libraries. Generally,

Describe your circuit as detailed as necessary and as general as possible. Preserving portability of VHDL models requires to design without taking advantage of features offered by particular soft- and hardware manufacturers. ASYNCHRONOUS RESET: Most FPGAs automatically reset all flip-flops (FFs) when they are loaded. Therefore, some FPGA designers code FFs without reset. However, migration to an other hardware requires unequivocal initial conditions. Porting HDL models to an other hardware FFs might fall randomly into '0' or '1' state. When we have several drivers to the same signal like y <= siga; y <= sigb; Within concurrent environment (i.e. outside a PROCESS or a subprogram) the sequence of the statements is irrelevant and y in the example above is a multiply driven signal, for example a bus line. This is forbidden for unresolved data types like std_ulogic. For resolved data types like std_logic a hidden resolution function decides what happens. If signal siga drives a '0' and sigb drives a '1', then a 'X' is driven to signal y. Within sequential environment (i.e. within a PROCESS or a subprogram) the last driver overrides previous drivers. In the example above signal y would be driven by the value of sigb.

Page 75: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 75 -

4.4.1.1 Modeling Edge-Triggered Memory

Model memory preferably as D-flip-flops (DFFs) with the following constructs. The IF statement executes the first branch with TRUE condition. Give reset signal highest priority! A process statement executes for initialization at time NOW=0ns (now is a VHDL function) and then if – and only if – there is an event (=signal change) in its sensitivity list. This problem becomes visible in Listing 4.2.1 part(d). Assume that signals reset='1' and q, qb were initialized to the same logic value, '0' or '1'. Then, process p_dff_err will initialize at NOW=0ns but q=qb remain unchanged, which is forbidden and can block a system at start time. p_dff:PROCESS(clk,reset) BEGIN IF reset='0' THEN q<='0; ELSIF clk'EVENT AND clk='1' THEN q<=d; END IF; END PROCESS p_dff;

p_state_memory:PROCESS(clk,reset) BEGIN IF reset ='0' THEN state<=reset_state; ELSIF clk'EVENT AND clk='1' THEN state<=next_state; END IF; END PROCESS p_state_memory;

(a) Modeling memory for a scalar state and (b) for a state vector

p_dff_good:PROCESS(clk,reset) BEGIN IF reset='0' THEN q<='0' AFTER delay; ELSIF clk'EVENT AND clk='1' THEN q<=d AFTER delay; END IF; END PROCESS p_dff_good; qb<=NOT(q); -- this is always o.k.

p_dff_err:PROCESS(clk,reset) BEGIN IF reset ='0' THEN q<='0; qb<='1; ELSIF clk'EVENT AND clk='1' THEN q<=d; qb<=NOT(d); END IF; END PROCESS p_dff_err;

(c) recommended inverting output model, (d) this might fail at initialization @time=0

Listing 4.4.1.2: Modeling memory 4.4.1.2 Modeling Combinational Logic

Modeling combinational is well done with concurrent statements that do not contain a feedback loop. Example for a 1-bit half adder: sum <= a xor b; carry_out <= a AND b; In many situations designers use a PROCESS statement of the form p_combinational:PROCESS(sensitive_signals) BEGIN driven_output_signals <= f(sensitive_signals, other_signals); END PROCESS p_combinational;

Page 76: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 76 -

The process generates (forbidden) latches, if one of the following two basic rules for combinational logic is violated:

1. All input signals of the process must be listed in its sensitivity list. 2. All output signals must be driven all time.

Violation example for rule 1: In the process below labeled p_partial_sensitivity_list the assignment y<=b; can be executed if and only if an event on signal a occurs. To realize that a double-edge triggered FF using signal a as clock signal is required, which is not combinational. p_partial_sensitivity_list:PROCESS(a) BEGIN Y <= b; -- latch generation: b is not in the sesitivity list! END PROCESS p_partial_sensitivity_list; Violation example for rule 2: In the process below labeled p_wrong the assignment next_y<=b; can be executed if and only if a='1'. When a='0' then next_y must not change. To guarantee this the synthesizer generates a latch, so that the code is no more purely combinational. This problem is removed in process p_good. Don’t forget that y has now to appear in the sensitivity list because it is an input signal. a) p_wrong:PROCESS(a,b)

BEGIN IF a='1' THEN next_y <= b; -- what happens if a='0'? END IF; END PROCESS p_wrong;

b) p_good:PROCESS(a,b,y) BEGIN IF a='1' THEN next_y <= b; ELSE next_y <= y; END IF; END PROCESS p_good;

4.4.1.3 Modeling NextState Logic

The NextState logic of a FSM is a combinational logic with inputs stimuli and state and output NextState. To hold the two rules above write signals state and all stimuli into the sensitivity list and start with NextState<=state to fulfill the two rules for avoiding latches. The following example does also contain an enable entry: Listing 4.4.1.3: NextState logic

P_NextStateLogic:PROCESS(state, simuli) IS BEGIN NextState <= state; IF enable='1' THEN ... END IF; END PROCESS p_NextStateLogic;

Page 77: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 77 -

4.4.1.4 Modeling Combined NextState-Logic and State-Memory

In the following example we have a counter with the typical FSM feedback loop made of two processes labeled p_NextStateLogic and p_StateMemory. The model of the combinational logic is blue, critical parts that are easily forgotten are red. LIBRARY ieee; USE ieee.std_logic_1164.ALL; ENTITY counter IS GENERIC(cPeriod:POSITIVE:=10); PORT(reset,clock,EnableIn:IN std_logic; EnableOut:BUFFER std_logic; count:BUFFER NATURAL RANGE 0 TO cPeriod-1 ); END ENTITY counter; --Architecture with 2 processes for the FSM feedback loop: ARCHITECTURE rtl_counter_fsm2 OF counter IS SIGNAL NextCount:NATURAL RANGE 0 TO cPeriod-1; BEGIN -- Begin NextState Logic: p_NextStateLogic:PROCESS(enable,count) BEGIN NextCount<=count; -- Begin NextState Logic IF EnableIn='1' THEN IF count = cPeriod-1 THEN NextCount<=0; ELSE NextCount<=count+1; END IF; END IF; -- End NextState Logic END PROCESS p_NextStateLogic; -- -- Begin State Memory p_StateMemory:PROCESS(reset,clock) BEGIN IF reset='0' THEN count <= 0; ELSIF clock'EVENT AND clock='1' THEN count <= NextCount; -- apply NextState Logic END IF; END PROCESS p_StateMemory; -- -- output logic: EnableOut <= '1' WHEN (count=cPeriod-1 AND EnableIn='1') ELSE '0'; END ARCHITECTURE rtl_counter_fsm2; To translate a FSM-loop with 2 processes into a FSM-loop with 1 process:

1. remove declaration of signal NextState, in the architecture’s declaration region, 2. take the process of the state memory and change its label to p_FSMloop, 3. replace statement state <= NextState by the next-state logic in the other process 4. delete the other process, 5. replace signal NextState, by signal state, 6. remove statement NextState<=state; if present, 7. no changes in output logic!

Page 78: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 78 -

To translate a FSM-loop with 1 process into a FSM-loop with 2 processes:

1. declare signal NextState with same data type as signal state, 2. copy the 1 process into 2 processes, label them p_NextStateLogic and p_StateMemory, 3. finish process p_StateMemory by replacing the next-state logic by "state<=NextState;" 4. copy the next-state logic into process p_NextStateLogic, 5. add "NextState<=state;" as fist executable statement in process p_NextStateLogic, 6. replace all strings "state<=" by "NextState<=", 7. no changes in output logic!

--Architecture with 1 process for the FSM feedback loop: ARCHITECTURE rtl_counter_fsm1 OF counter IS SIGNAL NextCount:NATURAL RANGE 0 TO cPeriod-1; BEGIN -- Counter p_fsm:PROCESS(reset,clock) BEGIN IF reset='0' THEN count <= 0; ELSIF clock'EVENT AND clock='1' THEN IF EnableIn='1' THEN -- Begin NextState Logic IF count = cPeriod-1 THEN count <= 0; ELSE count <= count+1; END IF; END IF; -- End NextState Logic END IF; END PROCESS p_fsm; -- -- output logic: EnableOut <= '1' WHEN (count=cPeriod-1 AND EnableIn='1') ELSE '0'; END ARCHITECTURE rtl_counter_fsm1; To do: Translate architectures in the ADAC system This chapter requires the configuration skills of chapter 4.3 In directory <>\adac\VHDL\ you will find the file counter.vhd witch contains architectures rtl_counter_bcd_safe binary coded decimal, safe treatment of forbidden states rtl_counter_bcd_cheap binary coded decimal, don’t care about forbidden states rtl_counter_fsm0 empty architecture rtl_counter_fsm1_dn FSM loop in 1 process, counting down rtl_counter_fsm2_up FSM loop in 1 processes, counting up Navigate ModelSim to <>\adac\ModelSim\testbenches\tb_counter\ and type do work.do into the transcript window. ModelSim should deliver the simulation shown in Fig. 4.2.1. Code new architectures rtl_counter_fsm1_up and rtl_counter_fsm2_dn. You can copy most code from the complete architectures.

Page 79: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 79 -

4.4.2 Applications

4.4.2.1 Time-Discrete Filter Structures

(a) Digital Filter in 1st canonical direct structure, ai, si and nsi (i=1...c) are bit-vectors.

z-1 z-1

ac

z-1

yi ,

Y(z)

ac-1 a3 a2 a1

z-1

xi , X(z)

ns1 s1nsc sc s3 s2ns2ns3s4

filter_canon1

(b) Digital Filter in 2nd canonical direct structure, ai, si and nsi (i=1...c) are bit-vectors.

z-1 z-1 z-1

a1

xi ,

X(z)

s1

a2

a3

s2 scns2 ns3 nsc

yi, Y(z)acz-1

s3ns1

filter_canon2

Fig. 4.4.2.1: FSM models with state and coefficient vectors. Table 4.4.2.1: Complete table with respect to filter structures

1st canonic direct structure 2nd canonic direct structure

state vector?

NextState vector?

Stimulus signals

Output signals Moore

Mealy

NextState logic

Output logic: Moore

Mealy:

Page 80: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 80 -

4.4.2.2 Sinc Filters

(a) filter in general representation, (b) sinc filter (rtl_SincSum) and (c) its impulse response.

Z-1 Z-1 Z-1

a1 a2 aK

Z-1 Z-1 Z-1

a

xin xin

yout

yout

(a) (b)

1 2 K

(c)

a0

0

(d): comb architecture of sinc filter (in our code rtl_SincComb).

z-1 z-1

xi ,

X(z)

s1 s2

sN+1

ns2 nsN

yi, Y(z)

z-1ns1

filter_comb

z-1sN

nsN+1 wa

Fig. 4.4.2.2: (a) general filter, (b), (d) different sinc filters, (c) sinc-filter impulse response. Fig. part(a) show a time discrete filter in ......... canonic direct structure. When all coefficients have the same value then it can be realized as a single multiplication in the output logic as shown in Part(b). This produces impulse responses as shown in part(c). filters with such an impulse response are called sinc filters. With a=aj=1 for any j no multiplications are required. Such filters are used for both, decimation (lowering the sampling rate) and interpolation (up-sampling). Copy the given folder directory adac to a local directory, navigate to ModelSim

testbenches tb_des_adac. Start ModelSim and navigate to File ModelSim testbenches tb_des_adac. Type command do work.do into the Transcript Window. You should see a graphics window as shown in Fig. 3.2. What is the value of UDAC1out

(blue line) at 1 ms? Note it accurately: .............................................................

Page 81: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 81 -

Hint: To get the curser to a desired time point t0 you can click in the left hand side of the graphics window on UADC1out close to t0. With keys Tab(ulator) and Shift+Tab we can move from event to event of that curve. Then click on the white label of u_c2 which was computed with very dense time points and move curses by tabulator to t0. Furthermore you can click zoom around cursor (see loupe button (+) with ruler) Navigate in the ModelSim simulator’s Workspace Window Files to open file sinc.vhd. You will find the following design units: ENTITY sinc ARCHITECTURE rtl_SincComb ARCHITECTURE rtl_SincSum_canon1_fsm1 ARCHITECTURE rtl_SincSum_canon1_fsm2 ARCHITECTURE rtl_SincSum_canon2_fsm1 ARCHITECTURE rtl_SincSum_canon2_fsm2 CONFIGURATION con_sinc Look into file SincDn.vhd, that uses the sinc-filters for decimation (down-sampling). Which of the 5 architectures for entity sinc is used by default? Explain why. .............................................................. .............................................................. .............................................................. Some of the 5 architectures within file sinc.vhd are complete. Grow the configuration tree in file cfg_de2_adac.vhd such, that you can test all 5 architectures in file sinc.vhd one after the other. Which of them are complete? (Verify it e.g. at UADC1out(t=2.5ms) that you have noted above). The actually configured architecture contains red line numbers in the debugger indicating “ready for setting breakpoints by double-click of left mouse button”). Which of the 5 architectures in sinc.vhd are not complete? .............................................................. Exercise: the two architectures that are not complete have to be completed by (a) translating a FSM-loop from 1 process to 2 processes and (b) translating a FSM-loop from 2 processes to 1 process. After doing so, do you get exactly the same for all architectures? ..............................................................

Page 82: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 82 -

4.4.2.3 Digital Filter of 1st Canonic Direct Structure

dwp

q

r

wpd

wpq

r

dwp

q

r

wp

reset

rtl_filter_canon1

nsK ns2 ns1sK s2

s1

pK p2p1

FFK FF2 FF1

clock

add2 add1

coefc

multc mult2 mult1

ncoef2 coef1

n n

m+nm+n m+n

FilterOut

cOutWidth

FilterIn m = cInWidth

enablee e e

d q

r

d q

r

reset

rtl_filter_canon2

ns1 ns2s1 s2

p1

FFK FF2

clock

add

coef1

mult1

multK

n

coef2 coefK

n

FilterOut

cOutWidth

FilterIn

cInWidth

enable

e e

coef2

mult2

n

d q

r

nsK sK

FFK

e

wp

cInWidth cInWidth

p2

pK

wp

wpcInWidth

Fig. 4.4.2.3: Digital filter in (a) 1st and (b) 2nd canonic direct structure. Fig. 4.4.2.3 gives a deeper insight into the digital filters shown in Fig. 4.4.2.1. You do not need a deep understanding of this filter structures for this exercise. Here, you only need to transform an FSM from 1-process loop to 2 process loop and vice versa.

Page 83: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 83 -

Navigate in the ModelSim simulator’s Workspace Window Files to open file filter.vhd. You will find the following design units: ENTITY filter ARCHITECTURE rtl_filter_canon1_fsm1 OF filter ARCHITECTURE rtl_filter_canon1_fsm2 OF filter ARCHITECTURE rtl_filter_canon2_fsm1 OF filter ARCHITECTURE rtl_filter_canon2_fsm2 OF filter CONFIGURATION con_filter Look into file dsdemod.vhd, that uses the filter after decimation with sinc filters. Which of the 5 architectures for entity filter is used by default? Explain why. .............................................................. .............................................................. .............................................................. Some of the 4 architectures within file filter.vhd are complete. Grow the configuration tree in file cfg_de2_adac.vhd such, that you can test all 4 architectures in file filter.vhd one after the other. Which of them are complete? (Verify it e.g. at UADC1out(t=2.5ms) that you have noted above). .............................................................. Exercise: the architectures in filter.vhd that are not complete have to be completed by (c) translating a FSM-loop from 1 process to 2 processes and (d) translating a FSM-loop from 2 processes to 1 process. Hint: This chapter requires the configuration skills of chapter 4.3 After doing so, do you get exactly the same for all architectures or approximately similar? ..............................................................

Page 84: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 84 -

4.5 Data and Libraries with VHDL This chapter points out some important issues of VHDL, it is no comprehensive tutorial. It is based on the author’s experience of frequently asked questions during circuit design courses with students having some previous knowledge on that topic. 4.5.1 Design Units

Table 4.5.1: Building blocks in VHDL

COMPONENT LIBRARY Comments To the outer world ENTITY PACKAGE Corresponds to a symbol Inner realization ARCITECTURE BPACKAGE BODY Corresponds to a schematics Combination CONFIGURATION 4.5.2 Compilation Order Dependence

VHDL is compilation order dependent. It has a loader, no linker. Sub-modules are loaded immediately when compiling the COMPONENT directive within an architecture. We can organize our VHDL code arbitrarily in different files, but components to be loaded must have been complied before respecting the following sequence: PACKAGE ENTITY ARCHITECTURE PACKAGE BODY The package body may be compiled any time after the package. This gives us the possibility to declare a constant in the package and assign its value in the package body. 4.5.3 Kinds of Code: Concurrent – Sequential – Structural

VHDL code can be written in three different modes: Concurrent is the default mode. In concurrent code the sequence of statements is irrelevant. “Structural” is using components. “Sequential” is within a PROCESS statement or subprograms, i.e. it is processed top-down. To make the sequence of concurrent statements irrelevant we need a delayed assignment. A signal is never assigned immediately but scheduled for the future. Therefore, zero delay is realized as simulation delta (Δ) which consumes no time in seconds. In the lower left corner of the ModelSim simulator we find timing specifications like “NOW: 3 ms Delta: 6”. Note that NOW is a VHDL function returning the actual simulation time of type TIME, e.g. 25 ns.

Page 85: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 85 -

4.5.4 Data

4.5.4.1 Data Objects

VHDL handles data by one of the following data objects: SIGNAL: interconnection wires VARIABLE: local storage of temporary data CONSTANT: named constant values Table 4.5.4.1 shows in which environment a data object may be declared and where it may be used, i.e. assigned or read. Signals represent wires and assign data after a delay. A process runs within one Δ a signal cannot get and read a value in the same run of a process. We overcome this problem by declaring variables in the declaration region of a process. They can be written and read in tow subsequent statement, like in C ode. Table 4.5.4.1: The three data objects and the environments where they may be declared and used.

data object environment to be declared in environment to be used in SIGNAL concurrent everywhere

VARIABLE sequential sequential CONSTANT everywhere everywhere

Objecs _______________________|_______________________ | | | SIGNAL VARIABLE CONSTANT Fig. 4.5.4.1: VHDL data objects. For driving a signal use "<=”. For assigning a value to a constant, a variable or for signal initialization use ":="-

Driving a signal several times in sequential code: last driver overrides previous

drivers. Driving a signal N>1 times in concurrent code: Multiply driven signal with N drivers,

data type with resolution function required, e.g. std_logic or std_logic_vector.

Page 86: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 86 -

4.5.4.2 Data Types

Data object have to be declared with a data type. Available are scalar the types INTEGER, REAL, enumerated and BIT and the composite data types such ARRAY and RECORD. Scheme of data type declaration statements: TYPE type_name IS type_mark; SUBTYPE subtype_name IS <range_specification> OF type_name;

Examples for type and subtype declarations: TYPE BOOLEAN IS (false,true); SUBTYPE t_address IS RANGE 0 TO 15 OF INTEGER; SUBTYPE NATURAL IS RANGE 0 TO INTEGER'HIGH OF INTEGER; SUBTYPE POSITIVE IS RANGE 1 TO INTEGER'HIGH OF INTEGER; Types | _____________________|_______________________ | | | | Access Scalar File Composite | | _____________|_____________ ___|___ | | | | | | Integer Real Physical Enumerated Array Record Fig. 4.5.4.2: VHDL data types. The assignment of a value to a data object is guarded such, that only values of the same data type or a subtype can be assigned to a data object. The user can specifiy own data types. See e.g. [18]-[22] for more details. Types like BOOLEAN, BIT or std_logic is an enumerated types., where std_ulogic is unresolved and can have one driver only, while std_logic is the resolved subtype of std_ulogic and can have several drivers, so it can be used as bus line. In some cases a distinction between signed and unsigned is necessary: An unsigned number keeps constant when we add an arbitrary number of zeros: 101 = 00101. A signed number keeps constant when we add an arbitrary number of signs bits: 101 = 11101. Any number keeps constant if we add fractional trailing zeros: 101.1 = 101.100, 11=11.000. Exercise: add the following numbers after filling preceding and trailing bits:

Given numbers Unsigned treatment Signed treatment 11011011.11011 101.11101101

11011011.11011 101.11101101

11011011.11011 101.11101101

Page 87: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 87 -

4.5.5 Libraries and Packages

4.5.5.1 Using Existing Libraries and Packages

Use existing code if possible. It is typically organized in libraries which are composed of packages. A typical library retrieval is (1) LIBRARY ieee; (2) USE ieee.std_logic_1164.ALL; (3) USE ieee.std_logic_unsigned."+"; (4) USE ieee.std_logic_signed.CONV_INTEGER; (5) USE ieee.std_logic_arith.CONV_STD_LOGIC_VECTOR; (6) LIBRARY adac_lib; (7) USE adac_lib.pk_adac.ALL; (8) USE work.pk_filter.ALL; (9) ... (10) SIGNAL N:INTEGER; (11) SIGNAL bitvec1,bitvec2:std_logic_vector(15 DOWNTO 0); (12) ... (13) N <= CONV_INTEGER('0'&bitvec1) (14) vec2 <= CONV_STD_LOGIC_VECTOR(N,bitvec2'LENGTH) The code above has the following meanings: Line (1): "Retrieve library with name ieee". Line (2): Use ALL from package std_logic_1164 found within library ieee. Line (3): Use only the declaration of the "+" operator found in package std_logic_unsigned

within library ieee. Applied on bit-vectors as operands it will be synthesized as arithmetic summation and the most significant bit will not be interpreted as sign bit. (To treat the first bit as sign bit use the "+" operator from package std_logic_signed.)

Line (4): "Retrieve library with name adac_lib". As it is not a standard library it must be introduced to the tool, the respective commands are tool dependent.

Line (5): Make function CONV_INTEGER from package std_logic_signed available. Line (5): Make function CON_STD_LOGIC_VECTOR from package std_logic_arith

available. Line (7): Use ALL declarations from package pk_adac found within library adac_lib. Line (8): Use ALL declarations from package pk_filter found within library work. The

working library work needs no LIBRARY statement, at is always linked. Line (10): Declaration of signal N with data type INTEGER, somewhere in the declarations

region of an architecture.. Line (11): Declaration of signals bitvec1, bitvec2 with data type std_logic_vector,

somewhere in the declarations region of an architecture. Line (13): Converting bitvec1 to integral number N. the concerted preceding '0' before

bitvec1 make the result always positive. Line (14): Converting integral number N to bitvec2.

Page 88: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 88 -

If the LIBRARY / USE statements are written above ... an ENTITY, then they are valid for this entity and its architectures, an ARCHITECTURE, then they are valid for this architecture, a PACKAGE, then they are valid for this package and its package body, a PACKAGE BODY, then they are valid for this PACKAGE BODY.

Exercise: Rename library adac_bin to a self-created name and make the system run again. 4.5.5.2 Creating an Own Package

Package and package body are like entity and architecture. Packages may contain non-executable declarations only while package bodies may contain executable code also. Declarations made within a package are available whenever loading this package. Declarations made in a package body are known only in this package body below the declaration. Listing 4.2 shows Tcl-commands to create a library and symbol for it that can be used within the VHDL code when working with the ModelSim simulator. LIBRARY ieee; USE ieee.std_logic_1164.ALL; PACKAGE pk_example IS -- Declaration of an externally visible constant: CONSTANT cExtern:INTEGER:=10; -- -- gate delay as "deferred" constant: no value assigned: CONSTANT delay:TIME; -- -- multiplexer: interface declaration only, no executable code: FUNCTION mux(sel:INTEGER;vec:std_logic_vector) RETURN std_logic; -- SIGNAL big_array:std_logic_vector(1 TO 40_000); END PACKAGE pk_example; PACKAGE BODY pk_example IS -- Declaration of an only internally visible constant: CONSTANT cIntern:INTEGER:=20; -- -- here the deferred constant has to get its value: CONSTANT delay:TIME:=2 ns; -- -- here the function mux has to get its body: FUNCTION mux(sel:INTEGER;vec:std_logic_vector) RETURN std_logic IS BEGIN RETURN vec(sel); END FUNCTION mux; END PACKAGE BODY pk_example; The package named pk_example above declares the constant cExtern. It will be available in the package body and everywhere where this package is declared. This is different from the constant cIntern declared within the package body below. It will be known only within this package body and below its declaration.

Page 89: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 89 -

The constant delay is a so-called deferred constant, as no value is assigned to it in the package. The assignment is deferred (Latin: “carried away”) into the package body. As the package body may be compiled as last design unit, different delays (e.g. for fast, typical, slow parameters) can be passed to the design by compiling nothing else than the package body. The external interface of the multiplexer function mux is declared in the package. In the package body function mux gets its executable body. If the declaration in the package is omitted, this function will be known only in the package body and after its declaration. Signal big_array will be declared in any design unit where package pk_example is declared. It will be different signals which are independent from each other in any of those design units. 4.5.6 Arrays for State-Machine Design

z-1 z-1 z-1

a1

xi ,

X(z)

s1

a2

a3

s2 scns2 ns3 nsc

yi, Y(z)acz-1

s3ns1

filter_canon2

(a) Digital Filter in 2nd canonical direct structure, ai, si and nsi (i=1...c) are bit-vectors.

t_state

t_state :

t_StateVector :

t_coef :

t_CoefVector :

t_coef

(b) Data structures to realize the vectors of coefficients (ai) and data words (si, nsi).

Fig. 4.5.6: (a) A model that requires a vector of bit-vectors and (b) a VHDL realization.

Page 90: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 90 -

Fig. 4.5.6(a) illustrates a digital filter that requires vectors of bit-vectors. Fig. 4.5.6 (b) and listing 4.5.6 realize a single coefficient ai alias CoefVector(i) as bit-vector of type t_coef. All coefficients are summarized in the constant CoefVector of type t_CoefVector. A single state or next-state is realized as bit-vector of data type t_state. A vector of such signals, e.g. named state or NextState, can be declared as signal of type t_StateVector. In the following code... Constant cXxWidth is the count of bits of signal xx, Constant cXxFract is the count of fractional bits of signal xx. Example: The string "01.101" has a bit-width of 5 bits, 3 of them fractional. Listing 4.5.6 (a): The package pk_filter. (Note: Some synthesizers cannot assign the values of "deferred constant" CoefVector in the package body. In this case remove the package body and assign the values in the package. Doing so you loose the capability of changing filter coefficients by recompiling the package bode only, you have to recompile the entire design.)

(1) ---------------------------------------------------------------------- (2) -- Module : pk_filter (3) -- Designer : Martin Schubert (4) -- Date last modified: 07.03.2011 (5) -- Purpose : Data Structures for Digital FIR Filter (6) ---------------------------------------------------------------------- (7) LIBRARY ieee; USE ieee.std_logic_1164.ALL; (8) PACKAGE pk_filter IS (9) CONSTANT cDataInWidth:POSITIVE:=18; -- Input-Data BitWidth (10) CONSTANT cDataInFract:POSITIVE:=16; -- No of Input-Data fract. Bits (11) CONSTANT cDataOutWidth:POSITIVE:=18; -- Output-Data BitWidth (12) CONSTANT cDataOutFract:POSITIVE:=16; -- No of Output-Data fract Bits (13) CONSTANT cCoefWidth:POSITIVE:=18; -- Coefficient's BitWidth (14) CONSTANT cCoefFract:POSITIVE:=18; -- No of Coef's fractional Bits (15) SUBTYPE t_DataIn IS std_logic_vector(cDataInWidth-1 DOWNTO 0); (16) SUBTYPE t_DataOut IS std_logic_vector(cDataOutWidth-1 DOWNTO 0); (17) SUBTYPE t_coef IS std_logic_vector(cCoefWidth-1 DOWNTO 0); (18) TYPE t_CoefVector IS ARRAY(NATURAL RANGE <>) OF t_coef; (19) CONSTANT cTaps:POSITIVE:=33; (20) CONSTANT CoefVector: t_CoefVector(1 TO cTaps); (21) END PACKAGE pk_filter; Listing 4.5.6 (b): The package body pk_filter.

(22) PACKAGE BODY pk_filter IS (23) CONSTANT CoefVector: t_CoefVector(1 TO cTaps) (24) := (OTHERS=>(cCoefWidth-6=>'1',OTHERS=>'0')); (25) END PACKAGE BODY pk_filter; A data type hands down his properties to a subtype. For example operators "+", "-", "*", etc., available in library ieee for data type std_logic_vector are available for t_coef by SUBTYPE t_coef IS std_logic_vector(cCoefWidth-1 DOWNTO 0); They are not available for vectors of type t_coef when we create a net data type writing TYPE t_coef IS std_logic_vector(cCoefWidth-1 DOWNTO 0);

4.5.7 Exercise: (=16P)

Complete package pk_filter in listing 4.5.7 doing the following:

Page 91: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 91 -

Make sure that data types std_logic and std_logic_vector can be used according to library ieee.std_logic_1164. (2P) Complete line (10) such, that data type t_DataIn declares a vector representing a number with cDataInWidth bits of type std_logic . (1P) Complete line (11) such, that data type t_coef declares a vector representing a number with cCoefWidth bits of type std_logic . (1P) Complete line (12) such, that data type t_CoefVector declares a vector with elements type t_coef . The index range of this vector can be defined later with natural numbers. (2P) No value is assigned to the constant in line (14). Where does this constant gets its value and what is the correct denomination of such a constant? (2P) .................................................................. What do you write over an Entity to make all declarations in Package pk_filter, which is located in logical library adac_lib, available? (2P) .................................................................. Listing 4.5.7: Package pk_filter.

(1) ....................................................................

(2) ....................................................................

(3) PACKAGE pk_filter IS

(4) CONSTANT cDataInWidth:POSITIVE:=8; -- Input-Data BitWidth

(5) CONSTANT cDataInFract:POSITIVE:=6; -- No of Input-Data fract. Bits

(6) CONSTANT cDataOutWidth:POSITIVE:=18; -- Output-Data BitWidth

(7) CONSTANT cDataOutFract:POSITIVE:=16; -- No of Output-Data fract Bits

(8) CONSTANT cCoefWidth:POSITIVE:=18; -- Coefficient's BitWidth

(9) CONSTANT cCoefFract:POSITIVE:=18; -- No of Coef's fractional Bits

(10) ...TYPE t_DataIn IS .............................................

(11) ...TYPE t_coef IS .............................................

(12) ...TYPE t_CoefVector IS ..........................................

(13) CONSTANT cTaps:POSITIVE:=33;

(14) CONSTANT CoefVector: t_CoefVector(1 TO cTaps);

(15) END PACKAGE pk_filter;

Page 92: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 92 -

Write a library statement at (16), that allows for the multiplication of numbers in the std_logic_vector-format using '*' (while library is known). (1P) Line (17): Declaration of type t_product as function of constants such, that a signal of that type matches the product of t_DataIn and t_coef type signals. (1P) Line (18): declaration of signal product such, that we can write the VHDL command: "product<=DataIn*CoefVector(i);" (2P) Lines (20) and (21): Complete the declarations of iPl und iPh such, that (22) works respecting the vector lengths and the number of fractional bits using the respective named constants in package pk_filter. (For the computation of iPl, iPh see document “FSM Design for DSP Using Fixed-Point Numbers” [23]). (2P)

(16) ....................................................................

(17) ....................................................................

(18) ....................................................................

(19) SIGNAL DataOut:t_DataOut;

(20) CONSTANT iPl: ......................................................

(21) CONSTANT iPh: ......................................................

(22) DataOut <= product(iPh DOWNTO iPl);

Page 93: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 93 -

4.5.8 Conversion between Integer std_logic_vector

Consider the following code, particularly the bold lines: Listing 4.5.8

LIBRARY ieee; USE ieee.std_logic_1164; USE ieee.std_logic_signed.conv_integer; USE ieee.std_logic_arith.conv_std_logic_vector; ARCHITECTURE rtl_de2_engen OF de2_engen IS SIGNAL ledg:std_logic_vector(7 DOWNTO 0); SIGNAL selDigit:NATURAL RANGE 0 TO 7; SUBTYPE t_digit IS NATURAL RANGE 0 TO 16; -- 16 is dark TYPE t_digits IS ARRAY(NATURAL RANGE <>) OF t_digit; BEGIN selDigit <= conv_integer('0'&sw(7 DOWNTO 5)); ledg(7 DOWNTO 4) <= conv_std_logic_vector(CountOut(selDigit),4); END ARCHITECTURE rtl_de2_engen; 4.5.9 Program to Generate Filter Coefficients

In subdirectory Filter_Coefficients you will find the executable filter_coefficients.exe. It is made by the author from (lost) C code. Double double-click left mouse button on this exe-program and you will be asked to 1. Type one of the letters , 'L', 'B', 'H' to get the filter coefficients of a low. Band- or high-

pass, respectively. 2. Pass-band amplitude, a real number which is typically 1.

Page 94: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 94 -

5 Signal Conditioning 5.1 Goals and Notation

5.1.1 Goals

xmin

xmax

time

x

xmin

xmax

time

x

(a) (b)

Fig. 5.1.1: Effects of signal conditioning on quantization: (a) bad, (b) good. Signal conditioning manipulates signals to take best advantage of measurement equipment. This is typically done by amplification and offset shift as illustrated in Fig. 5.1.1. It may also include conversion of single-ended into differential signals or vice versa or filtering to distinguish harmonics. The goal of signal conditioning is to use the complete available signal range (5.11) without exceeding it. (5.12) 5.1.2 Notation

In this chapter we will use small letters for time-domain signals and capital letters for frequency domain signals: X(f) = F{x(t)} x(t) = F-1{X(f)} (5.2) where F{ } and F-1{ } stand for Fourier and its reverse transformation, respectively, as well as for its derivatives, Laplace and z transformation. Transfer characteristics (dt. Übertragungskennlinie): input-output curve y=f(x). Transfer function (dt. Übertagungsfunktion): spectral I/O Bode curve H(f) = Y(f)/X(f). This chapter deals with transfer characteristics. Characteristic data is noted as cx characteristic input data points, in formulae we use xi = cx(i). cy characteristic output data points, in formulae we use yi = cy(i). cc coefficients of characteristic polynomial, in formulae we use ck = cc(k+1). NoC Number of Characteristics, = Number of Points (xi,yi) = Number of Coefficients ck. cxy composed data structure: cxy=[cx cy] or cxy=[cx cy cc].

Page 95: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 95 -

5.2 Linear Transfer Functions

x1

x2

time

x

(a)

y1

y2

y

(b)

x1 x2

y1

y2

y

(c)

x

x

y

Fig.5.2: Linear signal translation from (a) range x1 - x2 to (b) range y1 - y2, (c) plotting y(x). A linear transformation from mathematical point of view can be written as y = cy0 + cy1 x (5.21) with constants cy0 and cy1. In Fig. 5.2(c) we see that a y(x) plot must deliver a straight line. A linear characteristics according to (5.21) is unequivocally defined by two points (x1,y1) and (x2,y2) leading to the linear equation system. y1 = cy0 + cy1 x1 (5.22) y2 = cy0 + cy1 x2 Computing constants cy0 and cy1. For a linear function y(x) we may write

12

1

12

1

xx

xx

yy

yy

(5.23)

which can be used back and forth and is nicely symmetric:

1112

12 )( yxxxx

yyy

This equation can be written as

xxx

yyx

xx

yyyy

12

121

12

121 (5.24)

Writing xccy yy 10 delivers amplification and offset, respectively, as

12

121 xx

yycy

(5.25)

1110 xcyc yy . (5.26)

Page 96: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 96 -

Computing the constants cx0 and cx1. As (5.23) is symmetrica in x and y, we can use the same procedurce to compute x(y):

1112

12 )( xyyyy

xxx

yyy

xxy

yy

xxxx

12

121

12

121 (5.27)

Writing yccx xx 10 delivers amplification and offset, respectively, as

12

121 xx

yycx

(5.28)

1110 xcyc xx . (5.29)

Page 97: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 97 -

5.3 Higher Order Polynomial Transfer Function

5.3.1 Model

In the non-linear case we add non-zero coefficients ci with i2. Respecting the nonlinear coefficients c2 and c3 yields y = c0 + c1 x + c2 x2 + c3 x3 (5.31) This is done with Matlab function y = f_PolyEval(x,cc) in listing 5.5.4. As Matlab vectors begin with index 1, we have coefficient ci=cc(i+1), i=0...NoC-1. 5.3.2 Mathematics

NoC coefficients require NoC data points (xi,yi), i=1,2,...NoC, to be determined. In our example NoC=4 data points lead to the 4 equations

343

2434104

333

2333103

323

2232102

313

2131101

xcxcxccy

xcxcxccy

xcxcxccy

xcxcxccy

(5.32)

Vectors cx, cy, cc of length NoC and matrix A of dimension NoC x NoC deliver for NoC=4

4

3

2

1

x

x

x

x

xv ,

4

3

2

1

y

y

y

y

yv ,

3

2

1

0

c

c

c

c

cv ,

34

244

33

233

32

222

31

211

1

1

1

1

xxx

xxx

xxx

xxx

A , (5.33)

With this notation we can write (5.16) as cy = A cc (5.34) and compute the coefficient vector as done by function cc = f_PolyInit(cx,cy) in listing 5.5.4: cc= A-1 cy (5.35) As Matlab vectors begin with index 1, we have ci=cc(i+1), i=0...NoC-1. The equation system (5.16) has no solution if determinant det(A) = 0. (5.36) This happens if xi=xj for i≠j. In case of (xi,yi) = (xj,yj) the information is redundant, for xi=xj and yi≠yj the information is contradictory, which may happen in systems with hysteresis. Higher order polynomials tend to oscillate. This effects can be avoided by other interpolation techniques, e.g. cubic splines.

Page 98: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 98 -

5.4 Clipping

5.4.1 Clipping the Input Waveform

Fig. 5.4.1: Why we need input clipping: Non-linear characteristics y(x) delivers an ye in the valid range of y while xe is outside the valid range of x.

xmin xmax

ymin

ymax

y

xxe

ye

Realistic modeling requires clipping. A 3V technology typically cannot deliver output signals >3V. The author recommends clipping of input signal x as non-linearity might deliver ye(xe) with ymin ye ymax for xe far outside the valid range of x. In Matlab we use xmax = max(cx), (5.41) xmin = min(cx), (5.42) ymax = max(cy), (5.43) ymin = min(cy), (5.44) with cx(1...NoC) and cy(1...NoC) being points (xi,yi), i=1...NoC defining the transfer characteristics. Performing clipping with 4 code lines we may write xmax = max(cx); % maximum x-coordinate xmin = min(cx); % minimum x-coordinate xclp = min(xmax,x) % clipping to upper limit xmax xclp = max(xmin,xclp); % clipping to lower limit xmin Function f_characteristics in listing 5.5.3 performs this clipping of x within one line of Matlab code: xclp = max(min(cx),min(max(cx),x)); % clip input x to range xmin, xmax 5.4.2 Clipping the Output Waveform

Fig.5.4.2: Why we need output clipping: y(x) in valid range xmin < x < xc delivers invalid y < ymin.

xminxmax

ymin

ymax

y

x

As illustrated in Fig. 5.4.2. polynomials with more than2 coefficients (i.e. more than 2 points defining the transfer characteristics) require clipping of y(xclp) also. Function f_characteristics in listing 5.5.3 performs this clipping of y within one line of Matlab code: y = max(min(cy),min(max(cy),yunclp)); % clip output y to range ymin, ymax

Page 99: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 99 -

5.5 Matlab Models Copy directory MSlib that you get from your supervisor1 to C:\MSlib\Mlib. Within Matlab command window type addpath('C:\Mslib\Mlib'); % adds folder to top of Matlab search path The effect of this command is, that all files and functions available in directory C:\Mslib\Mlib will now be available as if they were in your actual working directory. Listing 5.5: Some helpful Matlab commands

addpath(folderName1,..,FoldernameN); % adds folders to top of search path addpath('..\functions'); % adds neighb. dir functions to path mydir = pwd % writes directory on string mydir dir | ls % both commands list directories cd {<dir_name> | ..} % change directory: <dir_name> | ..

1 URL: https://hps.hs-regensburg.de/scm39115/homepage/education/courses/courses.htm Common Stuff MSlib.zip.

Page 100: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 100 -

5.5.1 Testbench

5.5.1.1 Source Code, Example Plot and Structural Diagram

Testbench tb_characteristics in listing 5.5.1 specifies the input parameters to function f_characteristics. It plots a transfer characteristics y(x) which is defined by vectors cx, cy as illustrated in Fig. 5.5.1

Fig. 5.5.1: Result of running testbench tb_characteristics, with ylinear=c0+c1x, top left: y(xclp(x)) with xclp=clipped(x), top right: err = y(x) – ylinear(x) mid left: y(t) = xclp(x(t)), no clipping here, mid right: err = y(x(t)) – ylinear(x(t)) low left: |YdB|=20dBlog10(|fft(y)|), low right: ErrdB = 20dBlog10(|fft(err)|).

Input parameters to be specified: Characteristic I/O curve parameters cx: characteristic input data points, vectors of length NoC (Number of Characteristics). cy: characteristic output data points, vectors of length NoC. NoC computed from length(cx), Number of Points of characteristics vectors cx, cy, cc.

Page 101: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 101 -

Time and frequency domain parameters NoW Number of Waves of test signal on time axis. Ats default=1: Amplitude of test-signal. Ots default=0: Offset of test-signal. ldNoS integer: Number of Samples on both time and frequency axis NoS Number of Samples on time and frequency axis, computed from round(2ldNoS), ldNoS

should be an integer Quantization Base base of number system: 10 for decimal, 2 for binary, 8 for octal, etc. NoMSP Number of Most Significant Places. E.g. 3 delivers 3.14 from . No quantization when Base=0 and/or NoMSP=0. Concluded parameters:

cc vector of length NoC, computed such that

1

0

NoC

k

kiki xcy with ck=cc(k+1).

Fts real: = NoS/NoW: relative frequency of test-signal.

xts test signal computed from: xts=Ats*sin(2Ftst) + Ots, vector of length NoS.

xclp = xts clipped to min(cy) xclp max(cy), visible only if different from xts.

yunclp

NoC

k

kclpk xc

1

1 : output signal computed from xclp, visible only if different from y.

y real: computed from yunclp by clipping to clipped to min(cy) y max(cy). The self-made functions involved are listed in the structural diagram 5.5.1. Be sure to have the listed functions in your working directory. Structural diagram 5.5.1:

tb_characteristics % testbech: key input parameters, compute graphics f_char % defining transfer characteristics f_PolyInit % compute coefficints cc() of interpolation polynomial f_PolyEval % evaluate polynomial y(x) for given cc f_delta % determinate quantization delta f_quantize % qantize given numbers f_rms % compue rms value of a signal f_dB % translating an amplitude amplification in dB f_fft % compute fft of a signal, result scaled to amplitudes f_fftdB % compute f_fft of a signal and translate it in dB f_index % find index of particular vector element (max,min...)

Page 102: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 102 -

Listing 5.5.1: Matlab code of testbench tb_characteristics.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Testbench: tb_characteristics % Purpose: Testbench for f_characteristics: transfer characteristics % Author: Martin Schubert % Date last modified: 30. May 2017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% addpath('..\..\Mlib\functions'); % % Specifications % ============== % specify transfer characteristics clear all; %cx = [-1.0 1.0]'; cy = [sqrt(2) -sqrt(2)]'; cx = [-1 1 0.0]'; cy = [+1 -1 0e-4]'*sqrt(2); %cx = [-1:0.2:1]'; cy = -0.4 + 0.1*cx + 0.2*cx.^2 + 0.3*cx.^3 + 0.4*cx.^4; % % specify test signal ldNoS = 12; % logarithm dualis of NoS NoS = 2^round(ldNoS); % Number of time-samples of test signal NoW = 47; % Number of Waves on time axis Ats = 1.00; Ots=0.00; % Amplitude and Offset of test signal dataWindow = 'bhar' % window function for sinusoidal test function NoFFC = 101; % Number of FIR Filter Coefficients Fg = 0.5; % FIR filter cut-off frequency. allpass if 0.5 filtWindow = 'cheb80'; % window function for filter design % % Quantization; round to NoMSP Most Significant Places of given Base NoB = 12; % Number of Bits = Bitwidth of data after quantization dsmorder = 0; % order of Delat-Sigma modulator, if 0: quantizer only % The latest version of tb_characteristics is found in \Mslib\Mlib\testbenches\. For this chapter turn off quantization by setting Base=0 and/or NoMSP=0.

Page 103: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 103 -

5.5.1.2 Polynomial Transfer Characteristics Specification

The transfer characteristics visualized in the top subplot is specified by two vectors cx, and cy of length NoC (Number of Points), with requirement NoC>1. From these points function f_PolyInit computes vector cc(1...NoC) such, that function f_PolyEval can compute

1

0

NoC

k

kiki xcy , (5.51)

whereas xi=cx(i), yi=cy(i) and ck=cc(k+1), as Matlab vectors always begin with index 1. In Fig 5.5.1 the characteristic polynomial was defined as cx = [-1.0 1.0]; cy = [sqrt(2) -sqrt(2)]; These two points are indicated as blue circles in the upper plot. The respective coefficients will be printed n the command window: y(x): transfer charcteristics: 1. order polynomial: c0=0, c1=-1.42421 Exercise: Observe computation of cc(k) as function of cx(i), cy(i), i,k=1...NoC Modify the vectors of characteristics input points to cx = [-1.0 1.0]'; cy = sqrt(2)*[ +1 -1]'; You will now see 3 blue circles in upper subplot of Fig. 5.5.1. Complete the printout that you see for the coefficients printed in the command window: y(x): transfer charcteristics: 2 . order polynomial: .... c0 = 0 , c1 = -1.41421 , c2 = 0 ............. ............. .............

The medium subplot in Fig. 5.5.1 shows one period of input x as black sinusoidal wave over time axis computed from. xts=Ats*sin(2Fts) + Ots . and y(x(t)) as blue wave computed from (5.51). The bottom subplots shows the respective Fourier transformed (FFT) |Y(F)| with F=0-0.5 being the relative frequency f/fs with sampling frequency fs. The left lower subplot has a linear axis while the right lower corner has an ordinate scaled in dB with respect. An amplitude of 1 in the time-domain appears as |Y(F)|=1 or 0dB in the frequency domain.

Page 104: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 104 -

Defining the Input/Output Limits by Clipping The points (cx(i),cy(i)), i=1...NoC, are also defining the range of input signal x and output signal y. They will be clipped such by function f_characteristics, that xmin xclp xmax yunclp = f(xclp) ymin yunclp ymax with xmin = min(cx); xmay=max(cx); ymin=min(cy); ymax=max(cy); Exercise: Observe input clipping of x(t) according to Fig. 5.4.1 Use cx=[-1.0 1.0 0.0]'; cy=sqrt(2)*[ +1 -1 0 ]'; Ats=1; Ots=0; NoW=23; to obtain a plot like Fig 5.5.1. Then increase the test-signal amplitude to Ats=1.02. What is the main graphical difference that you observe after augmentation of Ats by 2%? ............................................................... Increase the input signal’s amplitude to Ats=1.2. You will now see clipping effects in the medium subplot. A red line xclp appears as clipped part of x. Also the blue curve y(t) shows some non-linear flattening. Does this occur by clipping y(t) or is it the result of input clipping? ............................................................... Exercise: Observe output clipping of y(t) according to Fig. 5.4.2 Use again cx=[-1.0 1.0 0.0]'; cy=sqrt(2)*[ +1 -1 0 ]'; Ats=1; Ots=0; NoW=23; Now modify cy(3) according to Fig. 5.4.2 to cx=[-1.0 1.0 0.0]'; cy=sqrt(2)*[ +1 -1 -1]'; Ats=1; Ots=0; NoW=23;

Observe the upper and medium subplots showing y(x) and y(t)=f(x(t)), respectively. In the medium subplot the red curve xclp(t) should be invisible as covered by x, but unclipped yunclp(t) should have deviations from y(t). Do we have clipping of x(t) and/or y(t) in this case? ...............................................................

Page 105: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 105 -

Using Higher Order Polynomials Use points cx = [-1:0.2:1]'; cy = -0.4 + 0.1*cx + 0.2*cx.^2 + 0.3*cx.^3 + 0.4*cx.^4; to define the transfer characteristics. Here, c0=-0.4, ck=0.k for k=1...4 and ck=0 otherwise. You’ll have to find these coefficients in your printout, with some round-off noise on the coefficients c5...c9. Explain and test which harmonics occur for cx=[-1:0.2:1]'; cy=cx.^2; % hint: sin2(x)=½(1-cos(2x)) ............................................................... Explain and test which harmonics occur for cx=[-1:0.2:1]'; cy=cx.^4; % hint: sin4(x) = 0.375 – 0.5cos(2x) + 0.125cos(4x) ............................................................... Modify point the cy(3) such, that you see clipping at the top peak of output curve y(t) without clipping of input wave x(t) in the medium subplot. Look at Fig. 5.4.2 to understand the background. There is an infinite number of possibilities. cx=[-1.0 1.0 0.0]'; cy=[1.6 -1.6 ]'; Ats=1; Ots=0; NoW=23; ........

Using Very-High-Order Interpolation Polynomials Let’s assume you obtained the characteristics from a measurement with many points, e.g. NoC=1024 points as output of a 10bit DAC. This will result in a 1023rd order polynomial with NoC=1024 coefficients. Only the 1st 10 of them will be printed in your command window. The required numerical effort to compute NoC coefficients from a number of NoC data points requires Matlab to solve an equation system with NoC equations, i.e. invert a NoC x NoC matrix. The numerical effort rises quadratic with the matrix dimensions and higher order polynomials tend to oscillate when used for interpolation. Therefore, it is recommended to use other interpolation schemes like cubic splines for high resolution characteristic curves. Try to use 1001 data points: cx = [-1:0.002:1]'; cy = -0.4 + 0.1*cx + 0.2*cx.^2 + 0.3*cx.^3 + 0.4*cx.^4;

Page 106: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 106 -

5.5.1.3 Time-Domain Modeling

Time-Domain modeling is visualized in the medium subplot. Go back to the linear case of cx = [-1.0 1.0]'; cy = [1.6 -1.6]'; Ats=1; Ots=0; NoW=23; You should see Fig. 5.5.1 again. In the bottom right subplot showing the Fourier transformed of y(t) in dB computed from YdB=20dBlog10(|fft(y(t))| in dB We see some noise at some –320dB. This is the round-off error of your double-precision floating point numbers. What is the absolute value of –320dB in relation to Ats=1? ............................................................... The fast Fourier transform (FFT) requires 2M points with M being an integral number. In Fig. 5.5.1 we use M=10, i.e. a time axis length of NoS = 2M = 210 = 1024 M = ld(NoS) If M=ld(NoS) is not an integral number we have either to use the slower digital Fourier transform (DFT) or increase the time axis length with clever boundary conditions. Whatever is implemented in Matlab, try to use NoS=1050. Does it have a significant impact on the accuracy of the result? ............................................................... 5.5.1.4 Frequency-Domain Modeling

The FFT illustrated in the lower subplots assumes an infinite periodic continuation of the transformed time window. Therefore, the phase at the left end and of the transformation window must be equal to the phase at its right end. Otherwise we must try to ameliorate the situation with so-called window functions. Go back to the linear case of cx = [-1.0 1.0]'; cy = [1.6 -1.6]'; Ats=1; Ots=0; NoW=23; NoW is the Number of Waves that fit onto the time axis. The wavelength Lts in clock cycles of the test-signal as shown in the subplot of Fig. 5.1.1 is consequently ............................................................... The relative test-signal Frequency Fts of the 1st harmonic in the FFT is Fts=1/Lts or ...............................................................

Page 107: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 107 -

as can be seen from the print out in the command window. Do not choose wavelengths that are an integral number of clock cycles (i.e. NoS/NoW is integer) to avoid pattern noise (i.e. all situations are exactly repeated after a wavelength). Exercise Modify the number of waves fitting into the abscissa of the FFT from NoW=23 to 23.01. in which subplot do you observe a significant impact? Why? ............................................................... Find other values of NoW than 23. What is the rule to obtain an excellent FFT result showing the 1st harmonic at 0dB and all the rest below -300dB? ............................................................... FFT Consideration The kth harmonic of the signal is found on relative frequency Fk, with k=0...NoS-1. NoS is the time-axis length. As FT translates N time-points to N frequency points, NoS is also the length of the frequency vector. Relative frequencies F can be computed as F=[0:NoS-1]/NoS; % rel. frequencies, same number of points as time axis Real-world frequencies are computed from f=Ffs with sampling frequency fs. According to periodicity we know Y(F) over the complete infinite frequency axis, when we know it in the range F=0...½. This is because |Y(F)|=|Y(-F)| and |Y(F)|=|Y(mF)| with integral m. The consequence is that |Y(F)|=|Y(1-F)|, which is Matlab’s FFT result. Consequently, if you are looking for the difference between |Y(Fts)| and other frequencies, be aware that you will find |Y(1-Fts)|=|Y(Fts)|. Solution: Investigate |Y(Fts)| in range F=0...½ only. Observe |Y(F(k))| by as vector Y(k) in range 0 Fk ½, corresponding to 0 k ½NoS. Y(k=0) is the DC value, the sum of all taps on y(t). Y(k=1) is the intensity of the wave, that fits exactly 1 x into the complete time axis interval. Y(k=m) is the intensity of the wave, that fits exactly m x into the complete time axis interval. As out test signal is designed to fit NoW times into the time axis interval, it is located at Y(k=NoW). Its mth harmonics are found at Y(k=mNoW). Be careful to keep k ½NoS. As if this was not enough to consider, we have to keep in mind that Matlab vectors will always begin with index 1. Consequently, in Matlab notation, you will find Y(k=mNoW) on Yk = Y(k+1); % add 1 as Matlab indices begin at 1, not at 0

Page 108: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 108 -

5.5.2 Matlab Model of Transfer Characteristics Function f_char

Listing 5.5.2: Matlab code performing clipping using Matlab functions min( ) and max( ).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Module: f_char: compute transfer characteristics % Purpose: Signal Conditining with Input and Output Clipping % Inputs: % cxy(:,1) x-vector defining I/O characteristics: len(cx)>1 required % cxy(:,2) y-vector defining I/O characteristics: y(i) = f(x(i)) % cxy(:,3) optional c-vector : y = sum(c(k) x^k) % x Input signal over time exis, required % Outputs: % y Output signal over time exis: y(i) = f(x(i)) % xclp input vector after clipping to range min(cx)...max(cx) % yunclp output vector y before clipping to range min(cy)...max(cy) % Function Calls: % f_PolyCoefs: Compute coefs of polynomial % Author: Martin Schubert % Date last modified: 09.Apr.2017 by M. Schubert %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function [y,xclp,yunclp] = f_char(cxy,x) % make sure there are at least 2 inut arguments available assert(nargin>1,'function requires at least 2 input arguments'); % cx = cxy(:,1); cy = cxy(:,2); if size(cxy,2)<3; % compute coeffcients cv = f_PolyInit(cx,cy); else cv = cxy(:,3); end; % % clip input vector x to limits of characteristics vector cx xclp = max(min(cx),min(max(cx),x)); % compute output unclipped y = sum(ci*x^i), i=0...order yunclp = f_PolyEval(cv,xclp); % clip output vector y to limits of characteristics vector cy y = max(min(cy),min(max(cy),yunclp));

Page 109: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 109 -

5.5.3 Polynomial Coefficient Computation and Evaluation

For given data vectors cx and cy we can compute matrix A according to equation (5.18) and get cc by three different ways: 1. cc = A^(-1) * cy; % c = A-1 * y 2. cc = inv(A) * cy; % c = inv(A) * y 3. cc = A\cy; % this technique is recommended by Mathworks The technique in line 3 is recommended by MathWorks. In this case the inverse matrix A-1 is not completely computed as not required to solve the equation system. As in Matlab all vectors begin with index 1, we have to use ck = cc(k+1); with ck being the coefficient according to equation (5.18) and cc(k+1) its Matlab name. Listing 5.5.4(a): Matlab function f_PolyInit computing coefficient vector cc from (cx,cy).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: Compute coefs of polynomial y(x) through points (xi,yi) % Inputs: % cx(): x-vector defining polynomial: len(cx)>1 required % cy(): y-vector defining polynomial: y(i) = f(x(i)) % Outputs: % cc(): coefficients: y(x) = cc(i)*x^(i-1) % Author: Martin Schubert % Date last modified: 09.Apr.2017 by M. Schubert %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function cc = f_PolyInit(cx,cy) NoC = length(cx); assert(nargin==2,'function requires 2 input vectors'); assert(NoC>1,'input vectors must have at least 2 points'); assert(length(cy)==NoC,'error: cx and cy must have same length'); A = zeros(NoC,NoC); for row=1:NoC; for col=1:NoC; A(row,col) = cx(row)^(col-1); end; end; cc = A\cy; % the ' brings cy into the upright position

Listing 5.5.4(b): Matlab function f_PolyEval computing polynomial from x and coefs.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: Compute polynomial y(x) from cc and x % Inputs: % x(): input vector % cc(): coefficient vector % Outputs: % y(): coefficients: y(x) = sum(cc(i)*x^(i-1)) % Author: Martin Schubert % Date last modified: 09.Apr.2017 by M. Schubert %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = f_PolyEval(cc,x) xk = ones(1,length(x)); % = x^0 y = cc(1)*xk; % = c0 * x^0 for k=2:length(cc); xk = xk .* x; % x^(k-1) y = y + cc(k)*xk; % y = sum(ck * xk) end;

Page 110: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 110 -

5.6 Quality Criteria Read chapter 5.5.1.3 about frequency-domain computations in function tb_characteristics to understand where to look for the 1st and higher harmonics on vector Y(f)=fft(y(t)). 5.6.1 Spurious Free Dynamic Range (SFDR)

The Spurious free dynamic Range (SFDR) is the minimum distance between the amplitude of the maximal allowed sinusoidal test signal and the maximum amplitude harmonic. Fig 5.6.1: definition of SFDR. Typical measurement of spectrum analyzer. It is seen that there is some noise at any frequency plus harmonics of the test signal frequency. In the example we see some 80dB SFDR.

frequency / finput0 1 2 3 4 5 6 10

SFDR

lX(f)l0

-50

-100

Am

plit

ude

Sp

ect

rum

/ d

B

Exercise: Compute SFDR Write a Matlab function f_sfdr computing the total harmonic distortion of characteristics y(x). Check for the amplitude of the 1st harmonic in relative frequency range F=0...½. Check for the next highest harmonic Compute the difference 5.6.2 Total Harmonic Distortion (THD)

The Total Harmonic Distortion is an other measure for errors based on non-linearity. It computes the energy of the harmonics of the sinusoidal signal with frequency f1 compared to the energy at f1 or the total signal energy.

)(

)(

1

2

2

fX

fX

THD

N

kk

with fk = kf1, (5.53)

Exercise: Write a Matlab function f_thd computing the total harmonic distortion of characteristics y(x).

Page 111: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 111 -

5.7 Analog Circuitry for Signal Conditioning

5.7.1 Mathmatical Basics

Assume linear transfer functions translating input voltage Ux to output voltage Uy delives Uy = c0 + c1 Ux . (5.7.10) With 2 given points (Ux1,Uy1) and (Ux2,Uy2) we have 2 equations for the 2 unknowns c0, c1: Uy1 = c0 + c1 Ux1 (5.7.11) Uy2 = c0 + c1 Ux2 (5.7.12) To compute c0 and c1 we make the basic approach

12

1

12

1

xx

xx

yy

yy

UU

UU

UU

UU

(5.7.13)

which can be used back and forth symmetrically:

1112

12 )( yxxxx

yyy UUU

UU

UUU

(5.7.14)

1112

12 )( xyyyy

xxx UUU

UU

UUU

(5.7.15)

Consequently, we get amplication and offset as

12

121

xx

yy

x

y

UU

UU

U

Uc

, (5.7.16)

1110 xy UcUc , (5.7.17)

herein being the voltage amplification

1cAV (5.7.18)

and offset voltage

0cUoff (5.7.19)

Matlab models are offered in chapter 5.7.9 to comput c0, c1, resistors and biasing voltage UB for the different amplifier types. The most actual version will be found in directory MSlib/Slib/ that can be downloaded from the author’s homepage at https://hps.hs-regensburg.de/scm39115/homepage/education/courses/courses.htm -> Common Stuff.

Page 112: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 112 -

5.7.2 Inverting Amplifier

Fig 5.7.2: Inverting amplifier with input impedance Zin=R1.

Ux R1 R2

UB

Zin =>

Uy

This is the only amplifier that can deal with very high input voltages Ux when R1 can handle them. Equations:

1

21 R

Rc (5.7.21)

BUR

RRc

1

210

(5.7.22)

Computing devices and biasing voltage UB: Select Z1 = R1 = input impedance:

inZR 1 (5.7.23)

112 RcR (5.7.24)

021

1 cRR

RU B

(5.7.25)

Page 113: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 113 -

5.7.3 Non-Inverting Amplifier

Fig. 5.7.3: Non-inverting amplifier with input impedance Zin->∞.

R1

R2

UB

Zin =>

Ux

8

Uy

Equations:

1

211 R

RRc

(5.7.31)

1

20 R

Rc (5.7.32)

Computing devices and biasing voltage UB: Select R1, then

1112 cRR (5.7.33)

02

1 cR

RU B (5.7.34)

Page 114: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 114 -

5.7.4 Differential-In Single-Ended-Out Amplifier

Fig. 5.7.4: Diff-in single-ended-out amplifier.

R'2R'1

R2R1 Uy

OP1

UB

Uxm

U'BOP2

Uxp

P1

VCC

VEE

Ux

Fig. 5.7.4 illustrates the schematics of a differential-in single ended-out amplifier assuming R'1=R1 and R'2=R2. Amplifier OP2 can be omitted for low-impedant UB, otherwise OP2 is required to prevent the output resistance of UB from adding to R'2. Obey the valid range for common-mode input voltage Ucmi=½(Uxp+Uxm)! Equations:

1

21 R

Rc (5.7.41)

BUc 0 (5.7.42)

Computing devices and biasing voltage UB: Select R1, then

112 RcR (5.7.43)

0cU B (5.7.44)

Page 115: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 115 -

5.7.5 Instrumentation Amplifier

R3

R4 ext

R'3

OP2

OP3Uxp

U2

U1

stage 1: AV1 = 1+2R3/R4 stage 2: AV2 = -R2/R1

(25K)

(25K)

R'2R'1

R2R1

Uy

OP1

(40K) (40K)

(40K) (40K)

Uxm

Ux

UB U'B

OP4

Fig. 5.7.5: Instrumentation Amplifier. Numbers in braces are taken from INA128. Another example was INA128, AD8671. If OP4 is included in the device depends on the particular device.

Fig. 5.7.5 illustrates an instrumentation amplifier with voltage feedback. Current feedback instrumentation amplifiers have the same dependency on resistors R1...R4. OP4 is required to prevent the output resistor of UB from adding itself to R'2. which would destroy the matching condition R1= R'1 and R2= R'2. If OP4 is included in the package depends on the particular device. Obey the valid range for common-mode input voltage Ucmi=½(Uxp+Uxm). Equations:

3

43

1

21

22

R

RR

R

Rc

(5.7.51)

BUc 0 (5.7.52)

Computing devices and biasing voltage UB: Select R1, R2 and R3, (Typically, they are given as R2=R1), then

1

2

12

1

34

cR

RR

R (5.7.53)

0cU B (5.7.54)

Page 116: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 116 -

5.7.6 Fully Differential Amplifier

Fig. 5.7.6: Fully differential amplifier.

R'2R'1

R2R1

Uyp

Uxm

CMFBUcmo

OP1

Ri

Ri

Uym

Uy

VCC

VEE

Uxp

Uxm

Ux

Fig. 5.7.6 illustrates the schematics of a fully differential amplifier. It assumes matching: R'1=R1 and R'2=R2. Common mode output voltage is held by an inner control loop at outer Ucmo, which is here generated with Ri as Ucmo=½(VCC+VEE). Hint: Carefully obey the valid range for common-mode input voltage Ucmi=½(Uxp+Uxm) accoding to respective data sheets. Equations:

1

21 R

Rc (5.7.61)

c0 is centered by to UCMFB by feedback loop to common mode feedback (CMFB) input. (5.7.62) Computing devices: Select R1, then

112 RcR (5.7.63)

The common mode output voltage is typically centered into the output voltage range:

2min,max, outout

cmo

UUU

(5.7.64)

Page 117: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 117 -

5.7.7 Fully Differential Instrumentation Amplifier

R'2R'1

R2R1

Uyp

Uxm

U1

CMFBUcmo

OP1

Ri

Ri

Uym

Uy

VCC

VEE

U2

R3

R4 ext

R'3

OP2

OP3Uxp

Uxm

Ux

stage 1: AV1 = 1+2R3/R4 stage 2: AV2 = -R2/R1

Fig. 5.7.7: Fully differential instrumentation amplifier. Fig. 5.7.7 illustrates the schematics of a fully differential instrumentation amplifier. Obey the valid range for common-mode input voltage Ucmi=½(Uxp+Uxm). Equations:

3

43

1

21

2

R

RR

R

Rc

(5.7.71)

c0 is centered by to UCMFB by feedback loop to common mode feedback (CMFB) input. (5.7.72) Computing devices: Select R1, R2 and R3, (Typically, they are given and R2=R1), then

1

2

12

1

34

cR

RR

R (5.7.73)

The common mode output voltage is typically centered into the output voltage range:

2min,max, outout

cm

UUU

(5.7.74)

Page 118: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 118 -

5.7.8 Offset Compensation for Fully Differential Amplifier

t

Uout

(b)

Uoff

1

2

1

2

AV

Uoff

UoutUin

1

2

1

1

1

2

2

2

(a)

fchop 2fchop0

1/f noise(c)

Fig. 5.7.8: (a) Chopper stabilized Amplifier, (b) Output signal in time domain, (c) 1/f noise in frequency domain

Fully differential amplifiers allow for chopper compensation of amplifier’s offset as illustrated in Fig. 5.7.8(a): The signal on its path from Uin to Uout is not inverted during phase 1 when Ø1-controlled switches are conducting, inverted twice during phase 2 when Ø2-controlled switches are conducting. Consequently, the amplification is never inverting. On the other hand, the amplifier’s offset voltage Uoff is not inverted during phase 1 so that it adds to Uin, inverted once during phase 2, so it subtracts from Uin. Consequently, offset and low frequency noise like 1/f-noise are shifted to the chopper frequency and can be removed by lowpass filtering. If a fully differential amplifier is used to feed an ADC, we can make a first A/D conversion during phase 1 and a second conversion during phase 2. At the end we compute the average of those two values to remove the amplifier’s offset.

Page 119: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 119 -

5.7.9 Computing Spice Parameters for Signal-Conditioning Circuits

Listing 5.7.8: Matlab Testbench tb_OpAmp_SpiceParameter.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Testbench: tb_OpAmp_SpiceParameter % Purpose: Compute Spice parameters for different amplifier configurations % Author: Martin Schubert % Date last modified: 06.Mar.2017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Linear Transfer Characteristics fprintf('Spice Parameter Computation for operational amplifiers (OpAmps):'); fprintf('\n\rTransfer Characteristics: '); x1 = -1; x2 = 1; y1 = 0; y2 = 4; fprintf('from range: x1=%dV - x2=%dV to range x1=%dV - x2=%dV',x1,x2,y1,y2); c1 = (y2-y1) / (x2-x1); c0 = y1 - c1*x1; fprintf('\n\rTransfer Characteristics: '); fprintf('Amplification: c1=%dV, Offset: c0=%dV ',c1,c0); x = x1:(x2-x1)/1000:x2; y = c0 + c1*x; % % 1. Inverting Amplifier fprintf('\n\r 1in1out inverting simple ampifier: '); Zin = 100; R1 = Zin; % given R2 = R1*abs(c1); Ub = c0*R1/(R1+R2); fprintf('R1=%dK, R2=%dK, Ub=%dV',R1,R2,Ub); % % 2. Non-Inverting Amplifier fprintf('\n\r 1in1out non-inverting ampifier: '); R1 = 100; % given R2 = R1*(abs(c1)-1); Ub = -(R1/R2)*c0; fprintf('R1=%dK, R2=%dK, Ub=%dV',R1,R2,Ub); % % Diff-In / Single-Ended-Out Amplifier fprintf('\n\r 2in1out diff-in/single-out ampifier: '); R1 = 100; % given R2 = abs(c1)*R1; % input amplitude is Uip-Uim Ub = c0; fprintf('R1=%dK, R2=%dK, Ub=%dV',R1,R2,Ub); % % Diff-In/Single-Out Instrumentation Amplifier fprintf('\n\r 2in1out instrumentation ampifier: '); R1 = 100; % given R2 = 100; % given R3 = 100; % given R4 = 2*R3/(abs(c1)*R1/R2-1); % input amplitude is Uip-Uim Ub = c0; fprintf('R1=%dK, R2=%dK, R3=%dK, R4=%dK, Ub=%dV',R1,R2,R3,R4,Ub); % % Fully Differential Amplifier fprintf('\n\r 2in2out fully differential ampifier: '); R1 = 100; % given R2 = R1 * abs(c1); Ucmfb = (y2-y1)/2; fprintf('R1=%dK, R2=%dK, Ucmfb=%dV',R1,R2,Ucmfb); % % Fully Differential Instrumentation Amplifier fprintf('\n\r 2in2out fully diff. instr. ampifier: '); R1 = 100; % given R2 = 100; % given R3 = 100; % given R4 = 2*R3/(abs(c1)*R1/R2-1); % Ucmfb = (y2-y1)/2; fprintf('R1=%dK, R2=%dK, R3=%dK, R4=%dK, Ucmfb=%dV\n\r',R1,R2,R3,R4,Ucmfb);

Page 120: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 120 -

6 Quantization The first reported idea of quantization is the word “atom” coming from an old Greek expression saying “no more dividable”. The concept, that any material is composed of smallest pieces (atoms) is found in ancient Greek and Indian cultures. Proofs of this theory came in the beginning of 20th century with Albert Einstein and others. The basic concept of quantization is that quantity is an integral multiple of a smallest unit, e.g. a least significant bit (LSB), a delta (Δ), or atoms. Therefore, the kernel process of quantization comes with rounding to a given minimum step, typically termed Δ.

6.1 Mathematics Any number x can be written as

offoff x

xxx

(6.1)

This allows for weighted rounding as

offoff

q xxx

roundx

(6.2)

where offset xoff adjust the thresholds. In its simplest form with xoff=0 we have the basic model of quantization as

x

roundxq (6.3)

The round-off error (mathematical) or quantization error (signal processing) is

qq xxe (6.4)

Combining (6.4) and (6.3) delivers

offoff

q xxx

roundxe

(6.5)

Page 121: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 121 -

Listing 6.1(a): Matlab Function f_quantize performing quantization

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: Quantization % % Input paramters % x : require, value to be quantized, quantity, may be a vector % delta: scalar, default =0, quantization step, % no quantization if delta=0 % offset: scalar, default=0 % % Output paramter: xq = delta*round((x-offset)/delta) + offset % % Author: Martin Schubert % Date last modified: 05.Mar.2017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function xq = f_quantize(x,delta,offset) % make sure there are at least 3 inut arguments available assert(nargin>0,'function requires at least 1 input arguments'); % % Perform quantization if not(exist('delta')); delta = 0; end; % % is there an offset to be respected? if not(exist('offset')); offset = 0; end; % % quantize if delta == 0; xq = x-offset; % zero delta doesn't quantize else xq = delta * round((x-offset)/delta) + offset; end;

Listing 6.1(b): Testbench for Matlab Function f_quantize

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Purpose: Testbench tb_quantize for f_quantize % Author: Martin Schubert % Date last modified: 09.Mar.2017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% t = 0:1000; F = 0.001; xmax = 1; xmin = -1; Levels = 9; xv(1) = xmin; xv(2) = xmax; yv(1) = xmin; yv(2) = xmax; deltax=(xmax-xmin)/(Levels-1); xc = (xv(2)+xv(1))/2; % central x xa = (xv(2)-xv(1))/2; % amplitude x = xa*sin(2*pi*F*t); xoffset = 0.333; xq = f_quantize(x,deltax,xoffset); % quantization error; eq = x-xq; % post processing % graphical figure(2); plot(t,x,'k',t,xq,'b',t,eq,'r'); grid on; % numerical xrms = f_rms(x) % effective x yrms = f_rms(xq) % effective xq eqrms = f_rms(eq) % effective eq fprintf('xrms: ideal: %f, real: %f \r\n',xa/sqrt(2),xrms); fprintf('xqrms: %f \r\n',xqrms); deltax = (xmax-xmin)/(Levels-1); fprintf('eqrms: ideal: %f, real: %f \r\n',deltax/sqrt(12),eqrms);

Fig. 6.1: analog signal x (black), quantized xq, quantization error eq.

Page 122: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 122 -

Function f_rms used in the testbench above computes the effective (RMS) value as shown in Listing 6.1(c). Listing 6.1(c): Matlab Function f_rms compute effective value of a vector

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: Compute Root Mean Square (RMS) Value of Input Vector x % Input Parameter: % x input vector, required % Output: % xrms : = sqrt(xpow) : RMS-value of input signal x % xpow : = xeng/length(x): average power of y % xeng : = sum(|x(i)|^2) : total energy of signal % Author: Martin Schubert % Date last modified: 26.Mai.2017 by M. Schubert %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function [xrms,xpow,xeng] = f_rms(x) if size(x,1)==1; % computing effective effective energy ... xeng = (x*x'); % ... for horizontal vector elseif size(x,2)==1; xeng = (x'*x); % ... for vertical vector else fprintf('\n\rerror in f_rms: input is neither a scalar not a vector\n'); end; xpow = xeng / length(x); % average power per tap xrms = sqrt(xpow); % effective amplitude

Page 123: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 123 -

6.1.1 Rounding to an Absolute Δ-Step.

For simple rounding we use xoff=0. xoff≠0 is required for A/D conversion. The words “integral” and “fractional” places describe digits left and right of the point, respectively. Procedure to Round x Represented to Base b to a given step size bn:

Rounding a number x with basis b to an accuracy of n places using Δ=bn , (6.6)

n

nq b

xroundb

xroundx (6.7)

causes for n0 the closest n places left to the point being 0’s and for n<0 that there a no more than n places right to the point. Using Matlab + Octave Decimal-to-binary conversion of a positive integral number from can be done with Matlab command » binary_number = de2bi(decimal_number)

Note that you’ll get a vector of 1’s and 0’s with LSB in index 1 and MSB last, i.e. the binary number 110102 is displayed as 0 1 0 1 1. Doing this with Octave (4.2.1) requires to load the communications package with command » pkg load communications Applications:

1(a) Example: Round x=314159.2610 to n=4 integral decimal places:

b=10, n=4 Δ=104

xq =

4

4

10

26.31415910 round

xround = 31 0000.

After rounding with Δ=bn the last n integral decimal places of xq must be 0’s. 1(b) Exercise: Round x=14142.135610 to n=3 integral decimal places:

Page 124: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 124 -

2(a) Example: Round to an Accuracy of n=3 fractional decimal places:

b=10, n=-3 Δ=10-3

q =

33

10

...1415.310 roundround

= 3.142 .

After rounding to n fractional places there are no more than n places right to the point: 2(b) Exercise: Round x=2 to an Accuracy of n=2 fractional decimal places:

3(a) Example: Round x=1234.567810 to n=6 integral binary places:

b=2, n=6 Δ=26

xq =

6

6

2

5678.12342 round

xround = 64round(19.2...) = 1216.

Binary representation of xq: After rounding to n integral binary places the last n binary places of the number must be 0’s: 121610 = 100 1100 00002. 3(b) Exercise: Round x=765.432110 to n=8 integral binary places:

Binary representation of xq: After rounding to 8 integral binary places the last 8 binary places of the number must be 0’s:

Page 125: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 125 -

4(a) Example: Round to an accuracy of n=4 fractional binary places:

b=2, n=-4 Δ=2-4

44

22

roundroundxq = 2-4round(50.2...) = 2-450.

After rounding to n fractional binary places we can represent the number with n bits after the point. Binary representation: 5010 2-4 = 11001022-4 = 11.00102.

4(b) Exercise: Round 2 to an accuracy of n=5 fractional binary places:

After rounding to 5 fractional binary places we can represent the number with 5 bits after the point. Binary representation:

Page 126: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 126 -

6.1.2 Rounding to a Relative Δ-Step.

Typically we want to round a number to a certain amount of most significant places. So we have to compute the required Δ. Examples: Compute Δ: 3.6510-6 = 365 10-8 = 365 Δ with Δ=10-8, 1.2 105 = 12 104 = 12 Δ with Δ=104, 1.20105 = 120 103 = 120 Δ with Δ=103, 1011.1 = 1 0111 2-1 = 1 0111 Δ with Δ=2-1. 1011.10 = 10 1110 2-2 = 10 1111 Δ with Δ=2-2. Examples: Compute Δ: 2.5710-6 = .................................................... 4.6 105 = .................................................... 4.60105 = .................................................... 1100.11 = .................................................... 1100.110 = .................................................... Procedure to round x to its m most significant places with respect to base b:

Δ is computed for base b as n = ceil(logb(|x|)) – m (6.11)

mxceiln bbb |))(|(log . (6.12) The rest is identical as described above: xq=Δround(x/Δ). Matlab function f_quantize2msp and its testbench tb_quantize2msp are given in Listings 6.12. (b) and (a), respectively.

Page 127: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 127 -

Listing 6.1.2(a): Matlab Testbench tb_quantize2msp for to f_quantize2msp

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: Testbench for rounding to m most significan places % Author: Martin Schubert % Date last modified: 09.Mar.2017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % x = pi; % variable to be converted m = 6; % number of most significant places b = 2; % base fprintf('rounding x=%f to %d most significant places to base b=%d',x,m,b); [xq,n,delta] = f_quantize2msp(x,b,m); fprintf('\n\rquantized x is xq=%f, n=%d, delta=b^n=%f\n\r',xq,n,delta); Listing 6.1.2(b): Matlab function f_quantize2msp : compute m most significant places of x to

base b. Use mathematical relationship logb(x)=ln(x)/ln(b).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: round x to its m most significant places to base b % Input Parameter: % x: required: input to be rounded to its m most significant places % b: default=10 (decimal): base of number system: binary b=2, octal b=8 % m: default=3: number of most significant places requried % Output: % xq: quantized x % n : number of places to base b of delta % delta: absolute delta step used % Function calls: log(), use relatition logb(x)=log(x)/log(b) % Author: Martin Schubert % Date last modified: 09.Mar.2017 by M. Schubert %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function [xq,n,delta] = f_quantize2msp(x,b,m) if x==0; xq=0 else if nargin<2; b=10; end; % defualt: decimal number system if nargin<3; m=3; end; % default: 3 most significant places % compute absolute delta as b^n n = ceil(log(abs(x))/log(b))-m; % use logb(x)=log(x)/log(b) delta = b^n; % perform quantization xq = delta*round(x/delta); end;

Page 128: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 128 -

Examples and Exercises: Hint: do it yourself before confirming it with Matlab! 5(a) Example: Round x=88877710 to m=3 most significant decimal places.

Using b=10 (decimal) delivers Δ=10(ceil(log10(abs(x)))-m) = 106-3 = 103 = 1000,

xq =

3

3

10

88877710 round

xround = 889 000

5(b1) Exercise: Round x=7788810 to m=2 most significant decimal places.

5(b2) Exercise: Round q=1.6021771010-19C to m=3 most significant decimal places:

6(a) Example: Round positive x=1234.567810 to m=7 most significant binary places:

Using b=2 delivers Δ=2ceil(log2(abs(x)))-m = 211-7 = 24 = 16.

xq =

4

4

2

5678.12342 round

xround = 16round(77.1...) = 1232.

Proof using binary representation: After rounding to m most significant binary places the first m binary places of the number may be non-0’s: 123210 = 100 1101 00002.

6(b) Exercise: Round positive x= 2/1 to m=6 most significant binary places:

Proof using binary representation: After rounding to m=6 most significant binary places the first 6 binary places may be non-0’s:

Page 129: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 129 -

7(a) Example: Round negative x=- to m=8 most significant binary places

For negative numbers we need an additional sign bit. Given are 8 binary places to represent most significant bits of -. Step 1: Solve the problem with m' = 7 bits: Using b=2 delivers Δ=2ceil(log2(abs(-)))-m’ = 23-7 = 24 = 16.

|xq| =

4

4

22

round

xround = 2-4round(50.2...) = 50 2-4.

Step 2: Convert absolute value to binary: xq = -|xq| = -5010 2-4 = - 0011 0010 2-4. Step 3: Respect the sign: xq = -|xq| = - 0011 0010 2-4 = 1100 1110 2-4 signed representation.

7(b) Exercise: Round negative x=- 2 to m=8 most significant binary places

8. Round a vector h to m most significant binary places of its maximum number:

Figure out the required number range: hmax = max(abs(h)); % maximum absolute number to be represented hmin = min(h); % if negative numbers occur a sign bit is required

Page 130: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 130 -

6.2 Software Tests

6.2.1 Computing Δ and its Quantization Noise SNRq and SNRq,dB

In tb_characteristics we find the lines % Quantization; round to NoMSP Most Significant Places of given Base NoB = 12; % Number of Bits = Bitwidth of data after quantization dsmorder = 0; % order of Delat-Sigma modulator, if 0: quantizer only NoB is the number of Bits required to compute Δ. Remember that vectors cx(i), cy(i) define the transfer characteristics of our system and ymax=max(cy); ymin=min(cy); define its maximum and minimum output value range. This is now quantized into 2NoB levels or 2NoB-1 deltas, so that delta = (ymax-ymin)/(2^NoB-1); Running tb_characteristics with these settings we’ll get a best-case SNR of SNRq = ((ymax-ymin)2/8 / Δ2/12) SNRq,dB = NoBꞏ6.02dB + 1.76dB . Computed vlaues we get from tb_characteristics for NoB=12, NoW=63, dsmorder=0, NoS=212 and dataWindow='rect' is 74.0072 dB from the equation above and 74.0439 dB from computing the rms-value of the quantized curve. Experiment: Set the Number of Waves in the measurement interval from NoW=63 to 64. And run tb_characteristics again. What happens? Try NoW=65. What is the problem with NoW=32, 64, 128,..? .............................................................. .............................................................. .............................................................. ..............................................................

Page 131: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 131 -

6.2.2 Using Window Functions

The adjustment dataWindow='rect' is a so-called rectangular or do-nothing window. It delivers an ideal result for integral numbers NoW (=Number of Waves in the test interval) but is unrealistic for practical measurements. Set from NoW=63 to NoW=63.01 to check the disaster. Set NoW=63 and a Blackman-Harris window by dataWindow='bhar'. You will find that the indicated frequency Fts gets wider in the FFT, as can be observed with the graphical Zoom function. But setting NoW=63.01 doesn’t disturbe the measurement any more. 6.2.3 Delta-Sigma Modulation

The effect of window functions becomes more obvious if you set 1st or second order modulation with dsmorder=1 or dsmorder=2. The quantization delta remains the same, but the modulator pusches the noise from lower to higher frequencies. Try out the impact of the window function with integral and fractional NoW, ΔƩ modulator dsmorder = 0 (=quantization without modulation), dsmorder = 1 and dsmorder = 2. 6.2.4 Low-Pass Filtering or Delta-Sigma Demodulation

Pushing quantization noise to higher frequencies makes sene if – and only if – we can remove it at these higher frequencies. So default Fg=0.5 is an all-pass having no filtering impact. So set a low-pass with Fg ≥ NoW / NoS. Here we have NoW / NoS=63/4096 ≈ 1/65 ≈ 0.0154. Try it with Fg=0.1 or 0.02 and observe the computed SNRdB. Best case SNRq,dB with dsmorder=0, Fg=0.5: .............................. Computed SNRq,dB with dsmorder=2, Fg=0.1: .............................. Computed SNRq,dB with dsmorder=2, Fg=0.02: ..............................

Page 132: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 132 -

7 D/A and A/D Conversion

ADC DACdDAC NOB

xmax

xmin

xdADC

dmax

dmin

ymax

y

ymin

Fig. 7: Top-level view of an A/D and D/A Conversion (ADAC) system.

7.1 Linear A/D/A Behavioral Conversion Models For both ADC and DAC holds ideally a linear relationship between voltage Ux, integral number Nx and constants Umin, Umax, Nmin, Nmax:

minmax

min

minmax

min

NN

NN

UU

UU xx

(7.1)

7.1.1 Linear Behavioral D/A Converter Model

A D/A converter (DAC) translates an integral number Nin from range Nmin ≤ Nin≤ Nmax into a voltage Sie Uout within range Umin ≤ Uout≤ Umax, whereas Nin is variable and model paramters Nmin, Nmax, Umin, Umax are constants characterizing a particular device. From (7.1) we obtain

minminmax

minmaxmin NN

NN

UUUU inout

(7.1.1)

Translating this to the form Uout = c0 + c1ꞏNin (7.1.2) delivers

c1 = minmax

minmax

NN

UU

(7.1.3)

c0 = Umin - c1ꞏNmin . As minimum step size of Nin is 1, the minimum analog output-voltage step size ΔDA = c1 . (7.1.4)

Page 133: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 133 -

7.1.2 Linear Behavioral A/D Converter Model

An A/D converter (DAC) translates an analog voltage Uin from range Umin ≤ Uin≤ Umax into an integral number Nout within range Nmin ≤ Nout≤ Nmax, whereas Uin is variable and model paramters Umin, Umax, Nmin, Nmax are constants characterizing a particular device. From (7.1) we obtain

minminmax

minmaxmin UU

UU

NNNroundN inout (7.2.1)

Translating this to the form

inout UccroundN 10 (7.2.2)

delivers

c1 = minmax

minmax

UU

NN

(7.2.3)

c0 = Nmin - c1ꞏUmin As minimum step size of Nout is 1, the minimum analog input-voltage resolution is ΔAD = 1/c1 . (7.2.4) 7.1.3 Matlab Models

Listing 7.1.3.1: DAC model:

function Uout = f_dac(Nin,Nmin,Nmax,Umin,Umax) c1 = (Umax-Umin)/(Nmax-Nmin); c0 = Umin - c1*Nmin; Uout = c0 + c1*Nin; Listing 7.1.3.2: ADC model:

function Nout = f_adc(Uin,Umin,Umax,Nmin,Nmax,noquant) c1 = (Nmax-Nmin)/(Umax-Umin); c0 = Nmin - c1*Umin; Nout = c0 + c1*Uin; if nargin<6; % a 6th input argument prohibits quantization Nout = round(Nout); end;

Page 134: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 134 -

Listing 7.1.3.3: Testbench:

% tb_adac Ats = 1.0; Ots = 0.0; Fts=1/500; NoS=1000; t=0:NoS-1; Uin = Ats*sin(2*pi*Fts*t); % Umax = 1; Umin = -1; NoL = 9; % number of levels Nmin=0; Nmax=Nmin+NoL-1; % % ADC application Nio = f_adc(Uin,Umin,Umax,Nmin,Nmax); Uout = f_dac(Nio,Nmin,Nmax,Umin,Umax); eq = Uin-Uout; % % ADC application without quantization Nref = f_adc(Uin, Umin,Umax,Nmin,Nmax,'no_quantization'); Uref = f_dac(Nref,Nmin,Nmax,Umin,Umax); eref = Uin-Uref; % should be zero % figure(1) subplot(211); plot(t,Uin,t,Uout,t,eq); subplot(212); plot(t,Uin,t,Uref,t,eref); Fig. 7.1.3: Plot obtained with f_adc, f_dac and testbench tb_adac as listed above.

Page 135: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 135 -

7.2 Introducing Bended and Clipped Characteristics Real-world A/D and D/A converters are never absolutely linear. To model non-linearity we introduce clipping and bending of the characteristics. Clipping is done by given data points. cx = [x1, x2, x3,...] (7.5) xmax = max(cx) (7.6) xmin = min(cx) (7.7) cy = [x1, x2, x3,...] (7.8) ymax = max(cx) (7.9) ymin = min(cx) (7.10) defining the characteristics y=f(x) as described in chapter 5.3 where also the computation of ci is detailed. Input clipping is done by xclipped = max(xmin,min(xmax,x)) (7.11) before evaluation of the polynomial

y =

order

k

kclippedk xc

0

(7.12)

with ck = cc(k+1) as Matlab vector cc must begin with index 1. In case of extreme non-linearity we might also perform output clipping yclipped = max(ymin,min(ymax,y)) (7.13) As input clipping and polynomial computation of according to (7.13) is done by function f_characteristics(x,cx,cy) detailed in chapter 5.5. The Matlab models in Listing 7.2 compute the number of levels (NOB) and number of delta’s (NOD) from the decimal-vector dv. It contains the integral numbers dv = [d1, d2, d3,...] . (7.14) Subprogram f_characteristics computes dmax = max(dv) (7.15) dmin = min(dv) (7.16) As on the digital side Δd=1, the number of Δ’s and number of levels, respectively, is given by NOD = dmax - dmin (7.17) NOL = NOD +1 (7.17) Example: With feeding dv=[0 255] as input vector to f_adc we have implicitly declared 255 Δ’s and 256 levels. Function f_adc will always return integral numbers due to the round function.

Page 136: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 136 -

For f_dac it is not obvious that input vectors d and dv contain integral numbers only. The user should take care that this condition is fulfilled to guarantee a physically meaningful operation. Listing 7.2-1: Matlab ADC model with clipping and non-linear characteristics using f_characteristics

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: Model A/D Converter (ADC) % Input Parameter: % x Input signal over time exis, required % cx() x-vector defining I/O characteristics: len(cx)>1 required! % dv() input-integer-vector defining I/O characteristics: y(i) = f(x(i)) % Output: % d integer: Output signal over time exis: y(i) = f(x(i)) % Function calls: f_characteristics: non-linear charact. and clipping % Author: Martin Schubert % Date last modified: 06.Mar.2017 by M. Schubert %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function d = f_adc(x,cx,dv) % make sure there are at least 3 inut arguments available assert(nargin>2,'function requires at least 3 input arguments'); % % Apply linear Signal Conditioning and Quantization with delta==1 d = round(f_characteristics(x,cx,dv)); Listing 7.2-2: Matlab DAC model with clipping and non-linear characteristics using f_characteristics

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: Model D/A Converter (DAC) % Input Parameter: % d integer, input signal over time exis, required % dv() input-integer vector, defining I/O characteristics: len(dv)>1 ! % cy() y-vector defining I/O characteristics: y(i) = f(x(i)) % Output: % y integer: Output signal over time exis: y(i) = f(x(i)) % Function calls: f_characteristics: non-linear characteristics and clipping % Author: Martin Schubert % Date last modified: 06.Mar.2017 by M. Schubert %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function y = f_dac(d,dv,cy) % make sure there are at least 3 inut arguments available assert(nargin>2,'function requires at least 3 input arguments'); % % Apply linear Signal Conditioning y = f_characteristics(d,dv,cy);

Page 137: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 137 -

Listing 7.2-3: Matlab testbench tb_adac for functions f_adc and f_dac. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: Testbench for A/D and D/A Conversion models % Author: Martin Schubert % Date last modified: 06.Mar.2017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % t = 0:1000; F = 0.001; xmax = 1; xmin = -1; dv = [0 16]; cx(1) = xmin; cx(2) = xmax; cy(1) = xmin; cy(2) = xmax; xc = (cx(2)+cx(1))/2; % central x xa = (cx(2)-cx(1))/2; % amplitude x = xa*sin(2*pi*F*t); % A/D conversion d = f_adc(x,cx,dv); % D/A conversion y = f_dac(d,dv,cy); % quantization error; eq = x-y; % post processing % graphical figure(3); plot(t,x,'k',t,y,'b',t,eq,'r'); grid on; % numerical xrms = f_rms(x) yrms = f_rms(y) eqrms = f_rms(eq) fprintf('xrms: ideal: %f, real: %f \r\n',xa/sqrt(2),xrms); fprintf('yrms: %f \r\n',yrms); deltax = (xmax-xmin)/(dv(2)-dv(1)); fprintf('eqrms: ideal: %f, real: %f \r\n',deltax/sqrt(12),eqrms);

Fig. 7.2: Plot produced by testbench tb_adac

Exercise: Copy Matlab files tb_adac.m, f_adc.m, f_dac, f_characteristics.m, f_PolyInit.m and f_PolyEval.m into your directory and run tb_adac to get the plot shown in Fig. 7.2.

Page 138: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 138 -

7.3 ADA Students: Develop and Test your own A/D/A models Goal: Develop your own Matlab tools to measure quality criteria simulated with functions f_adc and f_dac above and at the same time include the measured errors into these function models. 7.3.1 Static Characteristics

Static characteristics and quality criteria can be measured with a static output=f(intput) curve. 7.3.1.1 Random Noise

Add a random error to the computed results. 7.3.1.2 Missing Codes

If SAR ADC’s are clocked too fast, they tend to set the MSB too fast. Example: for an 8-bit SAR ADC the output dADC=128 should come at half input voltage. Too fast clocking may cause an error that can be modeled in the output of f_adc as if and(d>120, d<=128); d=128; end; 7.3.1.3 Non-Monotonicity

Example that can be modeled in the output of f_adc as if d==129; d=125; end; 7.3.1.4 INL and DNL

INL: Integral non-linearity: Maximum deviation from the ideal linear characteristics. DNL: Differential non-linearity: Maximum difference of neighboring Δ’s. Define a non-linear characteristics using function f_characteristics employed in f_adc and f_dac. Plot a diagram dADC,out versus xADCin, then compare ideal and the non-linear characteristics dADC,out,ideal versus dADC,out,real.

Page 139: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 139 -

Fig. 7.3.1.4 (a) DNL (differential

non-linearity) describes the maximum difference of two neighboring 's, INL (integral non-linearity) describes the maximum deviation from the ideal curve.

digital

analog

INL

(b) Quantization error

caused by INL.

0

1

2

3

4

-1

-2

-3

-4

INL

UADCin

Page 140: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 140 -

7.3.2 Dynamic Characteristics

Dynamic characteristics are measured as output=f(frequency) at a sinusoidal input wave with maximum possible amplitude. Distinguish between Noise and Distortion. Feature: Distortion: ..................................................... Noise: ..................................................... 7.3.2.1 Measure Signal-to-Noise Ratio (SNR)

The signal to noise ratio of an A/D or D/A converter is defined as

NoisePower

rSignalPoweSNR (7.18)

Measured in dB we get

SNRdB = 10 dBꞏlog10(SNR) dB

SNRdB

SNR 1010 (7.19) The noise power is computed as square of all deviations from the ideal signal:

periodT

periodrms dtte

Te

0

22 )(1

(7.20)

This corresponds to the sum for time-discrete measurements:

endK

kk

periodrms e

Ke

0

22 1 (7.21)

The total noise power must be the same when it is integrated over the frequency axis:

2/

0

22 )('sf

qrms dffEE (7.22)

This corresponds to the sum for time-discrete measurements:

2/

0

22 )('sf

qrms dffEE =>

N

kkqrms fEE

0

22 )(' (7.23)

with )('2

kfE being the spectral signals power density, e.g. in V2/Hz. Consequently, we find

in may data sheets the quantity 'E , e.g. in HzV / .

Page 141: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 141 -

7.3.2.2 Random Noise

Exercise: Add random noise to your quantization models and check its behavior on the frequency axis by using Matlab’s random function. Observe its behavior over the frequency axis. 7.3.2.3 Quantization Noise

Exercise: Alter quantization noise amplitude of your quantization models and check its behavior on the frequency axis using Matlab’s.

12'

22/

0

22

sf

qq dfEE . (7.25)

According to theory you should observe a constant (“white”) noise power density '2

qE over

frequency and

12

22 qE . (7.26)

7.3.2.4 Effective Number of Bits (ENOB)

with 2.06=log10(2) and the 1.76dB stems from the fact that we compare a sinusoidal input curve with a triangular quantization error. When testing an ADC we typically measure its signal-to-noise ratio and then conclude to its effective number of bits (ENOB) from

dB

dBSNRENOB dB

06.2

76.1 (7.27)

As we can never exceed ideal best case conditions of quantization noise only we’ll always have ENOB NOB. (7.28) 7.3.2.5 Spurious Free Dynamic Range (Spurious Free Dynamic Range (SFDR)

Apply results from chapter 5.6.1. 7.3.2.6 Total Harmonic Distortion (THD)

Apply results from chapter 5.6.2.

Page 142: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 142 -

7.3.2.7 Signal to Noise and Distortion (SINAD)

Signal to Noise and Distortion is defined as

DistortionNoise

Signal

PP

PSINAD

(7.31)

typically much the same as SNR. Exercise: Use Matlab to for impact of non-linearities such as INL, missing codes or non-monotonicity on SFDR. 7.3.3 Speed versus Accuracy

The figure of merit depends on the application. For a handheld multimeter we typically want to have single measurements with high accuracy. For a video camera we need a combination of high throughput and good accuracy, delay of some ms more or less is not important. For systems requiring fast response like airbags low delay is essential. The general figure of merit is typically defined as Q1 or Q2 according to Q1 = Levels Throughput (7.41) Q2 = Levels / Delay (7.42) Throughput is the number of samples processed per second, measured in KSPS or MSPS or GSPS standing for Kilo, Mega or Giga samples per second, respectively. Throughput ca be compared to the amount of water in liter per seconds. Delay is time shift between flowing in and out. Generally Delay 1/Throughput. Exercise: introduce a delay in your ADC and DAC models.

Page 143: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 143 -

8 SK Students: Sampling Rate Issues 8.1 Sampling Rate

8.1.1 Fundamental Considerations

We have two significant trumps in digital electronics, namely speed and accurate clocks. Exercises: A motor is thundering at 6000 rotations per minute (RPM). Compute that in Hertz: 6000 RPM = ............................................................ Formula-1 racing-car motors tune up to 12000 RPM. How much faster is a 2 GHz clock? ............................................................ ............................................................ A cheap simple watch with a quartz oscillator has an error of 8.64 seconds a day. Compute that in per cent. ............................................................ These two trumps will have to compensate for several drawbacks, e.g. tolerances of some ±10% and more for electronic devices like resistors, capacitors, inductors, transistors. Nobody would buy gold or even potatoes with uncertainties of ±10%. Example: The output of a simple RC lowpass is accurately the average of its input voltage for frequencies f >> fC. Tolerances of R and C might shift the cut-off frequency fC=1/(2RC) for some per cent, but the averaged output Uout remains accurate. Precondition is speed (f >> fC), a stable clock timing and signal integrity of Uin, i.e. a noise free shape of the 1’s and 0’s fed to the lowpass. In Fig. 8.1. the input voltage Uin is quantized as rough as possible: 1 bit = 2 levels only, and the electronic devices R and C might have significant tolerances. Nevertheless we can get a very smooth and accurate output voltage Uout when the input bit-stream at Uin is fast enough.

R

UinUout

Fig. 8.1: Obtaining accurate output voltage

Uout by oversampling

Page 144: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 144 -

8.1.1.1 Criterion of Nyquist and Shannon

A/D conversion is a two-dimensional process, namely quantization in value and time. Time discrete systems represent signals on discrete time points only: tn = nT, n = 0, 1, 2, 3, ... (8.1) with T = 1/ fs Being the spacing between neighboring time points and fs the sampling frequency. 8.1.2 Aliasing

asdf 8.1.3 Changing the Sampling Rate

8.1.3.1 Up-sampling by Integral Factor M

8.1.3.2 Down-Sampling (Decimation) by Integral Factor N

8.1.3.3 Sub-Sampling

8.1.3.4 Sampling Rate Change by Fractional Factor M/N

8.1.3.5 Two-Step Up-Sampling

8.1.3.6 Two-Step Down-Sampling

8.2 Filter Design 8.2.1 Sinc Filter

8.2.2 Band Passes

Page 145: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 145 -

9 RED: Student Project: From Top-Level to FSM Design Objective: We will now use Matlab to illustrate high-level modeling and how to break it down to finite-state-machine (FSM) design. Here, we take the examles of up- and down-sampling. The project should (i) illustrate a complete 2-step up-sampling and/or down-sampling scheme and (ii) take any part of it an realize it detailed as FSM. Assumption: We have a customer that need a top-level presentation of a sound system changing sampling rates. We do the job with high-level matlab commands such as upsample(.), downsample(.), filter(.). If the result meets our needs we’ll go to translate it into a finite state machine design that we could easily translate to VHDL. Example 1: Down-sampling before up-sampling. We use a sound track, down-sample it and up-sample it afterwards. Example 2: As available sound tracks are typically deliverd at sampling rates of 44100Hz, it makes sense to upsample them first, then apply a ΔΣ modulation scheme and downsample it to regain the original music.

9.1 Getting Started with Sound Processing Read chapter 2 “User Interface of my_SoundStudio” and particularly sections 2.2 “Getting Started” and 2.3 File I/O” to read some sound from a file to a Matlab vector. After reading a sound vector from a file you should have it on vector xn0 with sampling frequency in variable fs0.

9.2 Down-Sampling, Decimation We want to decimate a sound signal by a factor of 30. First of all we’ll do it in a one-step method and later in a 2-step procedure. 9.2.1 Single-Step Decimation

Read the 5 seconds sound of file sound.txt. Play it with Matlab command sound(xn0,fs0); Reduce sampling rate by down-spampling rate dsr=30 uing Matlab commands dsr = 30; % set the down-sampling rate xn2 = downsample(xn0,dsr); % Matlab's down-sampling function %xn2 = f_subsample(xn0,dsr); % selfmade down-sampling function fs2 = ds0/dsr; % down-sampled sampling frequency sound(xn2,fs2); % listen to dwn-sampled sound with alias noise The self-made downsampling function is for users that do not have the respective toolbox is not available. (In Octave it is the control package to be loaded by: pkg load control.)

Page 146: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 146 -

In a next step we’ll have to remove aliasing noise by applying a lowpass filter with cut-off frequency Fg≤1/dsr. Check with Matlab Filter Design ana Anaysis tool (command fdatool) for an appropriate filter length or use an odd length of some NoFT≥3/Fg => NoFC=101 taps. NoFC stands for Number of fir Filter Coefficients. Using the selfmade lowpass computation function f_hlp we can write code to avoid aliasing: NoFC = 101; % first guess for fir filter length dsr = 30; % set the down-sampling rate Fg = 1/30; % first guess for fir filter cut-off frequency hlp = f_hlp(NoFT,Fg); % low-pass filter impulse response yn0 = filter(hlp,1,xn0); % low-pass filtering sound xn2 = downsample(yn0,dsr); % downsample sound after low-pass %xn2 = f_subsample(yn0,dsr); % downsample sound after low-pass figure(1); subplot(311); plot(abs(fft(xn0))); sound(xn0,fs0); subplot(312); plot(abs(fft(yn0))); sound(yn0,fs0); subplot(313); plot(abs(fft(xn2))); sound(xn2,fs2); Task: Build a FSM model to build a lowpass filter. And test it instead of function filter. Observe your filter characteristics with command f_bode(0,hlp); 9.2.2 Two-Step Decimation

Decimation by large factors dsr requires high filter orders. To change this we apply a sinc filter first, decimate in a first step by a factor osr1 to sampling frequency fs1 (e.g. osr1=6) and in a second step by factor osr2 to fs2, where dsr=dsr1ꞏdsr2. This effect can be seen from my_SoundStudio -> Main Menu -> 4. Graphics Read the 5 seconds sound of file sound.txt. Play it with Matlab command sound(xn0,fs0); Generate sinc1 filter with sinc1=ones(1,osr1). After that a sinc2 filter is created by sinc2=conv(sin1,sinc1). Generally a sincm+n filter is created by conv(sincm,sincn). Observe the filte characteristics with f_bode(0,sincx); After this decimation by factor dsr1 we use a lowpass to decimate in a second step by factor dsr2. This lowpass is significantly relaxed to the one decimating by factor dsr=dsr1ꞏdsr2. Task: Design a FSM model to build a 2-step decimation filter.

Page 147: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 147 -

10 Conclusions The reader learns in the hardware part of section 2 how to start the Terasic / Altera DE2 board and to program its Altera Cyclone II FPGA with VHDL using the Quartus II software. Some basic functions like reading out switches and controlling LEDs are introduced before learning how to read from and write to the board’s general-purpose input/output (GPIO) expansion headers. The school’s self-made DA2 daughter board contains some A/D and D/A converters: three DACs, a 9-level flash-ADC and an instrumentation amplifier. ΔΣ D/A conversion is possible with this board. DS2 grandchild board assembles A/D and D/A converters of DA2 board to form a ΔΣ modulation system for A/D conversion. Section 3 introduces a ΔΣ A/D and D/A conversion model as matter of modeling and investigation. Section 4 trains advanced VHDL modeling giving the student the skill to cope with such a project. Section 5 introduces theory of signal conditioning. Section 6 introduces theory of quantization. Section 7 applies the knowledge from section 5 and 6 to construct high-level Matlab models. Section 8 describes Sampling Rate Issues on a high-level and theoretical point of view, Section 9 breaks Sampling Rate Issues down to a circuit designer’s FSM point of view,. The following color code is used: Black text is addressed to all readers Grey text is useful information (e.g. concerning mathematics) without relevance for exams. Green text is addressed to ADA students, learning A/D and D/A converters. Pink is addressed to students learning signal processing theory, Brown text is addressed to RED students learning the art of digital circuit design.

Page 148: Circuit and System Design for DSP - OTH Regensburg · - 2 - Circuit and System Design for DSP ... Blue text indicates exercises / solutions. ... of Quartus supporting Cyclone II FPGAs

Prof. M. Schubert Circuit and System Design for DSP Ostbayerische TH Regensburg Principles and Practices Using VHDL and Matlab

- 148 -

11 References [1] Available: http://www.terasic.com [2] Available: http://www.altera.com. [3] Availablein Oct 2017 : ftp://ftp.altera.com/up/pub/Webdocs/DE2_UserManual.pdf. [4] Available Oct 2017: http://www.cs.columbia.edu/~sedwards/classes/2008/4840/DE2_schematics.pdf. [5] Avalable Oct. 2017 : http://www.johnloomis.org/altera/DE2/DE2_pin_assignments.csv. [6] OTH Regensburg, internal CIP pool system drive K:\Sb\ [7] https://hps.hs-regensburg.de/~scm39115/homepage/education/courses/ada/ada.htm,

User="student", Password="studaccept". [8] https://hps.hs-regensburg.de/~scm39115/homepage/education/courses/sc/sc.htm,

User="student", Password="studaccept". [9] Available: https://hps.hs-regensburg.de/scm39115/homepage/education/courses/red/red.htm,

User="student", Password="studaccept". [10] HSR: k:\Sb\Software\Measurement&Test\TestToneGenerator (license for private use!) [11] Timo Esser, Test Tone generator, available: http://kostenlose.rbytes.net/test-tone-

generator_download/ [12] M. Schubert, “Analog-to-Digital and Digital-to-Analog Conversion”, OTH Regensburg.

Available: Homepage Prof. Schubert @ OTH Regensburg (https://hps.hs-regensburg.de/~scm39115/) Offered Education Courses and Laboratories A/D and D/A Convrsion (ADA), Nov. 2015.

[13] Available: [12] Chapter 4: Signals, Noise and Signal-to-Noise Ratio, 2015 [14] Lerch, Elektrische Messtechnik, Analoge, digitale und computergetützte Verfahren, 3. Auflage,

Springer Verlag, 2006. [15] E. B. Hogenauer, “An economical class of digital filters for decimation and interpolation”, IEEE

Transactions on Acoustics, Speech and Signal Processing, California, USA, 1981. [16] S. R. Norsworthy, R. Schreier, G. C. Temes, „Delta-Sigma Data Converters“, IEEE Press, 1996,

IEE Order Number PC3954, ISBN 0-7803-1045-4. [17] J. C. Candy, G. C. Temes, 1st paper in “ Oversampling Delta-Sigma Data Converters, Theory,

Design and Simulation”, IEEE Press, IEEE Order #: PC0274-1, ISBN 0-87942-285-8, 1991. [18] C. A. Leme, “Oversampling Interfaces for IC Sensors”, Physical Electronics Laboratory, ETH

Zurich, Diss. ETH Nr. 10416. [19] Available: [12] A/D and D/A Conversion (ADAC) Rerefence Manual. [20] Available: [12] A/D and D/A Conversion (ADAC) Project Using Matlab, Aux. Files.