首页资源分类FPGA/CPLD > FPGA Prototyping By Verilog Examples

FPGA Prototyping By Verilog Examples

已有 445110个资源

下载专区

上传者其他资源

文档信息举报收藏

标    签:FPGAVerilog

分    享:

文档简介

一个美籍华人写的书,写的非常通俗易懂, 一本入门Verilog和FPGA的好书

文档预览

FPGA PROTOTYPING BY VERILOG EXAMPLES Xilinx SpartanTM-3Version Pong P. Chu Cleveland State University WILEY A JOHN WILEY & SONS, INC., PUBLICATION This Page Intentionally Left Blank FPGA PROTOTYPING BY VERILOG EXAMPLES This Page Intentionally Left Blank FPGA PROTOTYPING BY VERILOG EXAMPLES Xilinx SpartanTM-3Version Pong P. Chu Cleveland State University WILEY A JOHN WILEY & SONS, INC., PUBLICATION Copyright O 2008 by John Wiley & Sons, Inc. All rights reserved. Published by John Wiley & Sons, Inc., Hoboken, New Jersey. Published simultaneously in Canada. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4470, or on the web at www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 1l 1 River Sheet, Hoboken, NJ 07030, (201) 748-601 1, fax (201) 7486008, or online at http:1lwww.wiley.co1n/golpermission. Limit of LiabilitylDisclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose. No warranty may be created or extended by sales representatives or written sales materials. The advice and strategies contained herein may not be suitable for your situation. You should consult with a professional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages. For general information on our other products and services or for technical support, please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (3 17) 5723993 or fax (317) 572-4002. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic format. For information about Wiley products, visit our web site at www.wiley.com. Library of Congress Cataloging-in-Publication Data: Chu, Pong P., 1959- FPGA prototyping by Verilog examples 1 Pong P. Chu. p. cm. Includes index. ISBN 978-0-470-18532-2 (cloth) 1. Field programmable gate arrays-Design and construction. 2. Prototypes, Engineering. 3.Verilog (Computer hardware description language) I. Title. TK7895.G36C484 2008 621.39'54~22 2008003732 Printed in the United States of America. In memory of myfathel; Chia Chi Chu This Page Intentionally Left Blank CONTENTS Preface Acknowledgments PART I BASIC DIGITAL CIRCUITS 1 Gate-level combinational circuit 1.1 Introduction 1.2 General description 1.3 Basic lexical elements and data types 1.3.1 Lexical elements 1.4 Data types 1.4.1 Four-value system 1.4.2 Data type groups 1.4.3 Number representation 1.4.4 Operators 1.5 Program skeleton 1.5.1 Port declaration 1S . 2 Program body 1.5.3 Signal declaration 1.5.4 Another example 1.6 Structural description 1.7 Testbench xxi xxvii 1 1 2 3 3 4 4 4 5 5 5 6 7 7 8 9 12 vii viii CONTENTS 1.8 Bibliographic notes 14 1.9 Suggested experiments 14 1.9.1 Code for gate-level greater-than circuit 14 1.9.2 Code for gate-level binary decoder 14 2 Overview of FPGA and EDA software 15 2.1 Introduction 15 2.2 FPGA 15 2.2.1 Overview of a general FPGA device 15 2.2.2 Overview of the Xilinx Spartan3 devices 17 2.3 Overview of the Digilent S3 board 17 2.4 Development flow 19 2.5 Overview of the Xilinx ISE project navigator 21 2.6 Short tutorial on ISE project navigator 24 2.6.1 Create the design project and HDL codes 25 2.6.2 Create a testbench and perform the RTL simulation 26 2.6.3 Add a constraint file and synthesize and implement the code 26 2.6.4 Generate and download the configuration file to an FPGA device 29 2.7 Short tutorial on the ModelSim HDL simulator 31 2.8 Bibliographic notes 35 2.9 Suggested experiments 36 2.9.1 Gate-level greater-than circuit 36 2.9.2 Gate-level binary decoder 36 3 RT-level cornbinationaI circuit 39 3.1 Introduction 39 3.2 Operators 39 3.2.1 Arithmetic operators 41 3.2.2 Shifi operators 41 3.2.3 Relational and equality operators 42 3.2.4 Bitwise, reduction, and logical operators 42 3.2.5 Concatenation and replication operators 43 3.2.6 Conditional operators 44 3.2.7 Operator precedence 44 3.2.8 Expression bit-length adjustment 45 3.2.9 Synthesis of z and x values 46 3.3 Always block for a combinational circuit 48 3.3.1 Basic syntax and behavior 48 3.3.2 Procedural assignment 49 3.3.3 Variable data types 49 3.3.4 Simple examples 49 CONTENTS ix 3.4 If statement 51 3.4.1 Syntax 51 3.4.2 Examples 52 3.5 Case statement 54 3.5.1 Syntax 54 3.5.2 Examples 54 3.5.3 The casez and casex statements 56 3.5.4 The full case and parallel case 56 3.6 Routing structure of conditional control constructs 57 3.6.1 Priority routing network 57 3.6.2 Multiplexing network 59 3.7 General coding guidelines for an always block 60 3.7.1 Common errors in combinational circuit codes 60 3.7.2 Guidelines 63 3.8 Parameter and constant 64 3.8.1 Constant 64 3.8.2 Parameter 65 3.8.3 Use of parameters in Verilog-I995 67 3.9 Design examples 67 3.9.1 Hexadecimal digit to seven-segment LED decoder 67 3.9.2 Sign-magnitude adder 71 3.9.3 Barrel shifter 73 3.9.4 Simplified floating-point adder 75 3.10 Bibliographic notes 80 3.1 1 Suggested experiments 80 3.11.1 Multifunction barrel shifter 80 3.1 1.2 Dual-priority encoder 80 3.1 1.3 BCD incrementor 81 3.1 1.4 Floating-point greater-than circuit 81 3.1 1.5 Floating-point and signed integer conversion circuit 81 3.1 1.6 Enhanced floating-point adder 81 4 Regular Sequential Circuit 83 4.1 Introduction 83 4.1.1 D FF and register 83 4.1.2 Synchronous system 84 4.1.3 Code development 85 4.2 HDL code of the FF and register 86 4.2.1 D FF 86 4.2.2 Register 89 4.2.3 Register file 90 4.2.4 Storage components in a Spartan-3 device~Y"li""'pecific 91 X CONTENTS 4.3 Simple design examples 91 4.3.1 Shift register 91 4.3.2 Binary counter and variant 93 4.4 Testbench for sequential circuits 96 4.5 Case study 99 4.5.1 LED time-multiplexing circuit 99 4.5.2 Stopwatch 107 4.5.3 FIFO buffer 110 4.6 Bibliographic notes 115 4.7 Suggested experiments 115 4.7.1 Programmable square-wave generator 115 4.7.2 PWM and LED dimmer 115 4.7.3 Rotating square circuit 116 4.7.4 Heartbeat circuit 116 4.7.5 Rotating LED banner circuit 116 4.7.6 Enhanced stopwatch 116 4.7.7 Stack 117 5 FSM 119 5.1 Introduction 119 5.1.1 Mealy and Moore outputs 119 5.1.2 FSM representation 120 5.2 FSM code development 122 5.3 Design examples 125 5.3.1 Rising-edge detector 125 5.3.2 Debouncing circuit 130 5.3.3 Testing circuit 133 5.4 Bibliographic notes 135 5.5 Suggested experiments 135 5.5.1 Dual-edge detector 135 5.5.2 Alternative debouncing circuit 135 5.5.3 Parking lot occupancy counter 136 6 FSMD 139 6.1 Introduction 139 6.1.1 Single RT operation 139 6.1.2 ASMDchart 140 6.1.3 Decision box with a register 141 6.2 Code development of an FSMD 143 6.2.1 Debouncing circuit based on RT methodology 144 6.2.2 Code with explicit data path components 146 CONTENTS xi 6.2.3 Code with implicit data path components 148 6.2.4 Comparison i50 6.2.5 Testing circuit 152 6.3 Design examples 153 6.3.1 Fibonacci number circuit 153 6.3.2 Division circuit 157 6.3.3 Binary-to-BCD conversion circuit 160 6.3.4 Period counter 164 6.3.5 Accurate low-frequency counter 167 6.4 Bibliographic notes 170 6.5 Suggested experiments 170 6.5.1 Alternative debouncing circuit 170 6.5.2 BCD-to-binary conversion circuit 171 6.5.3 Fibonacci circuit with BCD I/O: design approach I 171 6.5.4 Fibonacci circuit with BCD I/O: design approach 2 171 6.5.5 Auto-scaled low-frequency counter 172 6.5.6 Reaction timer 172 6.5.7 Babbage difference engine emulation circuit 173 7 Selected Topics of Verilog 175 7.1 Blocking versus nonblocking assignment 175 7.1.1 Overview 175 7.1.2 Combinational circuit 177 7.1.3 Memory element 179 7.1.4 Sequential circuit with mixed blocking and nonblocking assignments 180 7.2 Alternative coding style for sequential circuit 182 7.2.1 Binary counter 182 7.2.2 FSM 185 7.2.3 FSMD 186 7.2.4 Summary 188 7.3 Use of the signed data type 188 7.3.1 Overview 188 7.3.2 Signed number in Verilog-I995 189 7.3.3 Signed number in Verilog-2001 190 7.4 Use of function in synthesis 191 7.4.1 Overview 191 7.4.2 Examples 192 7.5 Additional constructs for testbench development 193 7.5.1 Always block and initial block 194 7.5.2 Procedural statements 194 7.5.3 Timing control 196 Xii CONTENTS 7.5.4 Delay control 196 7.5.5 Event control 197 7.5.6 Wait statement 197 7.5.7 Timescale directive 197 7.5.8 System functions and tasks 198 7.5.9 User-defined functions and tasks 202 7.5.10 Example of a comprehensive testbench 204 7.6 Bibliographic notes 210 7.7 Suggested experiments 210 7.7.1 Shift register with blocking and nonblocking assignments 210 7.7.2 Alternative coding style for BCD counter 21 1 7.7.3 Alternative coding style for FIFO buffer 21 1 7.7.4 Alternative coding style for Fibonacci circuit 21 1 7.7.5 Dual-mode comparator 21 1 7.7.6 Enhanced binary counter monitor 212 7.7.7 Testbench for FIFO buffer 212 PART II 110MODULES 8 UART 215 8.1 Introduction 215 8.2 UART receiving subsystem 216 8.2.1 Oversampling procedure 216 8.2.2 Baud rate generator 217 8.2.3 UART receiver 217 8.2.4 Interface circuit 220 8.3 UART transmitting subsystem 223 8.4 Overall UART system 226 8.4.1 Complete UART core 226 8.4.2 UART verification configuration 228 8.5 Customizing a UART 230 8.6 Bibliographic notes 232 8.7 Suggested experiments 232 8.7.1 Full-featured UART 232 8.7.2 UART with an automatic baud rate detection circuit 233 8.7.3 UART with an automatic baud rate and parity detection circuit 233 8.7.4 UART-controlled stopwatch 233 8.7.5 UART-controlled rotating LED banner 234 9 PS2 Keyboard 235 9.1 Introduction 235 9.2 PS2 receiving subsystem 236 9.2.1 Physical interface of a PS2 port 9.2.2 Device-to-host communication protocol 9.2.3 Design and code 9.3 PS2 keyboard scan code 9.3.1 Overview of the scan code 9.3.2 Scan code monitor circuit 9.4 PS2 keyboard interface circuit 9.4.1 Basic design and HDL code 9.4.2 Verification circuit 9.5 Bibliographic notes 9.6 Suggested experiments 9.6.1 Alternative keyboard interface I 9.6.2 Alternative keyboard interface I1 9.6.3 PS2 receiving subsystem with watchdog timer 9.6.4 Keyboard-controlled stopwatch 9.6.5 Keyboard-controlled rotating LED banner 10 PS2 Mouse 10.1 Introduction 10.2 PS2 mouse protocol 10.2.1 Basic operation 10.2.2 Basic initialization procedure 10.3 PS2 transmitting subsystem 10.3.1 Host-to-PS2-device communication protocol 10.3.2 Design and code 10.4 Bidirectional PS2 interface 10.4.1 Basic design and code 10.4.2 Verification circuit 10.5 PS2 mouse interface 10.5.1 Basic design 10.5.2 Testing circuit 10.6 Bibliographic notes 10.7 Suggested experiments 10.7.1 Keyboard control circuit 10.7.2 Enhanced mouse interface 10.7.3 Mouse-controlled seven-segment LED display 11 External SRAM 11.1 Introduction 1 1.2 Specification of the IS6 I LV25616AL SRAM 1 1.2.1 Block diagram and I/O signals CONTENTS xiii 236 236 236 240 240 24 1 244 244 246 248 248 248 249 249 249 249 251 25 1 252 252 252 253 253 254 259 259 260 263 263 265 266 266 267 267 267 269 269 270 270 XiV CONTENTS 11.2.2 Timing parameters 270 1 1.3 Basic memory controller 274 11.3.1 Block diagram 274 11.3.2 Timing requirement 275 11.3.3 Register file versus SRAM 276 1 1.4 A safe design 276 11.4.1 ASMD chart 276 1 1.4.2 Timing analysis 277 11.4.3 HDL implementation 278 11.4.4 Basic testing circuit 28 1 11.4.5 Comprehensive SRAM testing circuit 283 1 1.5 More aggressive design 288 11.5.1 Timing issues 288 11S . 2 Alternative design I 288 11S.3 Alternative design I1 290 11S.4 Alternative design I11 291 1 1S.5 Advanced FPGA featuresXiLinZspecific 293 1 1.6 Bibliographic notes 294 11.7 Suggested experiments 294 11.7.1 Memory with a 512K-by-16 configuration 294 11.7.2 Memory with a 1M-by-8 configuration 295 11.7.3 Memory with an 8M-by-1 configuration 295 1 1.7.4 Expanded memory testing circuit 295 11.7.5 Memory controller and testing circuit for alternative design I 295 11.7.6 Memory controller and testing circuit for alternative design I1 295 11.7.7 Memory controller and testing circuit for alternative design I11 295 1 1.7.8 Memory controller with DCM 295 11.7.9 High-performance memory controller 296 12 Xilinx Spartan3 Specific Memory 297 12.1 Introduction 297 12.2 Embedded memory of Spartan-3 device 297 12.2.1 Overview 297 12.2.2 Comparison 298 12.3 Method to incorporate memory modules 298 12.3.1 Memory module via HDL component instantiation 299 12.3.2 Memory module via Core Generator 299 12.3.3 Memory module via HDL inference 3 00 12.4 HDL templates for memory inference 300 12.4.1 Single-port RAM 3 00 12.4.2 Dual-port RAM 303 12.4.3 ROM 305 CONTENTS XV 12.5 Bibliographic notes 12.6 Suggested experiments 12.6.1 Block-RAM-based FIFO 12.6.2 Block-RAM-based stack 12.6.3 ROM-based sign-magnitude adder 12.6.4 ROM-based sin(z) hnction 12.6.5 ROM-based sin(z) and COS(T) functions 13 VGA controller I: graphic 13.1 Introduction 13.1.1 Basic operation of a CRT 13.1.2 VGA port of the S3 board 13.1.3 Video controller 13.2 VGA synchronization 13.2.1 Horizontal synchronization 13.2.2 Vertical synchronization 13.2.3 Timing calculation of VGA synchronization signals 13.2.4 HDL implementation 13.2.5 Testing circuit 13.3 Overview of the pixel generation circuit 13.4 Graphic generation with an object-mapped scheme 13.4.1 Rectangular objects 13.4.2 Non-rectangular object 13.4.3 Animated object 13.5 Graphic generation with a bit-mapped scheme 13.5.1 Dual-port RAM implementation 13.5.2 Single-port RAM implementation 13.6 Bibliographic notes 13.7 Suggested experiments 13.7.1 VGA test pattern generator 13.7.2 SVGA mode synchronization circuit 13.7.3 Visible screen adjustment circuit 13.7.4 Ball-in-a-box circuit 13.7.5 Two-balls-in-a-box circuit 13.7.6 Two-player pong game 13.7.7 Breakout game 13.7.8 Full-screen dot trace 13.7.9 Mouse pointer circuit 13.7.10 Small-screen mouse scribble circuit 13.7.11 Full-screen mouse scribble circuit 14 VGA controller II: text 307 307 307 307 307 308 308 309 309 309 31 1 31 1 3 12 312 314 315 315 318 3 19 319 320 325 326 332 332 337 337 337 337 338 338 338 339 339 339 339 340 340 340 341 xvi CONTENTS 14.1 Introduction 34 1 14.2 Text generation 34 1 14.2.1 Character as a tile 34 1 14.2.2 Font ROM 342 14.2.3 Basic text generation circuit 344 14.2.4 Font display circuit 345 14.2.5 Font scaling 347 14.3 Full-screen text display 348 14.4 The complete pong game 352 14.4.1 Text subsystem 352 14.4.2 Modified graphic subsystem 358 14.4.3 Auxiliary counters 359 14.4.4 Top-level system 36 1 14.5 Bibliographic notes 366 14.6 Suggested experiments 366 14.6.1 Rotating banner 366 14.6.2 Underline for the cursor 366 14.6.3 Dual-mode text display 366 14.6.4 Keyboard text entry 366 14.6.5 UART terminal 366 14.6.6 Square-wave display 367 14.6.7 Simple four-trace logic analyzer 367 14.6.8 Complete two-player pong game 368 14.6.9 Complete breakout game 368 PART 111 PICOBLAZE MICRO CONTROLLER^^^^^^ 15 PicoBlaze Overview 371 15.1 Introduction 37 1 15.2 Customized hardware and customized software 372 15.2.1 From special-purpose FSMD to general-purpose microcontroller 372 15.2.2 Application of microcontroller 374 15.3 Overview of PicoBlaze 374 15.3.1 Basic organization 374 15.3.2 Top-level HDL modules 376 15.4 Development flow 377 15.5 Instruction set 377 15.5.1 Programming model 379 15.5.2 Instruction format 379 15.5.3 Logical instructions 380 15.5.4 Arithmetic instructions 381 15.5.5 ComDare and test instructions 3 82 15.5.6 Shift and rotate instructions 15.5.7 Data movement instructions 15.5.8 Program flow control instructions 15.5.9 Interrupt related instructions 15.6 Assembler directives 15.6.1 The KCPSM3 directives 15.6.2 The PBlazeIDE directives 15.7 Bibliographic notes 16 PicoBlaze Assembly Code Development 16.1 Introduction 16.2 Useful code segments 16.2.1 KCPSM3 conventions 16.2.2 Bit manipulation 16.2.3 Multiple-byte manipulation 16.2.4 Control structure 16.3 Subroutine development 16.4 Program development 16.4.1 Demonstration example 16.4.2 Program documentation 16.5 Processing of the assembly code 16.5.1 Compiling with KCSPM3 16.5.2 Simulation by PBlazeIDE 16.5.3 Reloading code via the JTAG port 16.5.4 Compiling by PBlazeIDE 16.6 Syntheses with PicoBlaze 16.7 Bibliographic notes 16.8 Suggested experiments 16.8.1 Signed multiplication 16.8.2 Multi-byte multiplication 16.8.3 Barrel shift function 16.8.4 Reverse function 16.8.5 Binary-to-BCD conversion 16.8.6 BCD-to-binary conversion 16.8.7 Heartbeat circuit 16.8.8 Rotating LED circuit 16.8.9 Discrete LED dimmer 17 PicoBlaze 110 Interface 17.1 Introduction 17.2 Output port CONTENTS xvii 383 384 386 389 390 390 390 391 393 393 393 393 394 395 396 398 399 400 404 406 406 407 410 410 41 1 412 412 412 412 413 413 413 413 413 413 413 415 415 416 XViii CONTENTS 17.2.1 Output instruction and timing 416 17.2.2 Output interface 417 17.3 Input port 418 17.3.1 Input instruction and timing 418 17.3.2 Input interface 419 17.4 Square program with a switch and seven-segment LED display interface 42 1 17.4.1 Output interface 42 1 17.4.2 Input interface 422 17.4.3 Assembly code development 424 17.4.4 HDL code development 43 1 17.5 Square program with a combinational multiplier and UART console 434 17.5.1 Multiplier interface 434 17.5.2 UART interface 435 17.5.3 Assembly code development 436 17.5.4 HDL code development 446 17.6 Bibliographic notes 449 17.7 Suggested experiments 449 17.7.1 Low-frequency counter I 449 17.7.2 Low-frequency counter I1 449 17.7.3 Auto-scaled low-frequency counter 449 17.7.4 Basic reaction timer with a software timer 449 17.7.5 Basic reaction timer with a hardware timer 450 17.7.6 Enhanced reaction timer 450 17.7.7 Small-screen mouse scribble circuit 450 17.7.8 Full-screen mouse scribble circuit 450 17.7.9 Enhanced rotating banner 450 17.7.10Pong game 450 17.7.11 Text editor 45 1 18 PicoBlaze Interrupt Interface 453 18.1 Introduction 453 18.2 Interrupt handling in PicoBlaze 453 18.2.1 Software processing 454 18.2.2 Timing 455 18.3 External interface 456 18.3.1 Single interrupt request 456 18.3.2 Multiple interrupt requests 456 18.4 Software development considerations 457 18.4.1 Interrupt as an alternative scheduling scheme 457 18.4.2 Development of an interrupt service routine 458 18.5 Design example 458 18.5.1 Interrupt interface 458 CONTENTS xix 18.5.2 Interrupt service routine development 459 18.5.3 Assembly code development 459 18.5.4 HDL code development 46 1 18.6 Bibliographic notes 464 18.7 Suggested experiments 464 18.7.1 Alternative timer interrupt service routine 464 18.7.2 Programmable timer 464 18.7.3 Set-button interrupt service routine 465 18.7.4 Interrupt interface with two requests 465 18.7.5 Four-request interrupt controller 465 Appendix A: Sample Verilog templates 467 A. 1 Numbers and operators 467 A. 1.1 Sized and unsized numbers 467 A. 1.2 Operators 468 A.2 General Verilog constructs 469 A.2.1 Overall code structure 469 A.2.2 Component instantiation 470 A.3 Routing with conditional operator and if and case statements 470 A.3.1 Conditional operator and if statement 470 A.3.2 Case statement 47 1 A.4 Combinational circuit using an always block 472 A.4.1 Always block without default output assignment 472 A.4.2 Always block with default output assignment 472 A S Memory Components 473 A.5.1 Register template 473 A.5.2 Register file 474 A.6 Regular sequential circuits 474 A.7 FSM 476 A.8 FSMD 478 A.9 S3 board constraint file (s3.ucf) 480 References 485 Topic Index 487 This Page Intentionally Left Blank PREFACE HDL (hardware description language) and FPGA (field-programmable gate array) devices allow designers to quickly develop and simulate a sophisticated digital circuit, realize it on a prototyping device, and verify operation of the physical implementation. As these technologies mature, they have become mainstream practice. We can now use a PC and an inexpensive FPGA prototyping board to construct a complex and sophisticated digital system. This book uses a "learning by doing" approach and illustrates the FPGA and HDL development and design process by a series of examples. A wide range of examples is included, from a simple gate-level circuit to an embedded system with an 8-bit soft-core microcontroller and customized 110 peripherals. All examples can be synthesized and physically tested on a prototyping board. Focus and audience FOCUS The main focus of this book is on the effective derivation of hardware, not the syntax of HDL. Instead of explaining every language construct, the book focuses on a small synthesizable subset and uses about a dozen code templates to provide the skeletons of various types of circuits. These templates are general and can easily be integrated to construct a large, complex system. Although this approach limits the "freedom" of syntactic expression, it will not prevent us from developing innovative hardware architecture. Because of the generality and flexibility of HDL, the same circuit can usually be described by a wide variety of language constructs and coding styles. Many of these codes are intended for modeling. They may lead to unnecessarily complex hardware implementation and sometimes cannot be synthesized at all. The template approach actually forces us to think more about hardware and develop a good coding practice for synthesis. Since we are xxii PREFACE more interested in hardware, it is more beneficial to spend time on developing 10 different hardware architectures with the same code template rather than describing the same circuit with 10 different versions of codes. There are two popular HDLs, VHDL and Verilog. Both languages are used widely and are IEEE standards. This book uses Verilog, and a separate book with a similar title uses VHDL. Despite the drastic syntactic differences in the two languages, their capabilities are very similar, particularly for our purposes. After we comprehend the design practice and coding methodology in one language, learning the other language is rather straightforward. Although the book is intended for beginning designers, the examples follow strict design guidelines and prepare readers for future endeavors. The coding and design practice is "forward compatible," which means that: The same practice can be applied to large design in the future. The same practice can aid other system development tasks, including simulation, timing analysis, verification, and testing. The same practice can be applied to ASIC technology and different types of FPGA devices. The code can be accepted by synthesis software from different vendors. In summary, the book is a hands-on, hardware-centric text that involves minimal HDL overhead and follows good design and coding practice to achieve maximalforward comparability. Audience and perquisites The book contains three major parts: basic digital circuits, peripheral modules, and embedded microcontroller. The intended audience is students in an introductory or advanced digital system design course as well as practicing engineers who wish to learn FPGA- and HDL-based development. For the materials in the first two parts, readers need to have a basic knowledge of digital systems, usually a required course in electrical engineering and computer engineering curricula. For the materials in the third part, prior exposure to assembly language programming will be helpful. Logistics Although a major goal of this book is to teach readers to develop software-independent and device-neutral HDL codes, we have to choose a software package and a prototyping board to synthesize and implement the design examples. The synthesis software and FPGA devices from Xilinx, a leading manufacture in this area, are used in the book. Software The synthesis software used in the book is the Web version of the Xilinx ISE package. The functionality of this version is similar to that of the full version but supports only a limited number of devices. Most introductory development boards use FPGA devices from the inexpensive Spartan-3 family. Since the Web version supports the Spartan-3 device, it fits our needs. The simulation software used in the book is the starter version of Mentor Graphics' ModelSim XE 111package. It is a customized edition of ModelSim. Both software packages are free and can be downloaded from Xilinx's Web site. FPGA prototyping board This book is prepared to be used with several entry-level FPGA prototyping boards manufactured by Digilent Inc., including the Spartan-3 Starter, Nexys-2, and Basys boards, all of which contain a Spartan-313E FPGA device and have similar 110peripherals. The design examples in the book are based on the Spartan-3 Starter board (or simply the S3 board), but most of them can be used directly on other boards as well. The applicability of the HDL codes is summarized below. Spartan3 Starter (S3) board. The S3 board contains all the peripherals and no additional accessory module is needed. All HDL codes and discussions can be applied to this board directly. Nexys-2 board. The Nexys-2 board is a newer board, which contains a larger FPGA device and a larger memory chip. Its peripherals are similar to those on the S3 board. There are two differences. First, the "color depth" of its VGA interface is expanded from 3 bits to 8 bits. Thus, the output of the VGA interface circuits discussed in Chapters 13 and 14 needs to be modified accordingly. Second, the Nexys-2 board contains a more sophisticated external memory device. Although the device can be configured as an asynchronous SRAM, the timing characteristics are different from those of the S3 board's memory device, and thus the HDL codes for the memory controller in Chapter 1 1 cannot be used directly. However, the same design principle can be applied to construct a new controller. Basys board. The Basys board is a simpler board. It lacks the RS-232 connector. To implement the UART module and the serial interface discussed in Chapter 8, we need Digilent's RS-232 converterperipheralmodule. The Basys board has no external memory devices, and thus the discussion of the memory controller in Chapter 11 is not applicable. Other FPGA boards. Most peripherals discussed in this book are de facto industrial standards, and the corresponding HDL codes can be used as long as a board provides proper analog interface circuits and connectors. Except for the Xilinx-specific portions, the codes can be applied to the boards based on the FPGA devices from other manufacturers as well. PC Accessories The design examples include interfaces to several PC peripheral devices. A keyboard, a mouse, and a VGA monitor are required for the respective modules, and a "straight-through" serial cable (the most commonly used type) is required for the UART module. These accessories are widely available and can probably be obtained from an old PC. Book organization The book is divided into three major parts. Part I introduces the elementary HDL constructs and their hardware counterparts, and demonstrates the construction of a basic digital circuit with these constructs. It consists of six chapters: Chapter 1 describes the skeleton of an HDL program, basic language syntax, and logical operators. Gate-level combinational circuits are derived with these language constructs. Chapter 2 provides an overview of an FPGA device, prototyping board, and development flow. The development process is demonstrated by a tutorial on Xilinx ISE synthesis software and a tutorial on Mentor Graphics ModelSim simulation software. Chapter 3 introduces HDL's relational and arithmetic operators and routing constructs. These correspond to medium-sized components, such as comparators, adders, and multiplexers. Module-level combinational circuits are derived with these language constructs. xxiv PREFACE Chapter 4 covers the codes for memory elements and the construction of "regular" sequential circuits, such as counters and shift registers, in which the state transitions exhibit a regular pattern. Chapter 5 discusses the construction of a finite state machine (FSM), which is a sequential circuit whose state transitions do not exhibit a simple, regular pattern. Chapter 6 presents the construction of an FSM with data path (FSMD). The FSMD is used to implement register transfer (RT) methodology, in which the system operation is described by data transfers and manipulations among registers. Chapter 7 discusses several more advanced topics on language constructs and coding techniques and introduces the development of more sophisticated testbenches. This chapter can be skipped without affecting the remaining chapters. Part I1 applies the techniques from Part I to design an array of peripheral modules for the prototyping board. Each chapter covers the development, implementation, and verification of an individual peripheral. These modules can be incorporated to a larger project. Part I1 consists of seven chapters: Chapter 8 discusses the design of a universal asynchronous receiver and transmitter (UART), which provides a serial link to receive and transmit data via the prototyping board's RS-232 port. Chapter 9 covers the design of a keyboard interface, which reads scan code from a keyboard. The keyboard is connected via the prototyping board's PS2 port. Chapter 10covers the design o f a mouse interface, which obtains the button and movement information from a mouse. The mouse is also connected via the prototyping board's PS2 port. Chapter 11 discusses the implementation and timing issues of a memory controller. The controller is used to read data from and write data to the two static random access memory (SRAM) devices on the S3 board. Chapter 12 discusses the inference and application of Spartan-3 device-specific components. The focus is on the FPGA's internal memory blocks. Chapter 13 presents the design and implementation of a video controller. The discussion covers the generation of video synchronization signals and shows the construction of simple bit- and object-mapped graphical interfaces. The monitor is connected to the prototyping board's VGA port. Chapter 14 continues development of the video controller. The discussion illustrates the construction of text interface and general tile-mapped scheme. Part 111 introduces an FPGA-based soft-core microcontroller, known as PicoBlaze, and demonstrates the integration of a general-purpose processor and customized circuit. It includes four chapters: Chapter 15 provides an overview of the organization and instruction set of PicoBlaze. Chapter 16 introduces the basic assembly programming and provides an overview of the development process. Chapter 17 discusses PicoBlaze's 110 feature and illustrates the procedure to derive customized circuits to interface other 110 peripherals. Chapter 18 discusses PicoBlaze's interrupt capability and demonstrates the construction of a customized interrupt-handling circuit. In addition to regular chapters, the appendix summarizes and lists all code templates. speciaml a r k s x i l i n x s p e c i f i c We use two special paragraph marks in the book: one for a Xilinx-specijic featzrre and one for Verilog-1995 constructs. While the examples PREFACE XXV described in the book are implemented on a Xilinx-based prototyping board and the codes are synthesized by Xilinx ISE software, we try to make the HDL codes as device independent and software neutral as possible. Most discussions and codes can be applied to different target devices and different synthesis software as well. However, certain codes or device features are unique to Xilinx ISE software or Spartan-3 FPGA devices. We use the Xilinx spec@ superscript, as in the heading of this section, to indicate that the discussion in the corresponding section or chapter is unique to Xilinx. Similarly, we use marginal notes, as shown on the outer edge, to indicate that the discussion in a paragraph is unique to Xilinx. This note indicates that the code or design is no Xilinx longer portable and needs to be revised when a different software package or target device specific is used. The Verilog language was first ratified in 1995 (referred to as Verilog-1995) and then revised in 2001 (referred to as Verilog-2001). Many useful enhancements are added in the revised version. We use Verilog-2001 in this book. If a language construct differs in the two versions, we describe the old syntax briefly in a separate paragraph and use a marginal note, as shown on the outer edge, for this type of discussion. It indicates "for your information" FYI and the materials are included to help readers understand the older Verilog codes. Instructional use The book can be a good companion text for an introductory digital systems course or an advanced project-oriented course. In an introductory digital systems course, the book supplies the lab portion of the curriculum. The chapters in Part I basically follow the sequence of a typical curriculum and can be presented along with regular lectures. One or two peripheral modules can be selected as case studies, and corresponding experiments can be used as term projects. In an advanced project-oriented course, the book provides a base for independent projects. The materials in Part I should be treated as an overview or refresher, which provides a general background on HDL, synthesis, and FPGA boards. Some modules in Part I1 can be used to demonstrate the design of more complex circuits. These modules can also be considered as building blocks (i.e., IPS)or subsystems to be integrated into final projects. The PicoBlaze microcontroller discussed in Part 111can be used as a general-purpose processor if an embedded-system type of project is desired. Companion Web site An accompanying Web site (http://acadernic.csuohio.edu/chu~p/rtpl)rovides additional information, including the following materials: Errata Code templates HDL code listing and relevant files Links to synthesis and simulation software Links to referenced materials Additional project ideas Errata The book is self-prepared, which means that the author has produced all aspects of the text, including illustrations, tables, code listings, indexing, and formatting. As errors xxvi PREFACE are always bound to happen, the accompanying Web site provides an updated errata sheet and a place to report errors. Cleveland, Ol~io January 2008 ACKNOWLEDGMENTS The author would like to express his gratitude to Professor George L. Kramerich for his encouragement and help. The author also thanks John Wiley & Sons, Inc. for giving permission to use Figures 3.1, 3.2,4.2,4.10,4.11,6.5, and 7.2 from my text RTL Hardware Design Using VHDL: Coding for Eficiency, Portability, and Scalability, and Xilinx, Inc. for giving permission to use Figures 2.3 and 9.3 from the Spartan-3 Starter Kit Board User Guide. All trademarks used or referred to in this book are the property oftheir respective owners. P. P. Chu This Page Intentionally Left Blank PART I BASIC DIGITAL CIRCUITS This Page Intentionally Left Blank CHAPTER 1 GATE-LEVEL COMBINATIONAL CIRCUIT 1.I INTRODUCTION Verilog is a hardware description language. It was developed in the mid-1980s and later transferred to the IEEE (Institute of Electrical and Electronics Engineers). The language is formally defined by IEEE Standard 1364. The standard was ratified in 1995 (referred to as Verilog-1995)and revised in 200 1(referred to as Verilog-200 1). Many useful enhancements are added in the revised version. We use Verilog-2001 in this book. Verilog is intended for describing and modeling a digital system at various levels and is an extremely complex language. The focus of this book is on hardware design rather than the language. Instead of covering every aspect of Verilog, we introduce the key Verilog synthesis constructs by examining a collection of examples. Several advanced topics are examined further in Chapter 7 and detailed Verilog coverage may be explored through the sources listed in the bibliographic section at the end of the chapter. Although the syntax of Verilog is somewhat like that of the C language, its semantics (i.e., "meaning") is based on concurrent hardware operation and is totally different from the sequential execution of C. The subtlety of some language constructs and certain inherent non-deterministic behavior of Verilog can lead to difficult-to-detect errors and introduce a discrepancy between simulation and synthesis. The coding of this book follows a "bettersafe-than-buggy" philosophy. Instead of writing quick and short codes, the focus is on style and constructs that are clear and synthesizable and can accurately describe the desired hardware. FPGA Prototyping by Verilog Examples. By Pong P.Chu Copyright @ 2008 John Wiley & Sons, Inc. 2 GATE-LEVEL COMBINATIONAL CIRCUIT Table 1.1 Truth table of 1-bit equality comparator input output i O i l eq In this chapter, we use a simple comparator to illustrate the skeleton of a Verilog program. The description uses only logic operators and represents a gate-level combinational circuit, which is composed of simple logic gates. In Chapter 3, we cover the remaining Verilog operators and constructs and examine the register-transfer-level combinational circuits, which are composed of intermediate-sized components, such as adders, comparators, and multiplexers. 1.2 GENERAL DESCRIPTION Consider a I-bit equality comparator with two inputs, iO and il, and an output, eq. The eq signal is asserted when iO and il are equal. The truth table of this circuit is shown in Table 1.1. Assume that we want to use basic logic gates, which include not, and, or, and xor cells, to implement the circuit. One way to describe the circuit is to use a sum-of-products format. The logic expression is + eq = ,iO. i l i O 1 . ill One possible Verilog code is shown in Listing 1.1. We examine the language constructs and statements of this code in the following subsections. Listing 1.1 Gate-level implementation of a I-bit comparator module eql // I/O ports ( input wire iO, i l , 5 output wire eq ); // signal declaration wire PO, p l ; 10 // body // slim o f t w o p r o d u c t t e r m s a s s i g n eq = pO I p l ; // product terms I5 a s s i g n pO = - i O & - i l ; assign pl = i O & i l ; endmodule BASIC LEXICAL ELEMENTS AND DATA TYPES 3 Figure 1.1 Graphical representation of a comparator program. The best way to understand an HDL (hardware description language) program is to think in terms of hardware circuits. This program consists of three portions. The 110port portion describes the input and output ports ofthis circuit, which are i O and i l , and eq, respectively. The signal declaration portion specifies the internal connecting signals, which are pO and p l . The body portion describes the internal organization of the circuit. There are three continuous assignments in this code. Each can be thought of as a circuit part that performs certain simple logical operations. We examine the language constructs and statements of this code in the next section. The graphical representation of this program is shown in Figure 1.1. The three continuous assignments constitute the three circuit parts. The connections among these parts are specified implicitly by the signal and port names. 1.3 BASIC LEXICAL ELEMENTS AND DATA TYPES 1.3.1 Lexical elements Identifier An identifier gives a unique name to an object, such as e q l , iO, or PO. It is composed of letters, digits, the underscore character (-), and the dollar sign ($). $ is usually used with a system task or function. The first character of an identifier must be a letter or underscore. It is a good practice to give an object a descriptive name. For example, mem-addr-en is more meaningful than mae for a memory address enable signal. Verilog is a case-sensitive language. Thus, data-bus, Data-bus, and DATAEUS refer to three different objects. To avoid confusion, we should refrain from using the case to create different identifiers. Keywords K w o r d s are predefined identifiers that are used to describe language constructs. In this book. we use boldface type for Verilog keywords, such as module and wire in Listing 1. I . White space White space, which includes the space, tab, and newline characters, is used to separate identifiers and can be used freely in the Verilog code. We can use proper white spaces to format the code and make it more readable. Comments A comment is just for documentation purposes and will be ignored by software. Verilog has two forms of comments. A one-line comment starts with //, as in / / T h i s is a commeni A multiple-line comment is encapsulated between / * and */, as in 4 GATE-LEVELCOMBINATIONAL CIRCUIT /* This is comment line I . This is comment l i n e 2 . This is comment l i n e 3. */ In this book, we use italic type for comments, as in the examples above. 1.4 DATATYPES 1.4.1 Four-value system Four basic values are used in most data types: 0: for "logic Ow,or a false condition I: for "logic I", or a true condition z:for the high-impedance state x: for an unknown value The z value corresponds to the output of a tri-state buffer. The x value is usually used in modeling and simulation, representing a value that is not 0, I, or z, such as an uninitialized input or output conflict. 1.4.2 Data type groups Verilog has two main groups of data types: net and variable. Net group The data types in the net group represent the physical connections between hardware components. They are used as the outputs of continuous assignments and as the connection signals between different modules. The most commonly used data type in this group is wire. As the name indicates, it represents a connecting wire. The wire data type represents a 1-bit signal, as in wire pO, p l ; // two I - b i t s i g n a l s When a collection of signals is grouped into a bus, we can represent it using a onedimensional array (vector), as in wire [7:01 d a t a l , data2; // 8-bit data wire [31:01 addr; // 32- bit a d d r e s s wire [0:71 revers-data; // ascending index should be avoided While the index range can be either descending (as in 17:01) or ascending (as in 10:71), the former is preferred since the leftmost position (i.e., 7) corresponds to the MSB of a binary number. A two-dimensional array is sometimes needed to represent a memory. For example, a 32-by-4 memory (i.e., a memory has 32 words and each word is 4 bits wide) can be represented as wire [3:01 meal [31:0] ; // 32-by-4 memory The other data types in the net group imply certain logical behavior or functionality, such as wand (for wired-and connection) and supply0 (for circuit ground connection). We don't use these data types in this book. Verilog-2001 also allows the signed data type and this issue is discussed in Section 7.3. PROGRAM SKELETON 5 Variable group The data types in the variable group represent abstract storage in behavioral modeling and are used in the outputs of procedural assignments. There are five data types in this group: reg, integer, real, time, and realtime. The most commonly used data type in this group is reg and it can be synthesized. The inferred circuit may or may not contain physical storage components. The last three data types can only be used in modeling and simulation, and the use of the integer data type is discussed in Section 7.3. In Verilog-1995, the variable group is known as the register group. Since this term is the same for a physical hardware register (i.e., a collection of flip-flops), it is changed in FYI the Verilog-2001 documentation to avoid confusion. In this book, we use the term variable for the data type, and use the term register for the physical register circuit. 1.4.3 Number representation An integer constant in Verilog can be represented in various formats. Its general form is [sign] [size] ' [base] [value] The [base] term specifies the base of the number, which can be the following: b or B: binary o or 0: octal h or H: hexadecimal d or D: decimal The [value] term specifies the value of the number in the corresponding base. The underline character (-) can be included for clarity. The [size] term specifies the number of bits in a number. It is optional. The number is known as a sized tiumber when a [size] term exists and is known as an unsized number otherwise. Sized number A sized number specifies the number of bits explicitly. If the size of the value is smaller than the [size] term specified, zeros are padded in front to extend the number. except in several special cases. The z or x value is padded if the MSB of the value is z or x, and the MSB is padded if the signed data type is used. Several sized number examples are shown in the top portion of Table 1.2. Unsizednumber An unsized number omits the [size] term. Its actual size depends on the host computer but must be at least 32 bits. The ' [base] term can also be omitted if the number is in decimal format. Assume that 32 bits are used in the host machine. Several unsized number examples are shown in the bottom portion of Table 1.2. 1.4.4 Operators Verilog has about two dozen operators. For the gate-level description, we need only the - following bitwise operators: (not), & (and), I (or), and ^ (xor). These operators infer basic gate-level cells. Other operators are discussed in Section 3.2. 1.5 PROGRAM SKELETON As its name indicates, HDL is used to describe hardware. When we develop or examine a Verilog code, it is much easier to comprehend ifwe think in terms of6'hardwareorganization" number 'b11010 ' hee 1 -1 Table 1.2 Examples of sized and unsized numbers stored value comment 11010 11010 11010 11010 11010 00000 00001 zzzzz XXXXX xxx0l 11111 - ignored 0 extended 0 extended z extended x extended x extended 2's complement of 00001 00000000000000000000000000011010 0000000000000000000000001 1101110 00000000000000000000000000000001 1111111111111111i111111111111Iil extendedto32bits extended to 32 bits extended to 32 bits extended to 32 bits rather than "sequential algorithm." Most Verilog codes in this book follow the basic skeleton shown in Listing 1.1. It consists of three portions: I10 port declaration, signal declaration, and module body. 1.5.1 Port declaration The module declaration and port declaration of Listing 1.1 are module eql ( input wire iO, il, output wire eq 1; The 110 declaration specifies the modes, data types, and names of the module's I10 ports. The simplified syntax is module [module-name] ( [model [mode] ... [mode] [data-type] [data-type] [data-type] ); [port-names] , [port-names] , [port-names] The [mode] term can be input, output, or inout, which represent the input, output, or bidirectional port, respectively. Note that there is no comma in the last declaration. The [data-type] term can be omitted if it is wire. Verilog-1995port declaration In Verilog-1995, port names, modes, and data types FYI are declared separately. For example, the preceding port declaration becomes PROGRAM SKELETON 7 module eql (iO, il, eq); / / d e c l a r e mode input iO, il; output eq; // declare data type wire iO, il; wire eq; // only port names in brackets We do not use this format in this book. 1.5.2 Program body Unlike a program in the C language, in which the statements are executed sequentially, the program body of a synthesizable Verilog module can be thought of as a collection of circuit parts. These parts are operated in parallel and executed concurrently. There are several ways to describe a part: Continuous assignment "Always block" Module instantiation The first way to describe a circuit part is by using a continuous assignment. It is useful for simple combinational circuits. Its simplified syntax is a s s i g n [signal-name1 = [expression1 ; Each continuous assignment can be thought as a circuit part. The signal on the left-hand side is the output and the signals used in the right-hand-side expression are the inputs. The expression describes the function of this circuit. For example, consider the statement a s s i g n eq = pO I pl; It is a circuit that performs the or operation. When pO or p l changes its value, this statement is activated and the expression is evaluated. The new value is assigned to eq after the propagation delay. There are three continuous assignments in Listing 1.1 and they correspond to the three circuit parts shown in Figure 1.1. Since the assignments correspond to the circuit parts, the order of these statements does not matter. The second way to describe a circuit part is by using an always block. More abstract procedural assignments are used inside the always block and thus it can be used to describe more complex circuit operation. The always block is discussed in Section 3.3. The third way to describe a circuit part is by using module instantiation. Instantiation creates an instance of another module and allows us to incorporate predesigned modules as subsystems of the current module. Instantiation is discussed in Section 1.6. 1.5.3 Signal declaration The declaration portion specifies the internal signals and parameters used in the module. The internal signals can be thought of as the interconnecting wires between the circuit parts, as shown in Figure 1.1. The simplified syntax of signal declaration is [data-type] [port-names]; Two internal signals are declared in Listing 1.1: wire PO, pl; Implicit net In Verilog, an identifier does not need to be declared explicitly. If a dec- FYI laration is omitted, it is assumed to be an implicit net. The default data type is wire. We can remove the explicit declarations in Listing 1.1 and the simplified code is shown in Listing 1.2. Listing 1.2 Code with implicit net module e q l - i m p l i c i t ( input iO, i l , // no data type d e c l a r a t i o n output eq -. 1; // no internal signal declaration // prodzrct terms must be placed in f r o n t IU a s s i g n pO = - i O & - i l ; / / i m p l i c i t d e c l a r a t i o n assign pl = i O & i l ; //implicit declaration // sum of two product terms a s s i g n e q = pO I p l ; I< endmodule Although the code is more compact, it may introduce subtle errors of misspelled identifiers. For clarity and documentation, we always use explicit declarations in this book. 1.5.4 Another example We can expand the comparator to 2-bit inputs. Let the input be a and b and the output be aeqb. The aeqb signal is asserted when both bits of a and b are equal. The code is shown in Listing 1.3. Listing 1.3 Gate-level implementation of a 2-bit comparator module eq2-sop ( input wire [1:01 a , b , output wire aeqb -. 1 ; // internal signal declaration w i r e PO, p l , p 2 , p 3 ; 10 / / slim o f p r o d u c t t e r m s a s s i g n a e q b = pO I p l I p2 I p 3 ; // product terms a s s i g n pO = ( - a [ 1 1 & " b [ l l ) & ( - a [ 0 1 & - b [ 0 ] ) ; a s s i g n p l = ( - a [ l l & - b Ell) & ( a [ O l & bCO1) ; 15 a s s i g n p2 = (a111 & bC11) & (-aCOI & - b [ O I ) ; a s s i g n p3 = (aC11 & bC11) & (a[01 & b[Ol) ; endmodule The a and b ports are now declared as a two-element array. Derivation of the architecture body is similar to that of the 1-bit comparator. The PO, p i , p2, and p3 signals represent STRUCTURAL DESCRIPTION 9 aeqb Figure 1.2 Construction of a 2-bit comparator from 1-bit comparators. the results of the four product terms, and the final result, aeqb, is the logic expression in sum-of-products format. 1.6 STRUCTURAL DESCRIPTION A digital system is frequently composed of several smaller subsystems. This allows us to build a large system from simpler or predesigned components. Verilog provides a mechanism, known as module instantiation, to perform this task. This type of code is called structural description. An alternative to the design ofthe 2-bit comparator of Section 1.5.4 is to utilize previously constructed I -bit comparators as the building blocks. The diagram is shown in Figure 1.2, in which two 1-bit comparators are used to check the two individual bits and their results are fed to an and cell. The aeqb signal is asserted only when both bits are equal. The corresponding code is shown in Listing 1.4. Listing 1.4 Structural description of a 2-bit comparator module eq2 ( input wire[l:01 a , b , output wire aeqb 5 1; // internal signal declaration wire eO, e l ; lo // bodv // i n s t a n t i a t e two I-bit comparators e q l e q - b i t 0 - u n i t ( . i O ( a [O] ) , . i l ( b LO]) , . e q ( e 0 ) ) ; eql eq-bitl-unit (.e q ( e l ) , .iO(a[ll), .il(bC11)) ; 15 // a and b are eqrral i f i n d i v i d u a l b i t s are e q u a l a s s i g n a e q b = eO & e l ; endmodule - -- - -- The code includes two module instantiation statements. The simplified syntax of module instantiation is Xilinx specific FYI 10 GATE-LEVEL COMBINATIONAL CIRCUIT [module-name] [instance-name] ( . [port-name] ( [signal-name] ) , .[port-name] ([signal-name]), ... 1; The first portion of the statement specifies which component is used. The [modulename] term indicates the name of the module and the [instancename] term gives a unique id for an instance. The second portion is port connection, which indicates the connections between the 110 ports of an instantiated module (the lower-level module) and the external signals used in the current module (the higher-level module). This form of mapping is known as connection by name. The order of the port-name and signal-name pairs does not matter. In Listing 1.4, the first component instantiation statement is The eql is the module name defined in Listing 1.1. The port mapping reflects the connections shown in Figure 1.2. The component instantiation statement represents a circuit that is encompassed in a "black box" whose function is defined in another module. This example demonstrates the close relationship between a block diagram and code. The code is essentially a textual description of a schematic. Although it is a clumsy way for humans to comprehend the diagram, it puts all representations into a single HDL framework. The Xilinx ISE package includes a simple schematic editor utility that can perform schematic capture in graphic format and then convert the diagram into an HDL structural description. Connection by ordered list An alternative scheme to associate the ports and external signals is connection by ordered list (sometimes also known as connection byposition). In this scheme, the port names of the lower-level module are omitted and the signals of the higher-level module are listed in the same order as the lower-level module's port declaration. With this scheme, the two module instantiation statements in Listing 1.4 can be rewritten as Although this scheme makes the code more compact, it is error prone, especially for a module with many 110ports. For example, ifwe modify the code of the lower-level module and switch the order of two ports in the port declaration, all the instantiated modules need to be corrected as well. If this is done accidentally during code editing, the altered port order may be left undetected during synthesis and leads to difficult-to-find bugs. We always use the connection-by-name scheme in this book. Verilogprimitive Verilog includes a set of predefinedprimitives that can be instantiated FYI as modules. These primitives correspond to simple gate-level function blocks, such as the and, or, and not cells. For example, the eql circuit can be implemented by using simple cells, as shown in Figure 1.3. The corresponding primitive-based code is shown in Listing 1.5. STRUCTURAL DESCRIPTION 11 Figure 1.3 Low-level diagram of a I-bit comparator. Listing 1.5 Implementation with Verilog primitive module eql-primitive ( input wire iO, i1, output wire eq 5 ): // internal signal declaration wire iO-n, il-n, PO, pi; I,, / / p r i m i t i v e g a t e i n s t a n t i a t i o n s not unit1 (iO-n, iO); // iO-n = -iO; not unit2 (il-n, ill; // i l - n = - i l ; and u n i t 3 (PO, i O - n , il-n); / / pO = i O - n & i l - n ; and unit4 (pl, iO, ill; 15 or unit5 (eq, PO, pl); / / p1 = iO & i l ; / / e q = pO I p l ; endmodule This form of code is very tedious and can easily be replaced with simple bitwise logical operators. We do not use primitives in this book. In addition to the predefined primitives, we can also define customized primitives, known as user-dejnedprimitives (UDPs). For example, we can define a I-bit comparator circuit in a UDP, as shown in Listing 1.6. Listing 1.6 UDP of a 1-bit comparator primitive eql-udp(eq, iO, ill; output eq; input iO, il; table / / iO i l : e q 0 0 : 1; 0 1 :o; 1 0 : 0; 10 1 1 : 1; endtable endprimitive 12 GATE-LEVEL COMBINATIONAL CIRCUIT test vector generator -test-in-0 a -test-in-l .b uut - test-out aeqb eq2 - monitor Figure 1.4 Testbench for a 2-bit comparator. A UPD is essentially a table-based description of a circuit. The same table can also be described by a case statement (discussed in Section 3.5). We use the latter approach and do not use UDPs in this book. 1.7 TESTBENCH After code is developed, it can be simulated in a host computer to verify the correctness of the circuit operation and can be s-vnthesized to a physical device. Simulation is usually performed within the same HDL framework. We create a special program, known as a testbench, to mimic a physical lab bench. The sketch of a 2-bit comparator testbench is shown in Figure 1.4. The u u t block is the unit under test, the t e s t v e c t o r g e n e r a t o r block generates testing input patterns, and the monitor block examines the output responses. A simple testbench for the 2-bit comparator is shown in Listing 1.7. Listing 1.7 Testbench for a 2-bit comparator // The ' t i m e s c a l e d i r e c t i v e s p e c i f i e s t h a t // the .simulation time unit is I ns and // the s i m u l a t i o n t i m e s t e p is 10 ps 'timescale 1 ns/lO ps 5 module eq2-testbench ; // signal declaration reg [1:0] test-in0 , test-in1 ; wire test-out ; I0 // i n s t a n t i a t e the c i r c u i t under t e s t eq2 uut (.a(test-inO), .b(test-inl), .aeqb(test-out)); ii // t e s t vector generator initial begin // t e s t vector 1 test-in0 = 2'bOO; test-in1 = 2'bOO; # 200; // t e s t vector 2 test-in0 = 2'bOl; test-in1 = 2'bOO; # 200; // test vector 3 test-in0 = Z'b01; test-in1 = 2'bll; # 200; // test vector 4 test-in0 = Z'b10; test-in1 = 2'blO; # 200; // test vector 5 test-in0 = 2'blO; test-in1 = 2'bOO; # 200; // test vector 6 test-in0 = 2'bll; test-in1 = 2'bll; # 200; // t e s t vector 7 test-in0 = 2'bll; test-in1 = Z J b 0 1 ; # 200; // stop sitnztlation $stop ; end 511 e n d m o d u l e The code consists of a module instantiation statement, which creates an instance of the 2bit comparator, and an initial block, which generates a sequence of test patterns. The initial block is a special Verilog construct, which is executed once when simulation starts. The statements inside an initial block are executed sequentially. Each test pattern is generated by three statements, as in // t e s t vector 2 test-in0 = Z'b01; test-in1 = 2'bOO; # 200; The first two statements specify the values for the t e s t - i n 0 and t e s t - i n 1 signals and the third indicates that the two values will last for 200 time units. The last statement, $stop, is a Verilog system function that stops the simulation and returns the control to simulation software. The code has no monitor. We can observe the input and output waveforms on a simulator's display, which can be treated as a "virtual logic analyzer." The simulated timing diagram of this testbench is shown in Figure 2.16. Writing code for a comprehensive test vector generator and a monitor requires detailed knowledge of Verilog. For now, this listing can serve as a testbench template for other combinational circuits. We can substitute the u u t instance and modify the test patterns according to the new circuit. We provide a review of additional modeling and simulation-related language constructs and demonstrate the construction of a more sophisticated testbench in Section 7.5. 1.8 BIBLIOGRAPHIC NOTES A short bibliographic section appears at the end of each chapter to provide some of the most relevant references for further exploration. A comprehensive bibliography is included at the end of the book. Verilog is a complex language. The standard is specified in IEEE Standard Verilog Hardware Description Language, IEEE Std 1364-2001. Verilog HDL, 2nd edition, by S. Palnitkar and Starter's Guide to Verilog 2001 by M . D. Ciletti provide detailed coverage ofthe language's syntax and constructs. Verilog-200 1 includes many improvements over the old standard. The article "The IEEE Verilog 1364-2001 Standard: What's New, and Why You Need It" by S. Sutherland summarizes the new features. Derivation of the testbench for a large digital system is a difficult task. Writing Testbenches: Functional Verijication qf HDL Models, 2nd edition, by J . Bergeron focuses on this topic. 1.9 SUGGESTED EXPERIMENTS At the end of each chapter, some experiments are suggested as exercises. The experiments help us to better understand the concepts and provide a hands-on opportunity to design and debug actual circuits. 1.9.1 Code for gate-level greater-than circuit Develop the HDL codes in Experiment 2.9.1. The code can be simulated and synthesized after we complete Chapter 2. 1.9.2 Code for gate-level binary decoder Develop the HDL codes in Experiment 2.9.2. The code can be simulated and synthesized after we complete Chapter 2. CHAPTER 2 OVERVIEW OF FPGA AND EDA SOFTWARE 2.1 INTRODUCTION Developing a large FPGA-based system is an involved process that consists of many complex transformations and optimization algorithms. Software tools are needed to automate some of the tasks. We use the Web version of the Xilinx ISE package for synthesis and implementation, and use the starter version of Mentor Graphics ModelSim XE 111package for simulation. In this chapter, we give a brief overview of the FPGA device and the S3 prototyping board, and provide short tutorials for the two software packages to "jump-start" the learning process. 2.2 FPGA 2.2.1 Overview of a general FPGA device Afield-programmable gate array (FPGA) is a logic device that contains a two-dimensional array of generic logic cells and programmable switches. The conceptual structure of an FPGA device is shown in Figure 2.1. A logic cell can be configured (i.e., programmed) to perform a simple function, and a programmable switch can be customized to provide interconnections among the logic cells. A custom design can be implemented by specifying the function of each logic cell and selectively setting the connection of each programmable switch. Once the design and synthesis are completed, we can use a simple adaptor cable to download the desired logic cell and switch configuration to the FPGA device and obtain FPGA Proto!vpbig h.y Vrrilog E.~amples.By Pong P.Chu Copyright @ 2008 John Wiley & Sons. Inc. programmable switch Figure 2.1 Conceptual structure of an FPGA device. abc y LUT clk clk 1 L--....-....--........................... (a) Conceptual diagram 111 1 (b) Example table Figure 2.2 Three-input LUT-based logic cell. the custom circuit. Since this process can be done "in the field" rather than "in a fabrication facility (fab)," the device is known asfieldprogrammable. LUTbased logic cell A logic cell usually contains a small configurable combinational circuit with a D-type flip-flop (D FF). The most common method to implement a configurable combinational circuit is a look-up table (LUT). An n-input LUT can be considered as a small 2'"by-1 memory. By properly writing the memory content, we can use an LUT to implement any n-input combinational function. The conceptual diagram of a threeinput LUT-based logic cell is shown in Figure 2.2(a). An example of three-input LUT implementation of a $ b @ c is shown in Figure 2.2(b). Note that the output of the LUT can be used directly or stored to the D FF. The latter can be used to implement sequential circuits. Macro cell Most FPGA devices also embed certain macro cells or macro blocks. These are designed and fabricated at the transistor level, and their functionalities complement the general logic cells. Commonly used macro cells include memory blocks, combinational multipliers, clock management circuits, and 110interface circuits. Advanced FPGA devices may even contain one or more prefabricated processor cores. 2.2.2 Overview of the Xilinx Spartan3 devices This book uses Xilinx Spartan-3 family FPGA devices. Based on the ratio between the number of logic cells and the 110 counts, the family is further divided into several subfamilies. Our discussion applies to all the subfamilies. Logic cell, slice, and CLB The most basic element of the Spartan-3 device is a logic cell (LC), which contains a four-input LUT and a D FF, similar to that in Figure 2.2. In addition, a logic cell contains a carry circuit, which is used to implement arithmetic functions, and a multiplexing circuit, which is used to implement wide multiplexers. The LUT can also be configured as a 16-by- 1 static random access memory (SRAM) or a 16-bit shift register. To increase flexibility and improve performance, eight logic cells are combined with a special internal routing structure. In Xilinx terms, two logic cells are grouped to form a slice, and four slices are grouped to form a conjgurable logic block (CLB). Macro cell The Spartan-3 device contains four types of macro blocks: combinational multiplier, block RAM, digital clock manager (DCM), and input/output block (IOB). The combinational multiplier accepts two 18-bit numbers as inputs and calculates the product. The block RAM is an 18K-bit synchronous SRAM that can be arranged in various types of configurations. A DCM uses a digital-delayed loop to reduce clock skew and to control the frequency and phase shift of a clock signal. An IOB controls the flow of data between the device's I10 pins and the internal logic. It can be configured to support a wide variety of I10 signaling standards. Devices in the Spartan-3 subfamily Although Spartan-3 FPGA devices have similar types of logic cells and macro cells, their densities differ. Each subfamily contains an array of devices of various densities. The numbers of LCs, block RAMS,multipliers, and DCMs of the devices from the Spartan-3 subfamily are summarized in Table 2.1. 2.3 OVERVIEW OF THE DlGlLENT S3 BOARD The Digilent S3 board is based on a Spartan-3 device (usually an XC3S200) and has an array of built-in peripherals. The simplified layouts of the board are shown in Figure 2.3(a) and (b). The main components and connectors are as follows: 1. Xilinx Spartan-3 XC3S200 FPGA device (XC3S200FT256) 2. 2M-bit Xilinx XCF02S platform flash configuration PROM 3. Jumper to select the configuration source 4. Two 256K-by-16 asynchronous SRAM devices (ISSI IS61LV25616AL-10T) (b) Bonom view Figure 2.3 Layout of an S3 board. (Courtesy of Xilinx, Inc. O Xilinx, Inc. 1994-2007. All rights resewed.) Device DEVELOPMENT FLOW 19 Table 2.1 Devices in the Spartan-3 family Number of Number of Block Number of Number of LCs block RAMS RAM bits multipliers DCMs 5. VGA display port 6. RS-232 serial port 7. RS-232 transceiverlvoltage-level convertor 8. Second RS-232 transmit and receive channel 9. PSI2 mouse/keyboard port 10. Four-digit seven-segment LED display 1 1. Eight slide switches 12. Eight discrete LED outputs 13. Four momentary-contact pushbutton switches 14. 50-MHz crystal oscillator clock source 15. Socket for an auxiliary crystal oscillator clock source 16. Jumper to select an FPGA configuration mode 17. Pushbutton switch to force FPGA reconfiguration 18. LED to indicate whether the FPGA is successfully configured 19. 40-pin expansion connector 1 (labeled B 1) 20. 40-pin expansion connector 2 (labeled A2) 2 1. 40-pin expansion connector 3 (labeled A1) 22. JTAG connector for Digilent download cable 23. Digilent low-cost download cable (included in the S3 kit but not shown in Figure 2.3) 24. JTAG port (to be used with the Xilinx Parallel Cable IV and MultiPRO Desktop Tool, which are not included in the S3 kit) 25. Power connector for an unregulated 5-V power supply (included in the S3 kit) 26. Power-on LED indicator 27. 3.3-V voltage regulator 28. 2.5-V voltage regulator 29. 1.2-V voltage regulator 30. Selector for PS2 port voltage supply (3.3 or 5 V) 2.4 DEVELOPMENT FLOW The simplified development flow of an FPGA-based system is shown in Figure 2.4. To facilitate further reading, we follow the terms used in the Xilinx documentation. The left portion of the flow is the refinement and programming process, in which a system is transformed from an abstract textual HDL description to a device cell-level configuration 20 OVERVIEW OF FPGA AND EDA SOFTWARE L 3 El inputfile process constraint Q RTLcode @ 1 synthesis 44 implementation I testbench 4 RTL simulation 44 r----7 I functional I I simulation I L----J programming static timing analysis I timing I I simulat~on I L----J FPGA chip Figure 2.4 Development flow. and then downloaded to the FPGA device. The right portion is the validation process, which checks whether the system meets the hnctional specification and performance goals. The major steps in the flow are: 1. Design the system and derive the HDL file(s). We may need to add a separate constraint file to specify certain implementation constraints. 2. Develop the testbench in HDL and perform RTL simulation. The RTL term reflects the fact that the HDL code is done at the register transfer level. 3. Perform synthesis and implementation. The synthesis process is generally known as logic synthesis, in which the software transforms the HDL constructs to generic gatelevel components, such as simple logic gates and FFs. The implementation process consists ofthree smaller processes: translate, map, and place and route. The translate process merges multiple design files to a single netlist. The map process, which is generally known as technology mapping, maps the generic gates in the netlist to FPGA's logic cells and 10Bs. Theplace androuteprocess, which is generally known asplacement androuting, derives the physical layout inside the FPGA chip. It places the cells in physical locations and determines the routes to connect various signals. In the Xilinx flow, static timing analysis, which determines various timing parameters, such as maximal propagation delay and maximal clock frequency, is performed at the end of the implementation process. 4. Generate and download the programming file. In this process, a configuration file is generated according to the final netlist. This file is downloaded to an FPGA device serially to configure the logic cells and switches. The physical circuit can be verified accordingly. OVERVIEW OF THE XlLlNX ISE PROJECT NAVIGATOR 21 The optional functional simulation can be performed after synthesis, and the optional timing simulation can be performed after implementation. Functional simulation uses a synthesized netlist to replace the RTL description and checks the correctness ofthe synthesis process. Timing simulation uses the final netlist, along with detailed timing data, to perform simulation. Because of the complexity of the netlist, functional and timing simulation may require a significant amount oftime. Ifwe follow good design and coding practices, the HDL code will be synthesized and implemented correctly. We only need to use RTL simulation to check the correctness of the HDL code and use static timing analysis to examine the relevant timing information. Both functional and timing simulations may be omitted from the development flow. 2.5 OVERVIEW OF THE XlLlNX ISE PROJECT NAVIGATOR Xilinx ISE (integrated software environment) controls all aspects of the development flow. Project Navigator is a graphical interface for users to access software tools and relevant files associated with a project. We use it to launch all development tasks except ModelSim simulation. The discussion in this section and the tutorial in the next section are based on ISE WebPack version 8.2. The default ISE window is shown in Figure 2.5. It is divided into four subwindows: Sources window (top left): hierarchically displays the files included in the project Processes window (middle left): displays available processes for the source file currently selected Transcript window (bottom): displays status messages, errors, and warnings Workplace window (top right): contains multiple document windows (such as HDL code, report, schematic, and so on) for viewing and editing Each subwindow may be resized, moved, docked, or undocked. The default layout can be restored by selecting View + Restore. Note that a subwindow may contain multiple pages. The tabs at the bottom are used to select the desired page. Sources window The sources window is used mainly to display files associated with the current project. A typical sources window, which corresponds to the design of Listing 2.2, is shown in Figure 2.6. The top drop-down list, labeled Sources for:, specifies the current design view. The synthesis/implementation view should be selected since we use ISE only for synthesis and implementation. There are three tabs at the bottom, labeled Sources, Snapshots, and Libraries. The Sources tab displays the project name, the FPGA device specified, and user documents and design files. The modules are displayed according to the internal design hierarchy. In Figure 2.6, the eq2 and eql entities reflect the hierarchy of Listing 2.2. The eq2 module also includes the eq-s3. ucf file, which specifies the constraints of the design. We can open a file in the workplace window by double-clicking the corresponding module. A top-level module icon can be placed next to a module, as in the eq2 module, to invoke synthesis and implementation for this particular module. The Snapshots tab displays project's "snapshots," which are copies of previously stored project files. The Libraries tab shows all libraries associated with the project. Processes window The processes window displays the processes available. The display is context sensitive and the available processes are based on the source type selected in the sources window. For example, the eq2 module, which is set as the top-level module, 22 OVERVIEW OF FPGA AND EDA SOFTWARE Figure 2.5 Typical ISE window. Figure 2.7 Typical processes window. is selected in Figure 2.6. The available processes are displayed in the processes window, as shown in Figure 2.7. Some processes may also contain several subprocesses. We can initiate a process by clicking on the corresponding icon. ISE incorporates the "auto make" technology, which automatically runs the processes necessary to get to the desired step. For example, when we initiate the Generate Programming File process, ISE automatically invokes the Synthesize and Implement Design processes since file generation is dependent on the implementation result, which, in turn, is dependent on the synthesis result. Transcript window The transcript window is used to display the progress of a process and relevant messages. The Console page displays errors, warnings, and information messages. An error is signified by a red X mark next to the message and a warning is signified by a yellow ! mark. The Warnings and Errors pages display only warning and error messages. Workplace window The workplace window is for users to view and edit various types of files. We use it to perform two main tasks. The first task is to view and edit the HDL and constraint files. The default editor is the ISE Text Editor, which is a simple text editor with features to assist creation of the HDL code. The second task is to check the design summary and various reports. 2.6 SHORT TUTORIAL ON ISE PROJECT NAVIGATOR Xilinx ISE consists of an array of software tools, but detailed discussion of their use is beyond the scope of this book. We present a short tutorial in this section to illustrate the basic development process. There are four major steps: 1. Create the design project and HDL codes. 2. Create a testbench and perform RTL simulation. 3. Add a constraint file and synthesize and implement the code. 4. Generate and download the configuration file to an FPGA device. These steps follow the general development flow discussed in Section 2.4. We use the 2-bit comparator discussed in Chapter 1 in the tutorial. The codes are repeated in Listings 2.1 and 2.2. Listing 2.1 Gate-level implementation of a 1-bit comparator module eql // 1 / 0 ports ( input wire iO, i l , output wire eq 1; // signal declaration wire PO, p l ; 10 // body // sum o f two product terms a s s i g n e q = pO I p l ; // product terms 15 a s s i g n pO = - i O & - i l ; assign p l = iO & i l ; endmodule Listing 2.2 Structural description of a 2-bit comparator module eq2 ( i n p u t w i r e [ l : 01 a , b , output wire aeqb 5 1; // i n t e r n u l signal declar.ation wire eO, e l ; SHORT TUTORIAL ON ISE PROJECT NAVIGATOR 25 // i n s t a n t i a t e ~ H ' O I- bit comparators e q l e q - b i t 0 - u n i t ( . iO(a[O]), . il ( b [o]) , . eq(eO)) ; eqi eq-bitl-unit ( . eq(el), . iO(a[1]), .il(b[ll)); 15 / / a and b a r e e q u a l if i n d i v i d u a l b i t s a r e e q u a l assign aeqb = eO & el; endmodule 2.6.1 Create the design project and HDL codes There are three tasks in this step: Create a project. Add or create HDL files. Check the HDL syntax. Create a project An ISE project contains basic information of a design. which includes the source files and a target device. A new project can be created as follows: 1. Select Start tAll Programst Xilinx ISE tProject Navigator(orwherever ISE resides) to launch the ISE project navigator. + 2. In Project Navigator, select File New Project. The New Project Wizard - Create New project dialog appears. Enter the project name as eq2 and the location, and verify that HDL is selected in the Top-level Source Type field. Click Next. 3. The New Project Wizard - Device Properties dialog appears. We need to enter the desired target device in this dialog. This information can be found in the FPGA board manual or by checking the marking on the top of the FPGA chip. For a typical S3 board, select the following: Product Category: All Family: Spartan3 Device: XC3S200 Package: FT256 Speed: -4 We also need to verify that the Xilinx XST software is selected for synthesis: Synthesis Tool: XST (VHDL/Verilog) 4. Click Next a few times to go through the remaining dialogs and then click Finish to complete the creation. After a project is created, we can create or add the relevant HDL files and a constraint file. Create a new HDL file If a file does not exist, we must create a new source file. The procedure to create a new HDL file is: 1. Select Project t New Source. The New Source Wizard - Select Source Type dialog appears. Select Verilog Module and type the file name, eq2. Click Next. 2. The next dialog appears. This dialog allows us to enter port names to be embedded in the Verilog code. However, since the code generated uses the old style of port declaration, we do not use this feature. Click Next. 3. Click Finish and a new HDL text editor window appears in the workplace window. The software automatically generates a comment header and module delimiters. 4. Use the editor to enter the HDL code in Listing 2.2 and save the file. 26 OVERVIEW OF FPGA AND EDA SOFTWARE 5. Repeat the process to create another file for the code in Listing 2.1. A d d existing files If a file already exists, it can be added to the project as follows: + 1 . Select Project Add Source. A dialog window appears. 2. Go to the appropriate directory and select the desired files. Click Open and a new dialog appears. 3. Click OK to complete the addition. These files now appear in the sources window of the project navigator. Check the code syntax After completing a new HDL file, we need to check the syntax of the code: 1. Select the desired file in the source window. 2. In the processes window, click the + icon next to Synthesize to expand the process hierarchy. 3. Double-click the Check Syntax process. The bottom transcript displays the progress of the process and reports errors and warnings, which begin with red X and yellow ! marks. Double-clicking the message leads to the offending line in the file. We can correct the problem, save the file, and repeat the syntax checking process until all syntax errors are eliminated. 2.6.2 Create a testbench and perform the RTL simulation The testbench functions as a virtual lab bench. It consists of the HDL module to be tested and a code segment to generate the stimulus. The RTL simulation verifies operation of the HDL module in the host computer. ISE contains a built-in ISE simulator and can launch the ModelSim simulator manufactured by Mentor Graphics Corporation. Since the latter is more robust and versatile, we use it in the book. Although ModelSim can be invoked from ISE Project Navigator, we treat it as an individual software tool and illustrate its use in Section 2.7. 2.6.3 Add a constraint file and synthesize and implement the code There are three tasks in this step: Add a constraint file. Perform synthesis and implementation. Check the design summary. A d d a constraint file Constraints are certain conditions imposed on the synthesis and implementation processes. For our purposes, the main type of constraint is the pin assignment of a top-level 110 port and the minimal clock rate. During the implementation process, an I10 signal of the top-level module must be mapped to a physical pin of the FPGA device. Since the peripherals' 110 signals are already permanently connected to the designated FPGA's pins on the prototyping board, we must ensure that the signals are mapped to the corresponding pins. The other type of constraint is about timing, which specifies the minimal clock frequency to facilitate the oscillator of the board. The constraint information is stored in a text file with an extension of .ucf (for the user constraint file). In the eq2 circuit, we can connect the a and b ports to four switches and the aeqb port to an LED to verify the physical operation of the circuit. For the S3 board, the corresponding pins are F12, G 1 2 , H 1 4 , H 1 3 , and K 1 2 . The constraint file becomes # 4 slide switches NET " a < O > " LOC = " F 1 2 " NET " a < l > " LOC = "G12" NET " b < O > " LOC = "H14" NET " b < l > " LOC = "H13" # led NET " a e q b " LOC = "K12" ; # switch 0 ; # switch 1 ; # switch 2 ; # switch 3 ; # led 0 Note that the # sign is used for a comment and the text after it is ignored. This file must be added to the design in the sources window. Several ISE tools are available to specify and generate the constraint file. Since all of our experiments are done in the same prototyping board, the constraints (i.e., pin assignment and clock frequency) remain the same. A constraint template file that includes all connected I10 peripheral signals of the S3 board is provided in the Appendix. One easy method to create a constraint file is simply to copy and edit the template file according to the 110 port names of the current design. The procedure to create the .ucf file for the eq2 circuit proceeds as follows: 1. Copy the template constraint file and rename it eq2_s3.ucf. 2. Follow the procedure in Section 2.6.1 to add the new constraint file to the eq2 module in the sources window. 3. Select the constraint file. 4. In the processes window, click the + icon next to User Constraints to expand the process hierarchy. 5. Double-click the Edit Constraints (Text) process to launch the ISE text editor. 6. Rename the I10 names as needed and then delete the unused pin assignments. 7. Save the file. The default option of ISE version 8.2 only allows the pin assignments of the existing top-level 110 ports. If unused pin assignments are not deleted from the ucf template, error messages will be generated. We can override the default option as follows: 1. Select the top-level HDL file. 2. Right-click the Implement Design process in the processes window and then select Properties... from the menu. A dialog window appears. 3. In the dialog window, check the Allow Unmatched LOC Constraints option and then click OK. AAer this option is turned on, we can use the same ucf template for all designs as long as the same I10 port names are kept in the top-level module, and we don't need to edit the ucf file each time. Perform synthesis and implementation Invoking the synthesis and implementation procedure is very simple: 1. Select the module to be synthesized and make sure that it is designated as the top-level module (with a green square next to the module icon). 2. Double-click the Implement Design process in the processes window. 3. Although the syntax is checked earlier, the code may contain constructs that cannot be synthesized or may lead to poor implementation (such as a combinational loop). The error and warning messages are displayed in the console tab of the transcript window. 4. Correct the problems and repeat the simulation and synthesis processes if needed. 28 OVERVIEW OF FPGA AND EDA SOFTWARE Figure 2.8 Design summary. Check the design summary As the project progresses, a report is generated in each process. These reports and key statistics are summarized in a design summary window. We can check the size ofthe resulting circuit (in terms ofthe numbers of slices, FFs, and LUTs) and, for a sequential circuit, check whether the clock rate meets the timing constraints. The summary can be invoked by double-clicking the View Design Summary process in the processes window. The summary for the eq2 circuit is shown in Figure 2.8. We can check the use of slices, LUTs, and so on, in the Device Utilization Summary portion. A more detailed report can be invoked by clicking the corresponding link. 2.6.4 Generate and download the configuration file to an FPGA device The last step is to generate the configuration file and download the file to the FPGA device. There are three tasks in this step: Connect the download cable. Generate the configuration file. Download the configuration file. The S3 kit comes with a parallel-port JTAG download cable, and the following discussion is based on this cable. The procedures for other cables are similar and detailed instructions may be found in their manuals. Connect the download cable The procedure to prepare the board is as follows: I. Make sure that the PROM and Mode jumpers (labeled 3 and 16 in Figure 2.3) are in their default setting (as the board is shipped). 2. Connect the power cable. 3. Connect one end of the download cable to the parallel port of a PC and connect the other end to the JTAG port (labeled 22 in Figure 2.3) on the S3 board. Generate the configuration file Generating a configuration file is very straightforward: 1. Make sure that the top-level module is selected in the source window. 2. Click Generate Programming File in the processes window. After this process is completed, a configuration file, eq2.bit, is generated. Download the configuration file Downloading the configuration file to an FPGA device is done by a software tool known as iMPACT, which can be invoked from ISE Project Navigator. The procedure is as follows: 1. In the processes window, click the + sign to expand the Generate Programming File hierarchy. 2. Double-click the Configure Device (IMPACT) process. The Welcome to iMPACT dia- log appears, as shown in Figure 2.9. Check Configure devices using Boundary-Scan (JTAG) and verify that Automatically connect to a cable and identify Boundary-Scan chain is selected in the drop-down list. Click Finish. 3. If a message indicating that two devices are found is displayed, click OK to continue. 4. The main iMPACT window, along with the Assign New Configuration File dialog, appears, as shown in Figure 2.10. The devices connected to the JTAG chain on the board should be detected and displayed. 5. Select the eq2.bit file and click Open to assign this configuration file to the xc3s200 device in the JTAG chain. 6. If a warning message appears, ignore it and click OK. 7. Select Bypass to skip the other device. 8. Right-click on the xc3s200 device image, and select Program .... The Programming Properties dialog opens. Click OK to program the device. 9. The Program Succeeded message appears when the downloading process is com- pleted. Now the FPGA device is configured and we can test the circuit with the switches and observe the output LED. Figure 2.10 iMPACT main window. Figure 2.11 Typical ModelSim window. An alternative way to configure the FPGA is to download the configuration file to a PROM and load the configuration file from the PROM. More information may be found in the sources cited in the bibliographic section. 2.7 SHORT TUTORIAL ON THE MODELSIM HDL SIMULATOR The ModelSim software is an HDL simulator manufactured by Mentor Graphics Corporation and can run independently without ISE. The discussion in this section is based on ModelSim XE 111 Starter version 6.0d. The default ModelSim window is shown in Figure 2.1 1. It is divided into three subwindows: Transcript window (bottom), Workspace window, and multiple document interface (MDI) window. The Workspace window displays information on the current process. The bottom tab is used to select the desired process page, which can be Project, Library, Sim, and so on. The Transcript window keeps track of command history and messages. It can also be used as a command-line interface to enter ModelSim commands. The MDI window is an area to display HDL text, waveform, and so on. The bottom tab selects the desired pages. Each subwindow may be resized, moved, docked, or undocked. Additional windows may appear for some operations. The default layout can be restored by selecting Window + Initial Layout. We present a short tutorial in this section to illustrate the basic simulation process. There are three steps: I . Prepare a simulation project. 2. Compile the HDL codes. 3. Perform a simulation and examine the waveform. We use the 2-bit comparator testbench discussed in Chapter 1 for the tutorial, and the code is repeated in Listing 2.3. Listing 2.3 Testbench of a 2-bit comparator // The ' t i m e s c a l e d i r e c t i v e s p e c i f i e s t h a t // the .simlrlation time unit is 1 ns and // the s i m u l a t i o n t i m e s t e p i s 10 ps 'timescale 1 ns/lO ps < module eq2-testbench; // sigrial declaration r e g [I :0] t e s t - i n 0 , t e s t - i n 1 ; wire test-out ; I0 // instatitiate the circuit under test eq2 uut (.a(test-inO), .b(test-inl), .aeqb(test-out)); 15 // lest vector generator initial begin // t e s t vector 1 test-in0 = 2'bOO; test-in1 = 2'bOO; # 200; // lest vector 2 test-in0 = 2'bOl; test-in1 = 2'bOO; # 200; // test vector 3 test-in0 = 2'bOl; test-in1 = 2'bll; # 200; // test vector 4 test-in0 = 2'blO; test-in1 = 2'blO; # 200; // test vector 5 test-in0 = 2'blO; test-in1 = 2'bOO; # 200; // test vector 6 test-in0 = 2'bll; test-in1 = 2'bll; SHORT TUTORIAL ON THE MODELSIM HDL SIMULATOR 33 (a) Create P r o j e c t dialog (b) Add items dialog Figure 2.12 New project dialogs. # 200; // test vector 7 test-in0 = 2'bll; test-in1 = 2'bOl; 45 # 200; // stop simulation $stop ; end so e n d m o d u l e Prepare a simulation project A ModelSim simulation project consists of the library definition and a collection of HDL files. A testbench is an HDL program and can be created by using the ISE text editor, as discussed in Section 2.6.1. Alternatively, ModelSim also has a built-in editor. We assume that all HDL files are already constructed. The procedure to create a project is as follows: + 1. Select Start + All Programs + ModelSim XE I l l 6.0d ModelSim (or wherever Mod- elSim resides) to launch the ModelSim program. + + 2. Select File New Project and the Create Project dialog appears, as shown in Figure 2.12(a). Enter the project name as eq-testbench, select the project location, and set Default Library Name to work. Click OK. A blank Project page appears in the main window and the Add items to the project dialog appears, as shown in Figure 2.12(b). 3. In the Add items to the project dialog, click Add Existing File and add the necessary HDL files. Click OK. The project tab appears in the workplace subwindow and displays the selected files, as shown in Figure 2.13. Compile the HDL code The compile term here means to convert the HDL code into ModelSim internal format. In Verilog, compiling is done on the module basis. The procedure is: + 1. Highlight the eql file and right-click the mouse. Select Compile Compile Selected. Note that the compiling should be started from the modules at the bottom ofthe design hierarchy. The progress and messages are displayed in the transcript window. 34 OVERVIEW OF FPGA AND EDA SOFTWARE Figure 2.14 Simulate dialog. 2. If the file contains no syntactical error, a check mark shows up. Otherwise, an X mark shows up. Click the red error line in the transcript window to locate the errors. Correct the problems, save the file, and recompile the file. 3. Repeat the preceding steps to compile the eq2 file and then the eq-tb file. Perform a simulation and examine the waveform After compiling the testbench and corresponding files, we can perform the simulation and examine the resulting waveform. This corresponds to running the circuit in a virtual lab bench and checking the waveform in a virtual logic analyzer. The procedure is: + 1. Select Simulate Simulate and the Simulate dialog appears. 2. In the Design tab, find and expand the work library, which is the one defined when we create the project. All compiled units are displayed, as shown in Figure 2.14. 3. Load e q 2 - t e s t b e n c h by double-clicking the corresponding icon. The sim tab appears in the workplace window and the corresponding page displays the structure of BIBLIOGRAPHIC NOTES 35 Figure 2.16 Waveform window. the eq2-testbench module, as shown in Figure 2.15. An object window, which contains the signals in the selected module, may also appear. 4. Highlight the uut unit and right-click the mouse. Select Add + Add to Wave. This adds all the signals of the uut unit to the waveform page. The waveform page appears in the MDI window. 5. If necessary, rearrange the signals order and set them to the proper formats (decimal, hex, and so on). + 6. Select Simulate Run. There are several commands to control the simulation: Restart (restart the simulation), Run (run the simulation one step), Continue run (resume the run from the interrupt), Run All (run the simulation forever), and Break (break the simulation). These commands are also shown as icons at the top of the window. 7. The waveform window displays the simulated result, shown in Figure 2.16. We can scroll the window, zoom in, or zoom out to check the correctness of the design. 2.8 BIBLIOGRAPHIC NOTES Both Xilinx ISE and Mentor Graphics ModelSim are complex software packages, and their documentation exceeds several thousand pages. Most documentation can be accessed via the Help menu. ISE has a short 30-page tutorial, ISE 8.l i Quick Start Tutorial, and a more comprehensive 170-page tutorial, ISE In-Depth Tutorial. ModelSim also has a similar tutorial, ModelSim Tutorial. These tutorials provide an overview on all features of the software package. Relevant information for the Spartan-3 device can be found in its data sheets, DS099 Spartan-3 FPGA Family: Complete Data Sheet, which includes the detailed explanation on the logic cells and macro cells. The Design Warrior's Guide to FPGAs by Clive Maxfield provides a comprehensive review of FPGA-related issues. The detailed 36 OVERVIEW OF FPGA AND EDA SOFTWARE Table 2.2 Truth table of a 2-to-4 decoder with enable input output en n(1) a.(O) bcode layout and I10 connectors of the S3 board may be found in Spartan-3 Starter Kit Board User Guide. Information on other prototyping boards can be found in their manuals. 2.9 SUGGESTED EXPERIMENTS 2.9.1 Gate-level greater-than circuit The greater-than circuit compares two inputs, a and b, and asserts an output when a is greater than b. We want to create a 4-bit greater-than circuit from the bottom up and use only gate-level logical operators. Design the circuit as follows: 1. Derive the truth table for a 2-bit greater-than circuit and obtain the logic expression in the sum-of-products format. Based on the expression, derive the HDL code using only logical operators. 2. Derive a testbench for the 2-bit greater-than circuit. Perform a simulation and verify the correctness of the design. 3. Use four switches as the inputs and one LED as the output. Synthesize the circuit and download the configuration file to the prototyping board. Verify its operation. 4. Use the 2-bit greater-than circuits and 2-bit equality comparators and a minimal number of "glue gates" to construct a 4-bit greater-than circuit. First draw a block diagram and then derive the structural HDL code according to the diagram. 5. Derive a testbench for the 4-bit greater-than circuit. Perform a simulation and verify the correctness of the design. 6. Use eight switches as the inputs and one LED as the output. Synthesize the circuit and download the configuration file to the prototyping board. Verify its operation. 2.9.2 Gate-level binary decoder An 11-to-2" binary decoder asserts one of 2" bits according to the input combination. The finctional table of a 2-to-4 decoder with an enable signal is shown in Table 2.2. We want to create several decoders using only gate-level logical operators. The procedure is as follows: 1. Determine the logic expressions for the 2-to-4 decoder with enable and derive the HDL code using only logical operators. 2. Derive a testbench for the decoder. Perform a simulation and verify the correctness of the design. 3. Use two switches as the inputs and four LEDs as the outputs. Synthesize the circuit and download the configuration file to the prototyping board. Verify its operation. SUGGESTED EXPERIMENTS 37 4. Use the 2-to-4 decoders to derive a 3-to-8 decoder. First draw a block diagram and then derive the structural HDL code according to the diagram. 5. Derive a testbench for the 3-to-8 decoder. Perform a simulation and verify the correctness of the design. 6. Use three switches as the inputs and eight LEDs as the outputs. Synthesize the circuit and download the configuration file to the prototyping board, Verify its operation. 7. Use the 2-to-4 decoders to derive a 4-to-16 decoder. First draw a block diagram and then derive the structural HDL code according to the diagram. 8. Derive a testbench for the 4-to-16 decoder. Perform a simulation and verify the correctness of the design. This Page Intentionally Left Blank CHAPTER 3 RT-LEVEL COMBINATIONAL CIRCUIT 3.1 INTRODUCTION The gate-level circuits discussed in Chapter 1 utilize simple bitwise operators to describe gate-level design, which is composed of simple logic cells. In this chapter, we examine the HDL description of circuits that are composed of intermediate-sized components, such as adders, comparators, and multiplexers. Since these components are the basic building blocks used in the register transfer methodology, it is sometimes referred to as RT-level design. We discuss more sophisticated Verilog operators, the always block, and routing constructs, and then demonstrate the RT-level combinational circuit design through a series of examples. 3.2 OPERATORS Verilog consists of about two dozen operators. In addition to the bitwise operators discussed in Chapter 1 , there are arithmetic, shift, and relational operators. These operators correspond to intermediate-sized components, such as adders and comparators. We examine these operators in this section and also cover miscellaneous synthesis-related Verilog constructs. Table 3.1 summarizes the operators. FPG.4 Protoypittg bj, Verilog Exantples. B y Pong P.Chu Copyright @ 2008 John Wiley & Sons, Inc. Table 3.1 Verilog operators Type of operation Arithmetic Operator symbol + - * / % ** Description addition subtraction multiplication division modulus exponentiation Number of operands Shift >> logical right shift 2 << logical left shift 2 >>> arithmetic right shift 2 <<< logical left shift 2 Relational > greater than 2 < less than 2 >= greater than or equal to 2 <= less than or equal to 2 Equality -- equality 2 I= inequality 2 --- case equality 2 case inequality 2 Bitwise - bitwise negation 1 & bitwise and 2 I bitwise or 2 bitwise xor 2 Reduction & I A reduction and reduction or reduction xor Logical ! logical negation 1 && logical and 2 II logical or 2 Concatenation {} concatenation { { } } replication Conditional ?: conditional 3 Table 3.2 Operator precedence Operator ! - + - (unary) ** */% + - (binary) Precedence highest ?: lowest 3.2.1 Arithmetic operators There are six arithmetic operators: +, -, *, /, %, and **. They represent addition, subtraction, multiplication, division, modulus, and exponentiation operations, respectively. The + and - operators can also be used as unary operators, as in -a. During synthesis, the + and - operators infer the adder and subtractor and they are synthesized by FPGA's logic cells. Multiplication is a complicated operation and synthesis of the multiplication operator * depends on synthesis software and target device technology. The Xilinx Spartan-3 FPGA Xilinx family contains prefabricated combinational multiplier blocks. The Xilinx XST software specific can infer these blocks during synthesis and thus the multiplication operator can be used in HDL code. The XCS200 device of the S3 board consists of twelve 18-by-18 multiplier blocks. Although the synthesis of the multiplication operator is supported, we need to be aware of the limitation on the number and input width of these blocks and use them with care. The /, %, and ** operators usually cannot be synthesized automatically. 3.2.2 Shift operators There are four shift operators: >>, <<, >>>, and <<<. The first two represent the logical shift right and left and the last two represent the arithmetic shift right and left. The 0's are shifted in for a logical shift operation (i.e., >> and <<). The sign bits (i.e., the MSB) are shifted in for the >>> operation and the 0's are shifted in for the <<< operation. Note that there is no difference between the << and <<< operations. The latter is included for completeness. Some shifting examples are shown in Table 3.3. If both operands of a shift operator are signals, as in a << b, the operator infers a barrel shifter, which is a fairly complex circuit. On the other hand, if the shifted amount is fixed, as in a << 2, the operation infers no logic and involves only routing of the input signals. Table 3.3 Shift operation examples This type of operation can also be described by using the catenation operator discussed in Section 3.2.5. 3.2.3 Relational and equality operators There are four relational operators: >, <, <=, and >=. These operators compare two operands and return a Boolean result, which can befalse (represented by I-bit scalar value 0) or true (represented by l -bit scalar value I). There are four equality operators: ==, !=, ===, and !==. As with the relational operators, they return ,false (I-bit 0) or true (I-bit 1). The === and !== operators, known as case equality and case inequality operators, take into consideration of the matches of the x and z bits in the operands. They cannot be synthesized. The relational operators and the == and ! = operators infer comparators during synthesis. 3.2.4 Bitwise, reduction, and logical operators The bitwise, reduction, and logical operators are somewhat similar and perform the and, or, xor, as well as not operations. These operators are implemented by basic logic cells. Bitwise operators There are four basic bitwise operators: & (and), I (or), (xor), and - (not). The first three operators require two operands. Negation and xor operation can be "- combined, as in or ^", to form the xnor operator. The operations are performed on a bit-by-bit basis and thus are known as bitwise operators. For example, let a, b, and c be 4-bit signals: wire [3:01 a , b , c ; The statement assign c = a I b; is the same as assign assign assign assign c[31 = a[31 I bC31; c [21 = a [ 2 1 I bC21 ; c [ l l = a [ l l I b[11 ; c COI = a[Ol I b[Ol ; - Reduction operators The previous &, I , and operators may have only one operand and then are known as reduction operators. The single operand usually has an array data type. The designated operation is performed on all elements of the array and returns a I -bit result. For example, let a be a 4-bit signal and y be a 1-bit signal: w i r e C3:OI a ; wire y; OPERATORS 43 Table 3.4 Logical and bitwise operation examples a b a&b alb a&&b allb 0 1 0 1 0 (false) 1 (true) 000 000 000 000 0 (false) 0 (false) 000 001 000 001 0 (false) 1 (true) 011 001 001 011 1 (true) 1 (true) The statement assign is the same as assign y = I a; // only one operand y = aC31 I a[21 I a[11 I a[01 ; Logical operators There are three logical operators: && (logical and), I I (logical or), and ! (logical negate). The logical operators are different from the bitwise operators. If we assume that no x or z is used, the operands of a logical operator are interpreted as false (when all bits are 0's) or true (when at least one bit is I), and the operation always returns a 1-bit result. As the name suggests, the logical operators should be used as logical connectives of Boolean expressions, as in Some examples are shown in Table 3.4. The corresponding bitwise operations are also included to illustrate the difference between the two types of operations. Since Verilog uses 0 and 1 to represent the false and true values, bitwise and logical operators can be used interchangeably in some situations. However, it is good practice to use logical operators for Boolean expressions and use bitwise operators for signal manipulation. 3.2.5 Concatenation and replication operators The concatenation operator, { ), combines segments of elements and small arrays to form a large array. The following example illustrates its use: wire al; w i r e [3:01 a4; w i r e [7:01 b8, c8, d8; ... a s s i g n b8 = (a4, a41; a s s i g n c8 = {al, al, a4, 2'bOOI; a s s i g n d8 = {b8[3:01 , c8[3:011; Implementation of the concatenation operator involves reconnection of the input and output signals and only requires "wiring." One application of the concatenation operator is to shift and rotate a signal by a fixed amount, as shown in the following example: w i r e C7:OI a ; w i r e [7:01 r o t , shl , sha; 44 RT-LEVELCOMBINATIONAL CIRCUIT // votate a to right 3 bits a s s i g n rot = (a[2:0], a[8:31); // s h i f t a to right 3 bits and insert 0 ( l o g i c a s s i g n shl = C3'b000, a[8:31); // s h i f t a t o r i g h t 3 b i t s a n d i n s e r t MSB // (arithmetic s h i f t ) a s s i g n sha = Ca[8] , a[8] , a[8] , a[8:3]); shift) The concatenation operator, N{ ), replicates the enclosed string. The replication constant, N, specifiesthe numberofreplications. For example, {4{2 'b01)) returns 8' b01010101. The previous arithmetic shift operation can be simplified: a s s i g n sha = C3{a[81), a[8:3]}; 3.2.6 Conditional operators The conditional operator, ? :,takes three operands and its general format is [signal] = [boolean-exp] ? [true-exp] : [false-exp]; The [boolean-expl is a Boolean expression that returns true ( I ' b l ) or false ( I 'bO). The [ s i g n a l ] gets [true-expl if it is true and [false-expl if it is false. For example, the following circuit obtains the maximum of a and b: assign max = (a>b) ? a : b; The operator can be thought as a simplified if-then-else statement: i f [boolean-exp] then [signal] = [true-expl ; else [signal] = Cf alse-expl ; Despite its simplicity, the conditional operators can be cascaded or nested to specify the desired selection. For example, the e q l circuit described in Table 1.1 can be rewritten using conditional operators: a s s i g n eq = (-il & - i O ) ? l'bl : ("il & iO) ? l'bO : (il & "iO) ? l'bO : lJbl; We can extend the maximal circuit to return the maximum of a, b, and c: a s s i g n max = (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c ) ; While synthesized, a conditional operator infers a 2-to-1 multiplexing circuit. The detailed derivation is discussed in Section 3.6. 3.2.7 Operator precedence The operator precedence specifies the order of evaluation. The precedence is shown in Table 3.2. When an expression is evaluated, the operator with higher precedence is evaluated first. For example, in the a + b >> 1expression, a + b is evaluated first and then >> 1 is evaluated. We can use parentheses to alter the precedence, as in a + (b >> I ) . It is a good practice to use parentheses to make an expression clearer, as in ( a + b) >> 1, even when they are not required. OPERATORS 45 3.2.8 Expression bit-length adjustment As signals in real hardware, nets and variables in a Verilog program usually have different numbers of bits (i.e., bit lengths or widths). In a Verilog statement, the bit lengths of operands can be different and the adjustment is determined by a set of implicit rules: Determine the maximal bit length of the operands in the context, which includes the right-hand-side expression and the left-hand-side signal. Extend the bit lengths of operands on the right-hand side to the maximum and evaluate the expression. Assign the result to the left-hand-side signal. Truncate the MSBs if the signal's bit length is smaller. Let us first consider a simple example: w i r e [7:01 a , b; a s s i g n a = 8'b00000000; assign b = 0; The first statement assigns an 8-bit value. "00000000",to a. The second statement assigns the integer 0 to b. Recall that the integer in Verilog is 32 bits and thus 0 is represented as "00000000000000000000000000000000". Since b is 8 bits wide, it is truncated to "00000000" during the assignment. Although both statements assign an all-zero pattern to the signals, we need to be aware of how the values are obtained. Let us consider another example: w i r e [7:01 a , b; w i r e [7:0] sum8; w i r e [8:01 sum9; a s s i g n sum8 = a + b; a s s i g n sum9 = a + b; In the first assignment, all operands are 8 bits wide and an 8-bit addition is performed. The carry-out bit of the addition is discarded. In the second assignment, the a and b signals are extended to 9 bits, the bit length of the sum9 signal, and a 9-bit addition is performed. The sum [91 bit gets the resulting carry-out bit. We can also use a concatenation operator if an explicit carry-out signal is desired: a s s i g n {c-out ,sum81 = a + b; Although the basic conversion rule is simple and intuitive, the subtleties can be errorprone. For example, let a, b, suml,and sum2 be 8-bit signals. The following statements give a different result: / / s h i f t 0 t o MSB o f sum1 a s s i g n suml = (a + b) > > 1 ; // s h i f t car-rj>-out o f a+b t o MSB o f sum2 a s s i g n sum2 = (0 + a + b) > > 1 ; In the first assignment, all operands are 8 bits wide and an 8-bit addition is performed. The carry-bit is discarded. When the shift operation is performed, 0 is shifted into the MSB. In the second assignment, 0 is an integer and thus is 32 bits wide. The a and b are extended to 32 bits for addition and the summation is shifted. The result is then truncated to 8 bits when assigned to sum2 and sum2 [71 gets the original carry-out bit. The conversion becomes more involved when the signed data type is used (discussed in Section 7.3). 1 a-in Figure 3.1 Symbol and functional table of a tri-state buffer. A safe but somewhat cumbersome alternative is to adjust the bit lengths of the operands manually. For example, an alternative that may be used to obtain sum2 is wire [8:01 sum-ext ; ... // extend sum to 9 b i t s a s s i g n sum-ext = tl'b0,a) + (l'bO,b); a s s i g n s u m 2 = s u m - e x t C9: 11 ; The code is longer but is more descriptive and less prone to error. In summary, we must be aware of the Verilog's automatic bit-length adjustment mecha- nism. Unintended bit-length mismatch may lead to subtle, difficult-to-find errors. Except for trivial adjustments, such as assigning an all-zero pattern with an integer 0, we should either adjust the bit lengths manually or thoroughly document the desired automatic adjustment. 3.2.9 Synthesis of z and x values In addition to the regular logic 0 and logic 1, net and variable can contain z and x values. Although they are not operators, we discuss the synthesis aspect of these two values in this subsection. Synthesis of z The z value implies high impedance or an open circuit. It is not a normal logic value and can only be synthesized by a tri-state bufer. The symbol and function table of a tri-state buffer are shown in Figure 3.1. The operation of the buffer is controlled by an enable signal, oe (for "output enable"). When it is 1, the input is passed to output. On the other hand, when it is 0, the y output appears to be an open circuit. The code of the tri-state buffer is a s s i g n y = (oe) ? a-in : l'bz; The most common application for a tri-state buffer is to implement a bidirectional port to better utilize a physical 110 pin. A simple example is shown in Figure 3.2. The d i r signal controls the direction of signal flow of the b i pin. When it is 0, the tri-state buffer is in a high-impedance state and the s i g - o u t signal is blocked. The pin is used as an input port and the input signal is routed to the s i g - i n signal. When the d i r signal is 1, the pin is used as an output port and the s i g - o u t signal is routed to an external circuit. The HDL code can be derived according to the diagram: module bi-demo ( inout wire bi, assign sig-out = output-expression; - OPERATORS 47 sig-in Figure 3.2 Single-bufferbidirectional 110port. Table 3.5 Truth table with don't-care input output i Y 00 0 01 1 10 1 1I X assign ... assign assign some-signal = bi = (dir) ? sig-in = bi; expression-with-sig-in; sig-out : l'bz; Note that the mode of the b i port must be declared as inout for bidirectional operation. For a Xilinx Spartan-3 device, a tri-state buffer exists only in the 110 block (IOB) of a physical pin. Thus, the tri-state buffer can be used only for I/O ports that are mapped to the Xilinx physical pins of an FPGA device. specific Synthesis of x In some combinational circuits, certain input patterns may never occur and thus the output value is irrelevant. We frequently assign a "don't-care" value to the output. During synthesis, the don't-care will be assigned a value (either 0 or 1) that can help the optimization process. Consider the truth table shown in Table 3.5. We assume that the i will never be 11and thus the corresponding output is specified as don't-care. In synthesis, we can use x for the don't-care value. One possible code for the previous table is a s s i g n y = (i==2'b00) ? I'bO : (i==2'b01) ? l'bl : (i==2'b10) ? l'bl : l'bx; // i = = 2 ' b l l Although this approach helps to minimize the circuit, it introduces a discrepancy between simulation and synthesis. In simulation, x is a unique value rather than "0 or 1". If the input is 11in simulation, the output becomes x and is not consistent with the synthesized result (which can be either 0 or 1). However, since the 11pattern should never occur in the original specification, the appearance of the x value can be used to signal potential errors in the testbench. 3.3 ALWAYS BLOCK FOR A COMBINATIONAL CIRCUIT To facilitate system modeling, Verilog contains a number ofprocedural statements, which are executed in sequence. Sincetheir behavior is different from the normal concurrent circuit model, these statements are encapsulated inside an always block or initial block. The initial block is executed once when the simulation is started. It can be used in simulation, as in the testbench example in Listing 1.7. Only the always block can be synthesized and it is discussed in this section. Since the procedural statement is more abstract, this type of code is sometimes known as behaviorial description. An always block can be thought of as a black box whose behavior is described by the internal procedural statements. Procedural statements include a rich variety of constructs but many of them don't have clear hardware counterparts. A poorly coded always block frequently leads to unnecessarily complex implementation or cannot be synthesized at all. The focus of this section is on the synthesis of combinational circuits and we limit the discussion to three types of statements: Blocking procedural assignment If statement Case statement The latter two can be considered as constructs that infer routing structure. 3.3.1 Basic syntax and behavior The simplified syntax of an always block with a sensitivity list (also known as event control e.~pression)is always @([sensitivity-list]) begin [optional name] [optional local variable declaration]; [procedural statement]; [procedural statement] ; end The [ s e n s i t i v i t y - l i s t ] term is a list of signals and events to which the always block responds (i.e., is "sensitive to"). For a combinational circuit, all the input signals should be included in this list. The body is composed of any number of procedural statements. The begin and end delimiters can be omitted if there is only one procedural statement in the body. The @ ([ s e n s i t i v i t y - l i s t ] ) term is actually a timing control construct. It is usually the only timing control construct in a synthesizable always block. An always block can be considered as a complex circuit part. It can be suspended or activated. When any signal of the sensitivity list changes or an event occurs, the part is activated and executes the internal procedural statements. Since there is no other timing control construct, the execution continues to the end and the part is suspended. Thus, an always block actually "loops forever" and the initiation of each loop is controlled by the sensitivity list. ALWAYS BLOCK FOR A COMBINATIONAL CIRCUIT 49 3.3.2 Procedural assignment A procedural assignment can only be used within an always block or initial block. There are two types of assignments: blocking assignment and nonblocking assignment. Their basic syntax is [variable-name] = [expression] ; // blocking assignment [variable-name] <= [expression] ; // nonblocking assignment In a blocking assignment, the expression is evaluated and then assigned to the variable immediately, before execution of the next statement (the assignment thus "blocks" the execution of other statements). It behaves like the normal variable assignment in the C language. In a nonblocking assignment, the evaluated expression is assigned at the end of the always block (the assignment thus does not block the execution of other statements). The blocking and nonblocking assignments frequently confuse new Verilog users and failing to comprehend their differences can lead to unexpected behavior or race conditions. The basic rule of thumb is: Use blocking assignments for a combinational circuit. Use nonblocking assignments for a sequential circuit. This topic is explained in detail in Section 7.1. Since we focus on combinational circuits in this chapter, only the blocking statement is used. 3.3.3 Variable data types In a procedural assignment, an expression can only be assigned to an output with one of the variable data types, which are reg, integer, real, time, and realtime. The reg data type is like the wire data type, but used with a procedural output. The integer data type represents a fixed-size (usually 32 bits) signed number in 2's-complement format. Since its size is fixed, we usually don't use it in synthesis. The other data types are for modeling and simulation and cannot be synthesized. 3.3.4 Simple examples We use two simple examples to illustrate the use and behavior of the always block and procedural blocking assignment. 1-bit comparator We can rewrite the previous I -bit comparator circuit in Listing 1.1 using an always block. The code is shown in Listing 3.1. Listing 3.1 Always block implementationof a 1-bitcomparator module eql-always ( input wire iO, i l , output reg eq // eq declared as reg s ); / / pO and p l d e c l a r e d as reg reg PO, pi; 10 always @(iO, i l ) // i O an i l must be in s e n s i t i v i t y l i s t begin // the order of s t a t e m e n t s is important PO = - i O & - i l ; pl = i0 & il; Ii eq = pO I pl; end endmodule Since the eq, pO, and p l signals are assigned within the always block, they are declared as the reg data type. The sensitivity list consists of i O and il, which are separated by a comma. When one of them changes, the always block is activated. The three blocking assignments are executed sequentially, much like the statements in a C program. The order of the statements is important and pO and p l must be assigned values before being used. In Verilog-1995, the keyword or is used in place of the comma in a sensitivity list. For FYI example, the list a l w a y s @(a, b , c) is written as a l w a y s @(a o r b o r c) We use only commas in this book. A combinational circuit must include all its input signals in the sensitivity list to correctly model the desired behavior. Missing a signal can lead to discrepancy between synthesis and simulation. In Verilog-2001, we can use the notation always Q* to implicitly include all the input signals. In this book, we use this construct for the combinational circuit. Three-input and circuit The similarity of the codes in Listings 1.1 and 3.1 is somewhat misleading. The behavior of continuous assignments and procedural statements is quite different. Consider the code in Listing 3.2. It is a circuit that performs an and operation over a, b, and c (i.e., a & b & c). Listing 3.2 Behaviorial reduced and circuit using a variable module and-block-assign ( input wire a, b, c, output reg y ); always Q* begin y = a; Iu y=y&b; y=y&c; end endmodule Figure 3.3 Circuits inferred from correct and incorrect code segments. The inferred circuit is shown in Figure 3.3(a). Ifwe use continuous assignments in a similar way, as shown in Listing 3.3, the description is incorrect. Listing 3.3 Incorrect code for a reduced and circuit module and-cont -assign ( input wire a , b, c , output wire y s ); assign y = a; assign y = y & b; assign y = y & c; 10 endmodule In this code, each continuous assignment infers a circuit part. The three appearances of y on the left-hand side imply that the three outputs are tied together. The corresponding circuit diagram is shown in Figure 3.3(c) and it is clearly not the desired circuit. 3.4 IF STATEMENT 3.4.1 Syntax The simplified syntax of an if statement is if [boolean-expr] begin [procedural statement1; [procedural statement] ; end else begin [procedural statement] ; [procedural statement]; Table 3.6 Function table of a four-request priority encoder input output r pcode The [boolean-exprl term is a Boolean expression and is evaluated first. If it is true, the statements in the following branch are executed. Otherwise, the statements in the else branch are executed. The else branch is optional and can be omitted. The begin and end delimiters can be omitted if there is only one procedural statement in a branch. Multiple if statements can be "cascaded" to evaluate multiple Boolean conditions and establish priorities, as in ... e l s e i f [boolean-expr-21 e l s e if [boolean-expr-31 ... else When synthesized, the if statements infer "priority routing" networks. This topic is discussed in Section 3.6. 3.4.2 Examples We use two simple examples to demonstrate use of the if statement. The first example is a priority encoder. The priority encoder has four requests, r C41, r C31, r C21, and r [ I ] , which are grouped as a single 4-bit r input, and r C41 has the highest priority. The output is the binary code of the highest-order request. The function table is shown in Table 3.6. The HDL code is shown in Listing 3.4. Listing 3.4 Priority encoder using an if statement module prio-encoder-if ( i n p u t wire C4:11 r , output reg [2:01 y 5 1; always Q* i f (r [ 4 1 = = l Jbl) // can be w r i t t e n as ( r [ 4 ] ) y = 3'blOO; else if (r[31==lJbl) // can be w r i t t e n as ( r [ 3 ] ) y = 3'b011; e l s e i f (r[21==l 'bl) // can be w r i t t e n as ( r [ 2 ] ) IF STATEMENT 53 Table 3.7 Truth table of a 2-to-4 decoder with enable input output en a ( l > a(O> y y = 3'bOlO; e l s e i f (r[ll==l 'bl) // can be w r i t t e n as ( r [ l ] ) Ii y = 3'b001; else y = 3'bOOO; endmodule The code first checks the r [4] request and assigns 100to pcode if it is asserted. It continues to check the r [31 request if r [4] is not asserted and repeats the process until all requests are examined. Note that the Boolean expression ( r [41==l'bl) is true when r [41 is 1. Since the true value is also expressed as 1 'bl in Verilog, the expression can be written as (r [41) as well. The second example is a binary decoder. An 11-to-2'3inary decoder asserts one bit of the 2"-bit output according to the input combination. The functional table of a 2-to-4 decoder is shown in Table 3.7. The circuit also has a control signal, en, which enables the decoding function when asserted. The HDL code is shown in Listing 3.5. Listing 3.5 Binary decoder using an if statement module decoder-2-4-if ( input wire [1:01 a , input wire en, 5 output reg [3:0] y 1; always Q* i f ( e n = = l JbO) // can be ~ l r i l t e nas ( - e n ) 10 y = 4'bOOOO; e l s e i f (a==2'b00) y = 4'bOOOl; else if (a==2'b01) y = 4'bOOlO; I5 else if (a==2'b10) y = 4'bOlOO; else y = 4'blOOO; 20 e n d m o d u l e 54 RT-LEVEL COMBINATIONAL CIRCUIT The code first checks whether en is not asserted. lfthe condition is false (i.e., en is I),it tests the four binary combinations in sequence. Note that the Boolean expression (en==l'bO) can be written as (-en) as well. 3.5 CASE STATEMENT 3.5.1 Syntax The simplified syntax of a case statement is case [case-exprl [item] : begin [procedural statementl ; [procedural statementl ; ... end [item] : begin [procedural statement 1 ; [procedural statement 1; ... end [iteml : begin [procedural statement 1 ; [procedural statementl; end ... default: begin [procedural statement 1 ; [procedural statementl; end endcase A case statement is a multiway decision statement that compares the [case-exprl expression with a number of [iteml expressions. The execution jumps to the branch whose [item] matches the current value of [case-expr] . If there are multiple matched [iteml expressions, execution jumps to the branch of the first match. The last item can be an optional default keyword. It covers all the unspecified values of the [case-exprl expression. The begin and end delimiters can be omitted if there is only one procedural statement in a branch. 3.5.2 Examples We use the same priority encoder and decoder examples to demonstrate use of the case statement. The functional table of a 2-to-4 decoder is shown in Table 3.7. The HDL code using a case statement is shown in Listing 3.6. CASE STATEMENT 55 Listing 3.6 Binary decoder using a case statement module decoder-2-4-case ( input wire [1:01 a , input wire en, 5 output reg [3:0] y 1; always Q* c a s e ( C e n ,a)) 10 3'b000, 3'b001, 3'b010, 3'bOll: y = 4'bOOOO; 3'blOO: y = 4'bOOOl; 3'blOl: y = 4'bOOlO; 3'bllO: y = 4'bOlOO; 3'blll: y = 4'blOOO; // default can also be used IS endcase endmodule We can group multiple values into one item expression, as in line 10, if the identical statements are used for these values. Note that all possible values of the {en,a) expression are covered by the item expressions. The function table of the priority encoder is shown in Table 3.6. The HDL code is shown in Listing 3.7. Listing 3.7 Priority encoder using a case statement module prio-encoder-case ( i n p u t w i r e C4: 11 r , output reg [2:01 y 5 ); always Q* c a s e (r) 4'b1000, 4'b1001, 4'b1010, 4'b1011, 10 4'b1100, 4'b1101, 4'b1110, 4'bllll: y = 3'blOO; 4'b0100, 4'b0101, 4'b0110, 4'bOlll: y = 3'bOll; 4'b0010, 4'bOOll: 15 y = 3'bOlO; 4'bOOOl: y = 3'bOOl; 4'boo00 : // default can also be used y = 3'bOOO; 20 endcase endmodule 3.5.3 The casez and casex statements There are two variations in addition to the regular case statement. In a casez statement, the z value and the ? character in the item expression are treated as don't-care (i.e., the corresponding bit does not need to be matched). In a casex statement, the z and x values and the ? character in the item expression are treated as don't-care. Since the z and x values may appear in simulation, the ? character is preferred. For example, the previous priority encoder can be coded with a casez statement, as shown in Listing 3.8. Listing 3.8 Priority encoder using a casez statement module prio-encoder-casez ( input wire [4:11 r , o u t p u t r e g C2:OI y S 1; always Q* casez (r) 4'bl???: y = 3'blOO; 4'b01??: y = 3'bOll; 4'b001?: y = 3'bOlO; 4'bOOOl: y = 3 ' b O O l ; 4'bOOOO: y = 3 ' b O O O ; // d e f a u l t can a l s o be u s e d endcase IS endmodule 3.5.4 The full case and parallel case In Verilog, the item expressions do not need to include all values of the [case-expr] expression and some values can be matched more than once. Consider the following casez statement: r e g C2:Ol s ... casez (s) 3'blll: y = l'bl; 3'bl??: y = l'bO; 3'bOOO: y = l ' b l ; endcase In this statement, the value 3 ' b l l l is matched twice in the item expressions (once in 3'blIlandoncein3'bl??). Sincethefirstmatchtakeseffect,ygetsl'blifsis3'blll. If s is 3' b001, 3'b010, or 3'b011, there are no matches and y will "keep its previous value." When all possible binary values of the [case-exprl expression are covered by the item expressions, the statement is known as afull case statement. For a combinational circuit, we must use a full case statement since each input combination should have an output value. We can add the default item to cover all the unmatched values. For example, the previous statement can be revised either as ROUTING STRUCTURE OF CONDITIONAL CONTROL CONSTRUCTS 57 casez (s) 3'blll: y = l'bl; 3'bl??: y = l'bO; d e f a u l t : y = l'bl; endcase // y gets 1 for unspecified values casez (s) 3'blll: y = l'bl; 3'bl??: y = l'bO; 3'bOOO: y = l'bl; d e f a u l t : y = l'bx; endcase // y gets don 't-care When the values in the item expressions are mutually exclusive (i.e., a value appears in only one item expression), the statement is know as aparallel case statement. For example, the previous casez statement is not a parallel case statement since the value 3 'b111 appears twice. The case statements of Listings 3.6 and 3.7 are parallel case statements. When synthesized, a parallel case statement usually infers a multiplexing routing network and a non-parallel case statement usually infers a priority routing network. This topic is discussed in the next section. Many synthesis software packages have "full case directive" and "parallel case directive." When they are used, all case statements are treated as full case statements and parallel case statements and synthesized accordingly. Verilog-2001 has similar attributes for this purpose. Using these directives essentially overrides original semantics of Verilog code FYI and introduces a discrepancy between simulation and synthesis. In this book, we express these conditions in code rather than applying these directives or attributes. 3.6 ROUTING STRUCTURE OF CONDITIONAL CONTROL CONSTRUCTS We examine several conditional control language constructs, including the ? : operator and the if and case statements. In the C language, these constructs are executed sequentially. There is no "sequential" control in a combinational circuit. These constructs are realized by routing networks. All expressions are evaluated concurrently and the routing network routes the desired result to the output. There are two types of routing structures: priority routing network and multiplexing network, which are inferred by an if-else type statement and a parallel case statement, respectively. 3.6.1 Priority routing network A priority routing network is implemented by a sequence of 2-to-1 multiplexers. The diagram and truth table of a 2-to-1 multiplexer are shown in Figure 3.4(a). An if-else statement implies a priority routing network. Consider the following statement: if (m==n) r=a+b+c; else i f (m > n) r=a-b; else r=c+1: 58 RT-LEVEL COMBINATIONAL CIRCUIT sel y 0 (false) iO 1 (true) i l (a) Diagram of a 2-to-1 multiplexer I Circuits for "value expressionsn ..............i.........................: Priority routing .....-.! Circuits for "Boolean expressions" (b) Diagram of an if statement Figure 3.4 Implementation of an if statement. The conceptual diagram of the statement is shown in Figure 3.4(b). The two 2-to-1 multiplexers form the priority routing network and other components implement various Boolean and arithmetic expressions. If the first Boolean condition (i.e., m==n) is true, the result of a+b+c is routed to r. Otherwise, the data connected to port 0 is passed to r. The next Boolean condition (i.e., m>n) determines whether the result of a-b or c+l is routed to the output. Note that all the Boolean expressions and arithmetic expressions are evaluated concurrently. The outputs from the Boolean circuits set the selection signals of the multiplexers to route the desired value to r. The number of cascading stages increases proportionally to the number of if-else clauses. A large number of if-else clauses will lead to a long cascading chain and introduce a large propagation delay. The conditional operator (?:) is like a simplified if-else statement and infers similar priority routing networks. A non-parallel case statement sets a preference on the first matched item and thus also infers similar priority routing networks. For example, consider the following case statement: case ( e x p r ) iteml: statementl; item2: staternent2; ROUTING STRUCTURE OF CONDITIONAL CONTROL CONSTRUCTS 59 sel y 00 i0 i2 i3 Y 01 il 10 i2 sel 11 i3 (a) Diagram and functional table of a 4-to-1 multiplexer Circuits for "value expressions" .........................i.. .................... Multiplexer r I sel (b) Diagram of a parallel case statement Figure 3.5 Implementation of a parallel case statement. item3 : statement3 ; default : statement4; endcase It can be translated to if [expr==itemll statement1 ; else if [expr==item21 statement2 ; else if [expr==item31 statement3 ; else statement4 ; 3.6.2 Multiplexing network A multiplexing network is implemented by an n-to-1 multiplexer. The desired input port is specified by the selection signal and the corresponding input is routed to the output. The diagram and functional table of the 22-to-1 multiplexer are shown in Figure 3.5(a). In a parallel case statement, we can map each value of the case expression to an input port of the multiplexer and connect the corresponding evaluated result to the port. The case expression is connected to the selection signal. The construction can best be explained by an example. Consider the following case statement: wire [1:01 s e l ; case (sell 2'bOO: r = a + b + c ; 2'bIO: r = a - b; default: r = c + 1; // endcase 2'601, 2'bll The conceptual diagram of this statement is shown in Figure 3.5(b). The sel varaible can assume four possible values: 00,01, 10, and 11. It implies a 22-to-1 multiplexer with sel as the selection signal. The evaluated result of a+b+cis routed to r when sel is 00, the result of a-b is routed to r when sel is 10, and the result of c + l is routed to r when sel is 01 or 11. Again, note that all value expressions are evaluated concurrently. The sel variable is used as the selection signal to route the desired value to the output. The width (i.e., number of input ports) of the multiplexer increases geometrically with the number of bits of sel. In general, the priority routing network is more effective when a preference is given under certain conditions, such as for a priority encoder, and the multiplexing network is more effective for a truth table or function table-based description, such as for a binary decoder. 3.7 GENERAL CODING GUIDELINES FOR AN ALWAYS BLOCK Verilog is for both modeling and synthesis. While writing code for synthesis, we need to be aware of how the various language constructs are mapped to hardware. This is especially true for an always block since variables and procedural statements can be used within the block. We should remember that the purpose of the code is to infer hardware rather than describing a sequential algorithm in C. Failing to do so frequently leads to unsynthesizable codes, unnecessarily complex implementation, or discrepancy between simulation and synthesis. In this section, we review some common errors and suggest a collection of coding guidelines. 3.7.1 Common errors in combinational circuit codes Following are common errors found in combinational circuit codes: a Variable assigned in multiple always blocks a Incomplete sensitivity list Incomplete branch and incomplete output assignment These errors are discussed below. Variable assigned in multiple always blocks In Verilog, variables can be assigned (i.e., appear on the left-hand side) in multiple always blocks. For example, the y variable is shared by two always blocks is the following code segment: reg y; reg a , b , clear; always Q* if (clear) y = lJbO; always Q* y=a&b; Although the code is syntactically correct and can be simulated, it cannot be synthesized. Recall that each always block can be interpreted as a circuit part. The code above indicates that y is the output of both circuit parts and can be updated by each part. No physical circuit exhibits this kind of behavior and thus the code cannot be synthesized. We must group the assignment statements in a single always block, as in always Q* if (clear) y = lJbO; else y=a&b; lncomplete sensitivity list For a combinational circuit, the output is a function of input and thus any change in an input signal should activate the circuit. This implies that all input signals should be included in the sensitivity list. For example, a two-input and gate can be written as always @(a, b) y=a&b; // both a and b are in s e n s i t i v i t y l i s t If we forget to include b, the code becomes always @(a) y=a&b; // a missing from s e n s i t i v i t y l i s t Although the code is still syntactically correct, its behavior is very different. When a changes, the always block is activated and y gets the value of a&b. When b changes, the always block remains suspended since it is not "sensitive to" b and y keeps its previous value. No physical circuit exhibits this kind of behavior. Most synthesis software will issue a warning message and infer the and gate instead. However, the simulation software still models the intended behavior and hence introduces a discrepancy between simulation and synthesis. In Verilog-2001, a special notation, @*i,s introduced to implicitly include all the relevant input signals and thus eliminates this problem. It is a good practice to use this notation for combinational circuit description. lncomplete branch and incomplete output assignment The output of a combinational circuit is a hnction of input only and the circuit should not contain any internal state (i.e., memory). One common error with an always block is the inference of unintended memory in a combinational circuit. The Verilog standard specifies that a variable will keep its previous value if it is not assigned a value in an always block. During synthesis, this infers an internal state (via a closed feedback loop) or a memory element (such as a latch). To prevent unintended memory in an always block, all output signals must be assigned proper values all the time. Incomplete branch and incomplete output assignment are two common errors that lead to unintended memory. To avoid these, we should observe the following rules while developing code for combinational circuit: Include all the branches of an if or case statement. Assign a value to every output signal in every branch. Consider the following code segment, which intends to describe a circuit that generates greater-than (i.e., g t ) and equal-to (i.e., eq) output signals: always Q* i f (a > b) // eq not assigned in t h i s branch gt = l'bl; e l s e i f (a == b) // g t n o t a s s i g n e d i n t h i s branch eq = l'bl; // final else branch is omitted The segment violates both rules. Let us first examine the incomplete branch error. There is no else branch in the segment. If both the a>b and a==bexpressions are false, both g t and eq are not assigned values. According to Verilog definition, they keep their previous values (i.e., the outputs depend on the internal state) and unintended latches are inferred. The segment also has incomplete output assignment errors. For example, when the a>b expression is true, eq is not assigned a value and thus will keep its previous state. A latch will be inferred accordingly. There are two ways to fix the errors. The first is to add the else branch and explicitly assign all output variables. The code becomes always Q* i f (a > b) begin gt = l'bl; eq = 1'bO; end e l s e i f (a == b) begin gt = l'bO; eq = l'bl; end else / / i . e . , a < b begin gt = l'bO; eq = l'bO; end The alternative is to assign a default value to each variable in the beginning of the always block to cover the unspecified branch and unassigned variable. The code becomes always Q* begin gt = l'bO; eq = l'bO; if (a > b) // d e f a u l t value for gt // default value for eq gt = l'bl; e l s e i f (a == b) eq = l'bl; end Both gt and eq assume 0 if they are not assigned a value later. The case statement experiences the same errors if some values of the [case-expr] expression are not covered by the item expressions (i.e., not a full-case statement). Consider the following code segment: reg [1:01 s ... case (s) 2'bOO: 2'blO: 2'bll: endcase y = l'bl; y = l'bO; y = l'bl; The 2'bOl value is not covered by any branch. If s assumes this combination, y will keep its previous value and an unintended latch is inferred. To fix the error, we must ensure that y is assigned a value all the time. One way to do this is to use the default keyword in the end to cover all the unspecified values. We can either replace the last item expression: case (s) 2'bOO: y = l'bl; 2'blO: y = l'bO; default: y = l'bl; e n d case // y g e t s I for 2'bOl or add a new item expression with the don't-care value: case (s) 2'bOO: y = l'bl; 2'blO: y = l'bO; 2'bll: y = l'bl; default: y = l'bx; endcase // y gets x for 2'bOl Alternatively, we can assign a default value in the beginning of the always block: y = 1'bO; // can ulso case (s) 2'bOO: y = l'bl; 2'blO: y = l'bO; 2'bll: y = l'bl; endcase use y = I 'bx for don 't-care 3.7.2 Guidelines The always block is a flexible and powerful language construct. However, it must be used with care to infer correct and efficient circuits and to avoid any discrepancy between synthesis and simulation. Following are the coding guidelines for the description of combinational circuits: Assign a variable only in a single always block. Use blocking statements for combinational circuits. Use @*to include all inputs automatically in the sensitivity list. Make sure that all branches of the if and case statements are included. Make sure that the outputs are assigned in all branches. One way to satisfy the two previous guidelines is to assign default values for outputs in the beginning of the always block. Describe the desired full case and parallel case in code rather than using software directives or attributes. Be aware of the type of routing network inferred by different control constructs. Think hardware, not C code. 3.8 PARAMETER AND CONSTANT 3.8.1 Constant HDL code frequently uses constant values in expressions and array boundaries. These values are fixed within the module and cannot be modified. One good design practice is to replace the "hard literals" with symbolic constants. It makes code clear and helps future maintenance and revision. In Verilog, a constant can be declared using the localparam (for "local parameter") keyword. For example, we can declare the width and range of a data bus as localparam DATA-WIDTH = 8 , DATA-RANGE = 2**DATA_WIDTH - 1; or define a symbolic port name: l o c a l p a r a m UART-PORT = 4'b0001, LCD-PORT = 4'b0010, MOUSE-PORT = 4'bOlOO; The expression in the declaration, such as 2**DATA-WIDTH-1, is evaluated during preprocessing and thus infers no physical circuit. In this book, we use capital letters for constants. The use of a constant can best be explained by an example. Consider the code of an adder with the carry-out bit. One way to do it is to extend the input manually by 1 bit, perform the regular addition, and extract the MSB of the summation as the carry-out bit. The code is shown in Listing 3.9. Listing 3.9 Adder using a hard literal module adder-carry-hard-lit ( i n p u t w i r e [3:01 a , b, o u t p u t w i r e [3:01 s u m , 5 output wire cout // carry-out >; // signal declaration w i r e [4:0] sum-ext ; 10 //body a s s i g n sum-ext = €1'bO, a) + Cl'b0, b); a s s i g n sum = sum-ext [3:01 ; a s s i g n cout= sum-ext [41 ; IS endmodule The code is for a 4-bit adder. Hard literals, such as 3 and 4, are used for the ranges, as in wire C4 :01 and sum-ext [3 :01,and the MSB, as in sum-ext C41. If we want to revise the code for an 8-bit adder, these literals have to be modified manually. This will be a tedious and error-prone process if the code is complex and the literals are referred to in many places. To improve readability, we can use a symbolic constant, N, to represent the number of bits of the adder. The revised code is shown in Listing 3.10. Listing 3.10 Adder using constants module adder-carry-local-par ( i n p u t w i r e [3:01 a , b , output wire [3:01 sum, 5 output wire cout // carry-out 1; // constant declaration localparam N = 4 , 10 N1 = N-1; // signal declaration wire [N:O] sum-ext; IS //body a s s i g n sum-ext = Cl'bO, a) + Cl 'bO, b); a s s i g n sum = sum-ext EN1 : 01 ; a s s i g n cout = sum-ext [NI ; The constant makes the code easier to understand and maintain. 3.8.2 Parameter A Verilog module can be instantiated as a component and becomes a part of a larger design, as discussed in Section 1.6. Verilog provides a construct, known as a parameter, to pass information into a module. This mechanism makes the module versatile and reusable. A parameter cannot be modified inside the module and thus functions like a constant. In Verilog-2001, a parameter declaration section can be added in the header, before the port declaration. Its simplified syntax is module [module-name] #( parameter [parameter-name] = [default-value] , ) ( ... >; [parameter-name]= [default-value] ; // 1/0 port declaration For example, the previous adder code can be modified to use the adder width as a parameter, as shown in Listing 3.1 1. Listing 3.11 Adder using a parameter module adder-carry-para #(parameter N=4) ( input wire [N-1:Ol a , b, 5 output wire [N-1:Ol sum, output wire cout // carry-out // constant declaration 10 l o c a l p a r a m N1 = N-1; // signal declaration wire [N:O] sum-ext ; 15 //body a s s i g n sum-ext = Cl'bO, a) + {I'bO, b); a s s i g n sum = sum-ext [NI :01 ; a s s i g n cout= sum-ext [N] ; The N parameter is declared with a default value of 4. After N is declared, it can be used in the port declaration and module body, just like a constant. If the adder is later used as a component in other code, we can assign a desired value to the parameter during component instantiation and override the default value. Similar to the port connection discussed in Section 1.6, parameter assignment can be done either by name or by ordered list. A potential problem of the by-ordered-list scheme is discussed in Section 1.6 and we always use the by-name scheme in this book. The default value will be used if the parameter assignment is omitted. The use of the parameter in component instantiation is demonstrated in Listing 3.12. Listing 3.12 Adder instantiation example module adder-insta ( i n p u t wire [3:01 a4, b4, o u t p u t w i r e [3:01 s u m 4 , 5 output wire c4, i n p u t wire [7:01 a8, b8, output wire [7:0] sum8, output wire c8 1; 10 // instantiate 8-bit adder a d d e r - c a r r y - p a r a # ( . N(8)) u n i t 1 ( . a(a8), .b(b8), . sum(sum8), . cout ( ~ 8 ) ); // instantiate 4-bit adder adder-carry-para unit2 . (.a(a4), .b(b4), .sum(sum4), cout(c4)); endmodule A parameter provides a mechanism to create scalable code, in which the "width" of a circuit can be adjusted to meet a specific need. This makes code more portable and encourages design reuse. DESIGN EXAMPLES 67 3.8.3 Use of parameters in Verilog-1995 The localparam keyword, header declaration, and assignment by name discussed earlier are all new Verilog-2001 features. In Verilog-1995, parameters are declared after the header FYI and can only be redefined by using the by-order-list scheme or the defparam statement. Furthermore, constants must be declared as parameters, even though they should not be redefined. The previous adder code in Verilog-1995 syntax is shown in Listing 3.13. Listing 3.13 Parameter use in Verilog- 1995 module adder-carry-95 (a, b, sum, cout); parameter N = 4; // parameter declared before the port parameter N1 = N-1; // no l o c a l p a r a m i n V e r i l o g -1995 input wire [N1:01 a , b ; s output wire [Nl:O] sum; output wire cout ; // signal declaration w i r e [N:01 sum-ext ; to //body a s s i g n sum-ext = {l'bO, a) + {l'bO, b); a s s i g n sum = sum-ext [Nl : O] ; a s s i g n c o u t = sum-ext [N] ; 15 endmodule When a component is instantiated, the parameter can only be redefined by using the by-ordered-list scheme, as in or by using the defparam statement, as in defparam unit 1.N=8; defparam unit1 .N1=7; adder-carry-95 unit1 (.a(a8), .b(b8), .sum(sum8), .cout(c8)); The Verilog-1995 scheme is more tedious and may introduce subtle errors and we don't use it in this book. 3.9 DESIGN EXAMPLES 3.9.1 Hexadecimal digit to seven-segment LED decoder The sketch of a seven-segment LED display is shown in Figure 3.6(a). It consists of seven LED bars and a single round LED decimal point. On the prototyping board, the sevensegment LED is configured as active low, which means that an LED segment is lit if the corresponding control signal is 0. A hexadecimal digit to seven-segment LED decoder treats a 4-bit input as a hexadecimal digit and generates appropriate LED patterns, as shown in Figure 3.6(b). For completeness, we assume that there is also a 1-bit input, dp, which is connected directly to the decimal (a) Diagram of a seven-segment LED display (b) Hexadecimal digit patterns Figure 3.6 Seven-segment LED display and hexadecimal pattems. point LED. The LED control signals, dp, a, b, c , d, e, f , and g, are grouped together as a single 8-bit signal, sseg. The code is shown in Listing 3.14. It uses one case statement to list all the desired patterns for the seven LSBs of the sseg signal. The MSB is connected to dp. Listing 3.14 Hexadecimal digit to seven-segment LED decoder module hex-to-sseg ( i n p u t w i r e [3:01 input wire dp, 5 o u t p u t r e g [7:0] 1; hex, sseg / / o u t p u t a c t i v e low always Q* begin 10 c a s e (hex) 4'hO: sseg [6:01 = 7'b0000001; 4'hl: sseg[6:0] = 7'b1001111; 4'h2: sseg [6:0] = 7'b0010010; 4'h3: sseg [6:01 = 7'b0000110; 4'h4: sseg[6:0] = 7'b1001100; 4'h5: sseg [6:0] = 7'b0100100; 4'h6: sseg [6:01 = 7'b0100000; 4'h7: sseg[6:0] = 7'bOOOlill; 4'h8 : sseg C6:01 = 7'b0000000 ; 20 4'h9 : sseg [6:01 = 7'b0000100 ; 4'ha: sseg [6:01 = 7'b0001000; 4'hb: sseg [6:0] = 7'b1100000; 4'hc: sseg[6:0] = 7'b0110001; 4'hd: sseg [6:01 = 7'blOOOOlO; 25 4'he: sseg C6:Ol = 7'b0110000; d e f a u l t : sseg [6:01 = 7'b0111000; //4'hf endcase sseg [71 = dp; end 30 endmodule There are four seven-segment LED displays on the prototyping board. To save the number of FPGA chip's 110pins, a time-multiplexing scheme is used. The block diagram of the time-multiplexing module, dispaux, is shown in Figure 3.7(a). The inputs are inO, inl, in2,and in3,which correspond to four 8-bit seven-segment LED patterns, and the outputs are an, which is a 4-bit signal that enables the four displays individually, and sseg, which is the shared 8-bit signal that controls the eight LED segments. The circuit generates a properly timed enable signal and routes the four input patterns to the output alternatively. The design of this module is discussed in Chapter 4. For now, we just treat it as a black box that takes four seven-segment LED patterns, and instantiate it in the code. Testing circuit We use a simple 8-bit increment circuit to verify operation ofthe decoder. The sketch is shown in Figure 3.7(b). The sw input is the 8-bit switch of the prototyping board. It is fed to an incrementor to obtain sw+l. The original and incremented s w signals are then passed to four decoders to display the four hexadecimal digits on seven-segment LED displays. The code is shown in Listing 3.15. Listing 3.15 Hex-to-LED decoder testing circuit module hex-to-sseg-test ( input wire clk, input wire [7:01 sw, 5 output wire C3:Ol an, o u t p u t wire C7:Ol sseg 1; // signal declaration lo wire [7:01 inc; w i r e [7:01 l e d 0 , led1 , l e d 2 , l e d 3 ; // increment input assign inc = sw + 1; IS // i n s t a n t i a t e four instances of hex decoders // instance for 4 LSBs of input hex-to-sseg sseg-unit-0 (.hex(sw[3:0]), .dp(lJbO), .sseg(ledO)); za / / i n s t a n c e f o r 4 MSBs o f i n p u t hex-to-sseg sseg-unit-I (.hex(sw[7:41), .dp(lJbO), .sseg(ledl)); // i n s t a n c e for 4 LSBs o f incrernented value hex-to-sseg sseg-unit-2 zs (.hex(inc[3:0]), .dp(l'bl), .sseg(led2)); / / i n s t a n c e f o r 4 MSBs o f i n c r e r n e n t e d v a l u e hex-to-sseg sseg-unit-3 (.hex(inc[7:4]), .dp(l'bl), .sseg(led3)); 30 / / i n s t a n t i a t e 7-seg LED d i s p l a y t i m e - m u l t i p l e x i n g m o d u l e disp-mux disp-unit 70 RT-LEVEL COMBINATIONAL CIRCUIT disp-mux reset (a) Block diagram of an LED time-multiplexing module - , / hex sseg - 4 dp hex-to-sseg / / hex sseg 4 dp hex-to-sseg +- hex - sseg 4 dp hex-to-sseg -in0 in1 in2 in3 - sseg -sseg an an / disp-mux 8 reset hex-to-sseg clk 0 (b) Block diagram of a decoder testing circuit Figure 3.7 LED time-multiplexingmodule and decoder testing circuit. ;S e n d m o d u l e We can follow the procedure in Chapter 2 to synthesize and implement the circuit on the prototyping board. Note that the disp-mux.v file, which contains the code for the timemultiplexing module, and the ucf constraint file must be included in the Xilinx ISE project during synthesis. 3.9.2 Sign-magnitude adder An integer can be represented in sign-magnitude format, in which the MSB is the sign and the remaining bits form the magnitude. For example, 3 and -3 become "00 11" and "1011" in Cbit sign-magnitude format. A sign-magnitude adder performs an addition operation in this format. The operation can be summarized as follows: If the two operands have the same sign, add the magnitudes and keep the sign. If the two operands have different signs, subtract the smaller magnitude from the larger one and keep the sign of the number that has the larger magnitude. One possible implementation is to divide the circuit into two stages. The first stage sorts the two input numbers according to their magnitudes and routes them to the max and min signals. The second stage examines the signs and performs addition or subtraction on the magnitude accordingly. Note that since the two numbers have been sorted, the magnitude of max is always larger than that of min and the final sign is the sign of max. The code is shown in Listing 3.16, which realizes the two-stage implementation scheme. For clarity, we split the input number internally and use separate sign and magnitude signals. A parameter, N, is used to represent the width of the adder. Listing 3.16 Sign-magnitude adder module sign-mag-add #( parameter N=4 1 5 ( i n p u t wire EN-1:Ol o u t p u t reg EN-1:Ol ); a, b, sum 10 // signal declaration reg [N-2:0] mag-a, mag-b , mag-sum, max, min; reg sign-a, sign-b, sign-sum; //body IS always Q* begin // separate magnitude and sign mag-a = a CN-2:OI ; mag-b = b EN-2: 01 ; 20 sign-a = a[N-11; sign-b = b CN-11 ; 72 RT-LEVELCOMBINATIONAL CIRCUIT sw[3:0] sw[7:4] =a =b sign-mag-add btn clk mout[2:0] 3,~ hex - sseg dp hex-to-sseg sign circuit in0 sseg Jin1 in2 an in3 - disp-mux reset 0 Figure 3.8 Sign-magnitudeadder testing circuit. // sort according to magnitude if (mag-a > mag-b) begin max = mag-a; min = mag-b; sign-sum = sign-a; end else begin max = mag-b; min = mag-a; sign-sum = sign-b; end // add/sub magnitude if (sign-a==sign-b) mag-sum = max + min; e1se mag-sum = max - min; 40 // form output sum = (sign-sum, mag-sum); end endmodule Testing circuit We use a Cbit sign-magnitude adder to verify circuit operation. The sketch of the testing circuit is shown in Figure 3.8. The two input numbers are connected to the 8-bit switch, and the sign and magnitude are shown on two seven-segment LED displays. Two pushbuttons are used as the selection signal of a multiplexer to route an operand or the sum to the display circuit. The rightmost even-segment LED shows the 3-bit magnitude, which is appended with a 0 in front and fed to the hexadecimal to seven-segment LED decoder. The next LED displays the sign bit, which is blank for the plus sign and is lit with a middle LED segment for the minus sign. The two LED patterns are then fed to the time-multiplexing module, dispaux, as explained in Section 3.9.1. The code is shown in Listing 3.17. DESIGN EXAMPLES 73 Listing 3.17 Sign-magnitude adder testing circuit module sm-add-test ( input wire clk, i n p u t w i r e [1:0] btn, 5 i n p u t w i r e [7:01 sw, o u t p u t w i r e [3:01 an, o u t p u t w i r e [7:01 sseg ); 10 // s i g n a l d e c l a r a t i o n w i r e 13:01 sum, mout , oct ; w i r e C7:01 led3, led2, ledl , led0 ; // instantiate adder IS sign-mag-add # ( . N (4)) sm-adder-unit (.a(sw[3:Ol>, .b(sw[7:41), .sum(sum)); / / m a g n i t u d e d i s p l a y e d o n r i g h t m o s t 7 - s e g LED a s s i g n mout = (btn==2'b00) ? sw [3:0] : 20 (btn==2 ' b0l) ? sw [7:41 : sum ; a s s i g n oct = {l'bO, mout [2:01); // i n s t a n t i a t e hex decoder hex-to-sseg sseg-unit zs (.hex(oct), .dp(lJbO), .sseg(ledO)); / / s i g n d i s p l a y e d on 2 n d 7 - s e g LED / / m i d d l e LED b a r on f o r n e g a t i v e n u m b e r a s s i g n ledl = mout [3] ? 8'b11111110 : 8'bllllllll; io / / b l a n k t w o o t h e r LEDs a s s i g n led2 = 8'bllllllll; a s s i g n led3 = 8'b11111111; / / i n s t a n t i a t e 7 - s e g LED d i s p l a y t i m e - m u l t i p l e x i n g m o d u l e 15 disp-mux disp-unit (.clk(clk), .reset(iJbO), .inO(ledO), .inl(ledl), . in2 (led2), . in3 (led31, . an(an), . sseg(sseg)) ; endmodule 3.9.3 Barrel shifter Although Verilog has built-in shift functions, there is no rotation operation. In this subsection, we examine an 8-bit barrel shifter that rotates an arbitrary number of bits to the right. The circuit has an 8-bit data input, a, and a 3-bit control signal, amt,which specifies the amount to be rotated. The first design uses a case statement to exhaustively list all combinations of the amt signal and the corresponding rotated results. The code is shown in Listing 3.18. 74 RT-LEVELCOMBINATIONAL CIRCUIT Listing 3.18 Barrel shifter using a case statement module barrel-shifter-case ( i n p u t w i r e [7:01 a, i n p u t w i r e [2:0] amt , 5 o u t p u t r e g [7:0] y ); // body always Q* case (amt) 3'00: y = a; 3'01: y = Ca[Ol, aC7:llI; 3'02: y = Ca[1:0], a[7:211; 3'03: y = (a[2:Ol, a[7:311; 3'04: y = Ca[3:Ol, a[7:413; 3'05: y = Ca[4:Ol, a[7:511; 3'06: y = Ca[5:0], a[7:611; d e f a u l t : y = Ca[6:0], a[7]3; endcase 20 endmodule While the code is straightforward, it will become cumbersome when the number of data bits increases. Furthermore, a large number of items in a case statement implies a wide multiplexer, which makes synthesis difficult and leads to a large propagation delay. Alternatively, we can construct the circuit by stages. In the nth stage, the input signal is either passed directly to output or rotated right by 2" positions. The nth stage is controlled by the nth bit of the amt signal. Assume that the 3 bits of amt are m2mlmo. The total + + rotated amount after three stages is m222 m12' mo20,which is the desired rotating amount. The code for this scheme is shown in Listing 3.19. Listing 3.19 Barrel shifter using multistage shifts module barrel-shif ter-stage ( i n p u t w i r e [7:01 a, i n p u t w i r e [2:01 amt, 5 o u t p u t w i r e [7:0] y ); // signal declaration w i r e [7:01 SO, sl; 10 // body // stage 0 , s h i f t 0 or 1 bit a s s i g n SO = amt [O] ? Ca[O], a[7:1]) : a ; // stage 1, s h i f t 0 or 2 b i t s 1 5 a s s i g n sl = amt [ll ? CsO[l:O] , sO[7:211 : S O ; // stage 2, s h i f t 0 or 4 b i t s a s s i g n y = amt [2] ? {s1[3:01, sl[7:41) : sl; endmodule DESIGN EXAMPLES 75 Testing circuit To test the circuit, we can use the 8-bit switch for the a signal, three pushbutton switches for the amt signal, and the eight discrete LEDs for output. Instead of deriving a new constraint file for pin assignment, we create a new HDL file that wraps the barrel shifter circuit and maps its signals to the prototyping board's signals. The code is shown in Listing 3.20. Listing 3.20 Barrel shifter testing circuit module shifter-test ( input wire [2:0] btn, input wire [7:01 sw, 5 output wire [7:01 led 1; // instantiate shifter barrel-shifter-stage shift-unit 10 (.a(sw), .amt(btn), .y(led)); endmodule 3.9.4 Simplified floating-point adder Floating point is another format to represent a number. With the same number of bits, the range in floating-point format is much larger than that in signed integer format. Although VHDL has a built-in floating-point data type, it is too complex to be synthesized automatically. Detailed discussion of floating-point representation is beyond the scope of this book. We use a simplified 13-bit format in this example and ignore the round-off error. The representation consists of a sign bit, s, which indicates the sign of the number (1 for negative); a 4-bit exponent field, e, which represents the exponent; and an 8-bit significand field, f , which represents the significand or the fraction. In this format, the value of a floating-point number is (- 1)" * .f * 2". The .f * 2e is the magnitude of the number and (-1)' is just a formal way to state that "s equal to 1 implies a negative number." Since the sign bit is separated from the rest of the number, floating-point representation can be considered as a variation of the sign-magnitude format. We also make the following assumptions: Both exponent and significand fields are in unsigned format. The representation has to be either normalized or zero. Normalized representation means that the MSB of the significand field must be 1. If the magnitude of the computation result is smaller than the smallest normalized nonzero magnitude, 0.10000000 * 20°00, it must be converted to zero. Under these assumptions, the largest and smallest nonzero magnitudes are 0.11111111 * ~;$,AA~~~:$: :). 2"" and 0.10000000 * 2°000, and the range is about 2'' (i.e., Our floating-point adder design follows the process of add~ngnumbers manually in scientific notation. This process can best be explained by examples. We assume that the widths of the exponent and significand are 2 and 1 digits, respectively. Decimal format is used for clarity. The computations of several representative examples are shown in Figure 3.9. The computation is done in four major steps: sort align addlsub normalize eg. 1 +O.54E3 -0.87E4 -0.87E4 -0.87E4 - -0.87E4 +- 0.54E3 +- 0.05E4 +- 0.05E4 -0.82E4 eg. 3 +O.54E0 -0.55EO -0.55EO -0.55EO -0.55EO - -0.55EO - +0.54EO - +0.54EO +- 0.54EO +O.54E0 -0.01EO -0.OOEO Figure 3.9 Floating-point addition examples. 1. Sorting: puts the number with the larger magnitude on the top and the number with the smaller magnitude on the bottom (we call the sorted numbers "big number" and "small number"). 2. Alignment: aligns the two numbers so that they have the same exponent. This can be done by adjusting the exponent of the small number to match the exponent of the big number. The significand of the small number has to shift to the right according to the difference in exponents. 3. Addition/subtraction: adds or subtracts the significands of two aligned numbers. 4. Normalization: adjusts the result to the normalized format. Three types of normal- ization procedures may be needed: After a subtraction, the result may contain leading zeros in front, as in example 2. After a subtraction, the result may be too small to be normalized and thus needs to be converted to zero, as in example 3. After an addition, the result may generate a carry-out bit, as in example 4. Our binary floating-point adder design uses a similar algorithm. To simplify the implementation, we ignore the rounding. During alignment and normalization, the lower bits of the significand will be discarded when shifted out. The design is divided into four stages, each corresponding to a step in the foregoing algorithm. The suffixes, 'b', 's', 'a', 'r', and 'n', used in signal names are for "big number," "small number," "aligned number," "result of addition/subtraction," and "normalized number," respectively. The code is developed according to these stages, as shown in Listing 3.21. Listing 3.21 Simplified floating-point adder module fp-adder ( input wire signl, sign2, i n p u t w i r e [3:01 expl, exp2, i n p u t w i r e [7:0] fracl, frac2, DESIGN EXAMPLES 77 output reg sign-out , output reg [3:01 exp-out , output reg [7:01 frac-out ); 10 // signal declaration //suffix b, s , a , n for // b i g , s m a l l , a l i g n e d , normalized number reg s i g n b , s i g n s ; 15 r e g [3:01 e x p b , e x p s , e x p n , e x p - d i f f ; r e g [ 7 : 01 f r a c b , f r a c s , f r a c a , f r a c n , sum-norm ; reg [8:0] sum; reg [2:0] l e a d 0 ; 20 // body always O* begin // 1 s t s t a g e : s o r t to find the larger number i f ({expl, f r a c l } > Cexp2, frac2)) begin signb = signl; signs = sign2; expb = e x p l ; exps = exp2; fracb = fracl; fracs = frac2; end else begin signb = sign2; signs = signl; expb = exp2; exps = expl; fracb = frac2; fracs = fracl; end // 2nd s t a g e : a l i g n smaller number exp-diff = expb - exps; f r a c a = f r a c s >> exp-dif f ; // 3rd stage: add/substract if (signb==signs) sum = { I ' b O , f r a c b } + { I ' b O , e1s e sum = { l ' b O , f r a c b ) - { I ' b O , fraca); fraca}; // 4th stage: normalize // count l e a d i n g 0s i f (sum[71) lead0 = 3'00; else i f (sumC61) lead0 = 3'01; e l s e i f (sumC51) 60 lead0 = 3'02; e l s e i f (sumC41) lead0 = 3'03; else if (sum[31) lead0 = 3'04; e l s e i f (sumC21) lead0 = 3'05; e l s e i f (sum C11) lead0 = 3'06; else lead0 = 3'07; // shift significand according to leading 0 sum-norm = sum < < l e a d 0 ; // tzormalize with special conditions if (sum[8]) // with carry o u t ; s h i f t frac lo r i g h t begin expn = expb + 1; f r a c n = sum [ 8 : 11 ; end else i f (lead0 > expb) // too small to normalize begin expn = 0 ; // set to 0 fracn = 0; end else begin expn = expb - lead0; f r a c n = sum-norm; end // ,form outpz~t sign-out = signb; exp-out = expn; frac-out = fracn; end 95 endmodule The circuit in the first stage compares the magnitudes and routes the big number to the signb, expb, and f r a c b signals and the smaller number to the s i g n s , exps, and f r a c s signals. The comparison is done between e x p l t f r a c l and exp2&frac2. It implies that the exponents are compared first, and if they are the same, the significands are compared. The circuit in the second stage performs alignment. It first calculates the difference between the two exponents, which is expb-exps, and then shifts the significand, f r a c s , to the right by this amount. The aligned significand is labeled f r a c a . The circuit in the third stage performs sign-magnitude addition, similar to that in Section 3.9.2. Note that the operands are extended by 1 bit to accommodate the cany-out bit. The circuit in the fourth stage performs normalization, which adjusts the result to make the final output conform to the normalized format. The normalization circuit is constructed in three segments. The first segment counts the number of leading zeros. It is somewhat like a priority encoder. The second segment shifts the significands to the left by the amount DESIGN EXAMPLES 79 specified by the leading-zero counting circuit. The last segment checks the carry-out and zero conditions and generates the final normalized number. Testingcircuit The floating-point adder has two 13-bit input operands. Since the prototyping board has only one 8-bit switch and four I-bit pushbuttons, it cannot provide enough number of physical inputs to test the circuit. To accommodate the 26 bits of the floatingpoint adder, we must create a testing circuit and assign constants or duplicated switch signals to the adder's input operands. An example is shown in Listing 3.22. It assigns one operand as constant and uses duplicated switch signals for the other operand. The addition result is passed to the hexadecimal decoders and the sign circuit and is shown on the seven-segment LED display. Listing 3.22 Floating-pointadder testing circuit module fp-adder-test ( input wire clk, i n p u t w i r e [1:01 btn, 5 i n p u t w i r e [7:0] sw, o u t p u t w i r e [3:01 an, o u t p u t w i r e [7:01 sseg ); 10 // s i g n a l d e c l a r a t i o n s w i r e signl , sign2, sign-out ; w i r e [3:01 expl, exp2, exp-out; w i r e [7:01 fracl , frac2, frac-out ; w i r e [7:01 led3, led2, led1 , led0 ; 15 // body // s e t up the fp adder input s i g n a l s a s s i g n signl = l'bO; a s s i g n expl = 4'bIOOO; 20 a s s i g n fracl = {l'bl, sw[l:Ol , 5'blOIOl); a s s i g n sign2 = sw[7] ; a s s i g n exp2 = btn; a s s i g n frac2 = Cl'bl, sw[6:011; 2s // i n s t a n t i a t e fp a d d e r fp-adder fp-unit ( . sign1 (signl), . sign2(sign2), . expl (expi), .exp2(exp2) .fracl(fracl), . frac2(frac2), . sign-out (sign-out), .exp-out(exp-out), .frat-out(frac-out)); 30 // i n s t a n t i a t e three instances of hex decoders // exponent hex-to-sseg sseg-unit-0 (.hex (exp-out) , . dp (1 'bo), . sseg (ledo)) ; 35 / / 4 LSBs o f f r a c t i o n hex-to-sseg sseg-unit-1 (.hex(frac-out[3:01), .dp(l'bl), .sseg(ledl)); // 4 MSBs of f r a c t i o n hex-to-sseg sseg-unit-2 (.hex(frac-out [7:4]), .dp(llbO), .sseg(led2)); // sign assign led3 = (sign-out) ? 8'b11111110 : 8'bllllllll; // i n s t a n t i a t e 7 - s e g LED d i s p l a y t i m e - m u l t i p l e x i n g module , disp-mux disp-unit ( . clk(clk), .reset (llbO), .ino(led01, .inl(ledl), .in2(led2), .in3(led3), .an(an), .sseg(sseg)); endmodule 3.10 BIBLIOGRAPHIC NOTES VerilogHDL,Zndedition, by S. Palnitkar andstarter's Guide to Verilog2001 by M. D. Ciletti provide detailed coverage of Verilog's syntax and constructs. The article "The IEEE Verilog 1364-200 1 Standard: What's New, and Why You Need It" by S. Sutherland summarizes the new features. The article ""full-case parallel-case", the Evil Twins of Verilog Synthesis" by C. E. Cummings examines the caveats of the full-case and parallel-case directives, and his other article, "New Verilog-200 1 Techniques for Creating Parameterized Models," discusses the advantage of Verilog-2001's new parameter passing scheme. 3.11 SUGGESTED EXPERIMENTS 3.11.1 Multifunction barrel shifter Consider an 8-bit shifting circuit that can perform rotating right or rotating left. An addi- tional I-bit control signal, lr, specifies the desired direction. 1. Design the circuit using one rotate-right circuit, one rotate-left circuit, and one 2-to-1 multiplexer to select the desired result. Derive the code. 2. Derive a testbench and use simulation to verify operation of the code. 3. Synthesize the circuit, program the FPGA, and verify its operation. 4. This circuit can also be implemented by one rotate-right shifler with pre- and post- reversing circuits. The reversing circuit either passes the original input or reverses the input bitwise (e.g., if an 8-bit input is the reversed result becomes aoala2a3a5a5a6a7R).epeat steps 2 and 3. 5. Check the report files and compare the number of logic cells and propagation delays of the two designs. 6. Expand the code for a 16-bit circuit and synthesize the code. Repeat steps 1 to 5. 7. Expand the code for a 32-bit circuit and synthesize the code. Repeat steps 1 to 5. 3.11.2 Dual-priority encoder A dual-priority encoder returns the codes of the highest or second-highest priority requests. The input is a 12-bit r e q signal and the outputs are f i r s t and second, which are the 4-bit binary codes of the highest and second-highest priority requests, respectively. 1 . Design the circuit and derive the code. 2. Derive a testbench and use simulation to verify operation of the code. 3. Design a testing circuit that displays the two output codes on the seven-segment LED display of the prototyping board, and derive the code. 4. Synthesize the circuit, program the FPGA, and verify its operation. 3.11.3 BCD incrementor The binary-coded-decimal (BCD) format uses 4 bits to represent 10 decimal digits. For example, 25910is represented as "0010 0101 1001" in BCD format. A BCD incrementor adds 1 to a number in BCD format. For example, after incrementing, "0010 0 101 1001" (i.e., 25910)becomes "0010 01 10 0000" (i.e., 26010). 1. Design a three-digit 12-bit incrementor and derive the code. 2. Derive a testbench and use simulation to verify operation of the code. 3. Design a testing circuit that displays three digits on the seven-segment LED display and derive the code. 4. Synthesize the circuit, program the FPGA, and verify its operation. 3.11.4 Floating-point greater-than circuit A floating-point greater-than circuit compares two floating-point numbers and asserts output, g t , when the first number is larger than the second number. Assume that the two numbers are represented in the format discussed in Section 3.9.4. 1. Design the circuit and derive the code. 2. Derive a testbench and use simulation to verify operation of the code. 3. Design a testing circuit and derive the code. 4. Synthesize the circuit, program the FPGA, and verify its operation. 3.11.5 Floating-point and signed integer conversion circuit A number may need to be converted to different formats in a large system. Assume that we use the 13-bit format in Section 3.9.4 for the floating-point representation and the 8-bit signed data type for the integer representation. An integer-to-floating-point conversion circuit converts an 8-bit integer input to a normalized, 13-bit floating-point output. A floating-point-to-integer conversion circuit reverses the operation. Since the range of a floating-point number is much larger, conversion may lead to the underflow condition (i.e., the magnitude of the converted number is smaller than "00000001") or the overflow condition (i.e., the magnitude of the converted number is larger than "01111111"). 1. Design an integer-to-floating-point conversion circuit and derive the code. 2. Derive a testbench and use simulation to verify operation of the code. 3. Design a testing circuit and derive the code. 4. Synthesize the circuit, program the FPGA, and verify its operation. 5. Design a floating-point-to-integer conversion circuit. In addition to the 8-bit integer output, the design should include two status signals, uf and of, for the underflow and overflow conditions. Derive the code and repeat steps 2 to 4. 3.11.6 Enhanced floating-point adder The floating-point adder in Section 3.9.4 discards the lower bits when they are shifted out (it is known as round to zero). A more accurate method is to round to the nearest even, as defined in the IEEE Standard for Binary Floating-Point Arithmetic (IEEE Std 754). Three extra bits, known as the guard, round, and sticky bits, are required to implement this method. If you learned floating-point arithmetic before, modify the floating-point adder in Section 3.9.4 to accommodate the round-to-the-nearest-even method. CHAPTER 4 REGULAR SEQUENTIAL CIRCUIT 4.1 INTRODUCTION A sequential circuit is a circuit with memory, which forms the internal state of the circuit. Unlike a combinational circuit, in which the output is a function of input only, the output of a sequential circuit is a hnction of the input and the internal state. The synchronous design methodology is the most commonly used practice in designing a sequential circuit. In this methodology, all storage elements are controlled (i.e., synchronized) by a global clock signal and the data is sampled and stored at the rising or falling edge of the clock signal. It allows designers to separate the storage components from the circuit and greatly simplifies the development process. This methodology is the most important principle in developing a large, complex digital system and is the foundation of most synthesis, verification, and testing algorithms. All of the designs in the book follow this methodology. 4.1.1 D FF and register The most basic storage component in a sequential circuit is a D-type flip-flop (D FF). The symbol and function table of a positive edge-triggered D FF are shown in Figure 4.l(a). The value of the d signal is sampled at the rising edge of the clk signal and stored to FF. A D FF may contain an asynchronous reset signal to clear the FF to 0. Its symbol and function table are shown in Figure 4.l(b). Note that the reset operation is independent of the clock signal. FPGA Prototyping b,v Verilog Examples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. clk q* (a) D FF FI reset clk q* reset (b) D FF with asynchronous reset reset clk en q* - reset external input clk (c) D FF with synchronous enable Figure 4.1 Block diagram and functional table of a D FF. - next-state d > -A . logic state-next ,lk 'n output logic output sate Figure 4.2 Block diagram of a synchronous system. The three main timing parameters of a D FF are T,, (clock-to-q delay), TSet,(,setup time), and Thol(hdold time). T,,is the time required to propagate the value of d to q at the rising edge of the clock signal. The d signal must be stable around the sampling edge to prevent the FF from entering the metastable state. TSet,a,nd Tholspdecify the time intervals before or after the sampling edge. A D FF provides 1-bit storage. A collection of D FFs can be grouped together to store multiple bits and is known as a register. 4.1.2 Synchronous system Block diagram The block diagram of a synchronous system is shown in Figure 4.2. It consists of the following parts: State register: a collection of D FFs controlled by the same clock signal Next-state logic: combinational logic that uses the external input and internal state (i.e., the output of register) to determine the new value of the register Output logic: combinational logic that generates the output signal Maximal operating frequency One of the most difficult design aspects of a sequential circuit is to ensure that the system timing does not violate the setup and hold time constraints. In a synchronous system, the storage components are grouped together and treated as a single register, as shown in Figure 4.2. We need to perform timing analysis on only one memory component. The timing of a sequential circuit is characterized by fmax, the maximal clockj?equency, which specifies how fast the circuit can operate. The reciprocal off,,, specifies Tclock, the minimal clock period, which can be interpreted as the interval between two sampling edges of the clock. To ensure correct operation, the next value must be generated and stabilized within this interval. Assume that the maximal propagation delay of next-state logic is TcombT. he minimal clock period can be obtained by adding the propagation delays and setup time constraint of the closed loop in Figure 4.2: and the maximal clock rate is the reciprocal: + f m a x = 1 - T ~ l ~ ~ Tkcq 1 Tcomb f Tsetup Timing constraint in Xilinx ISEXi'inx" ~ " " ~ fD~ur"ing synthesis, Xilinx software will analyze the synthesized circuit and show fmax in a report. We can also specify the desired operating frequency as a synthesis constraint, and the synthesis software will try to obtain a circuit to satisfy this requirement (i.e., a circuit whose f,,, is equal to or greater than the desired operating frequency). For example, if we use the 50-MHz (i.e., 20-ns period) oscillator on the prototyping board as the clock source, fmax of a sequential circuit must exceed this frequency (i.e., the period must be smaller than 20 ns). The following lines can be added to the constraint file: NET "clk" TNM-NET = "clk"; TIMESPEC "TS-clk" = PERIOD "clk" 20 ns HIGH 50 %; This indicates that the clk signal has a maximal period of 20 ns (i.e., 50 MHz) and a duty cycle of 50%. After synthesis, we can check the relevant timing information by invoking the View Design Summary process from the ISE's Processes window. The Timing Constraints section shows whether the imposed constraints are met, and the Static Timing Report section provides more detailed timing information. 4.1.3 Code development Our code development follows the basic block diagram in Figure 4.2. The key is to separate the memory component (i.e., the register) from the system. Once the register is isolated, the remaining portion is a pure combinational circuit, and the coding and analysis schemes discussed in previous chapters can be applied accordingly. While this approach may make the code a bit more cumbersome at times, it helps us to better visualize the circuit architecture and avoid unintended memory and subtle mistakes. Based on the characteristics of the next-state logic, we divide sequential circuits into three categories: Regular seqztential circuit. The state transitions in the circuit exhibit a "regular" pattern, as in a counter or shift register. The next-state logic is constructed primarily by a predesigned, "regular" component, such as an incrementor or shifter. FSM. The state transitions in the circuit do not exhibit a simple, repetitive pattern. The next-state logic is constructed by "random logic" and synthesized from scratch. It should be called a random sequential circuit, but is commonly known as an FSM (finite state machine). FSMD. The circuit consists of a regular sequential circuit and an FSM. The two parts are known as a data path and a controlpath, and the complete circuit is known as an FSMD (FSMwith data path). This type of circuit is used to implement an algorithm represented by register-transfer (RT) methodology, which describes system operation by a sequence of data transfers and manipulations among registers. The three types of circuits are discussed in this and two subsequent chapters. 4.2 HDL CODE OF THE FF AND REGISTER Describing storage components in HDL is a subtle procedure, and there are many ways to do it. In fact, one common problem encountered by a new HDL user is the inference of unintended latches and buffers. Instead of covering all possible forms of syntactic descriptions, we introduce the code templates for several commonly used memory components. Since our development process separates the register and the combinational circuit, these components are sufficient for all designs in this book. The components are: DFF Register Register file All code templates use always blocks. As discussed in Section 3.3.2, nonblocking assignments should be used for the memory elements, whose basic syntax is [variable-name] <= [expression]; This type of assignment can avoid potential race condition and eliminate the discrepancy between simulation and synthesis. This topic is explained in detail in Section 7.1. We consider three types of D FFs: D FF without asynchronous reset D FF with asynchronous reset D FF with synchronous enable The first two are the most basic memory components and can be found in the library of any device technology. The third can be constructed from a simple D FF. We include the code since it is a frequently used memory component and can be mapped to the FF of the Spartan-3 device's logic cell. D FF without asynchronous reset The hnction table of a D FF is shown in Figure 4. I (a) and the code is shown in Listing 4.1. Listing 4.1 D FF without asynchronous reset module d-ff ( input wire clk, input wire d , i output reg q 1; / / bod? always @(posedge clk) lo q <= d ; endmodule The rising edge is expressed by the posedge c l k event in the sensitivity list. The posedge (for "positive edge") keyword specifies the direction of the c l k signal changing toward 1. It indicates that the always block is activated only at the rising edge of the c l k signal, a condition reflecting the characteristics of an edge-triggered FF. Note that the d signal is not included in the sensitive list. This is consistent with the fact that the d signal is sampled only at the rising edge of the c l k signal, and a change in its value does not trigger any immediate response. D FF with asynchronous reset A D FF may contain an asynchronous reset signal, as shown in the hnction table of Figure 4.l(b). The signal clears the D FF to 0 any time and is not controlled by the clock signal. It actually has a higher priority than the regularly sampled input. Using an asynchronous reset signal violates the synchronous design methodology and thus should be avoided in normal operation. Its major application is to perform system initialization. For example, we can generate a short reset pulse to force a system to an initial state after turning on the power. The code for a D FF with asynchronous reset is shown in Listing 4.2. Listing 4.2 D FF with asynchronous reset module d-f f - r e s e t ( input wire clk, input wire d, 5 output reg q 1; reset, // bodv always @(posedge clk, posedge reset) 10 if (reset) q <= l'bO; else q <= d ; 15 endmodule Note that the posedge reset event is also included in the sensitivity list and its value is checked first in the if statement. The q signal is cleared to 0 if it is asserted and its operation is independent of the c l k signal. en clk reset reset Figure 4.3 D FF with synchronous enable. D FF with synchronous enable A D FF may include an additional control signal, en, to enable the FF to sample the input value. Its symbol and functional table are shown in Figure 4. I(c). Note that the en signal is examined only at the rising edge of the clock and thus is synchronous. If it is not asserted, the FF keeps its previous value. The code is shown in Listing 4.3. Listing 4.3 One-segment coding style for a D FF with synchronous enable module d-f f - e n - l s e g \ input wire clk, r e s e t , input wire en, 5 input wire d, output reg q ); // hod?, In always O(posedge clk, posedge r e s e t ) if (reset) q <= 1'bO; else if (en) q <= d ; I5 endmodule Note that there is no else branch after the second if statement. According to Verilog definition, a variable keeps its previous value if it is not assigned. If en is 0, q keeps its previous value. Thus, omission of the else branch describes the desired behavior of this FF. The enabling feature of this D FF is usehl in maintaining synchronism between a fast subsystem and a slow subsystem. For example, assume that the operation rates of a fast and a slow subsystem are 50 MHz and 1 MHz. Instead of using a derived 1-MHz clock to drive the slow subsystem, we can generate a periodic enable tick that is asserted one clock cycle every 50 clock cycles. The slow subsystem is disabled (i.e., keeps the previous state) for the remaining 49 clock cycles. The same scheme can also be applied to eliminate a gated clock signal. Since the enable signal is synchronous, this circuit can be constructed by a regular D FF and simple next-state logic. The code is shown in Listing 4.4, and its block diagram is shown in Figure 4.3. Listing 4.4 Two-segment coding style for a D FF with synchronous enable module d-f f -en_2seg ( input wire clk, reset, input wire en, , input wire d, output reg q ); // signal declaration IU reg r-reg, r-next; // body / / D FF always @ ( p o s e d g e clk , posedge reset IS if (reset) r - r e g <= 1 'bO; else r - r e g <= r - n e x t ; 20 / / n e x t - s t a t e l o g i c always Q* i f (en) r-next = d; else r-next = r-reg; // output logic always Q* q = r-reg; 30 endmodule For clarity, we use suffixes n e x t and r e g to emphasize the next input value and the registered output of an FF. They are connected to the d and q signals of a D FF. The code in Listing 4.3 can be considered as shorthand for this more explicit description. 4.2.2 Register A register is a collection of D FFs that are controlled by the same clock and reset signals. Like a D FF, a register can have an optional asynchronous reset signal and a synchronous enable signal. The code is identical to that of a D FF except that the array data type is needed for the relevant input and output signals. For example, an 8-bit register with asynchronous reset is shown in Listing 4.5. Listing 4.5 Register module reg-reset ( input wire clk, reset, input wire [7:0] d , 5 output reg [7:01 q ); // body always @ (posedge clk , posedge r e s e t ICI if (reset) q <= 0 ; else q <= d ; I endmodule 4.2.3 Register file A register file is a collection of registers with one input port and one or more output ports. The write address signal, w-addr, specifies where to store data, and the read address signal, r-addr, specifies where to retrieve data. The register file is generally used as fast, temporary storage. The code for a parameterized 2"'-by-B register file is shown in Listing 4.6. Two parameters are defined in this design: W specifies the number of address bits, which implies that there are 2" words in the file, and B specifies the number of bits in a word. Listing 4.6 Parameterized register file module reg-f i l e #( parameter B = 8 , // number of b i t s W = 2 // number o f address 5 ) ( input wire clk, input wire wr-en, i n p u t w i r e [W-1:01 w-addr , r - a d d r , i n p u t wire [B-1:OI w-data, output wire [B-1:Ol r - d a t a 1; bits // s i g r ~ a l declaration 15 reg [B-1:Ol a r r a y - r e g [2**W-1:0] ; // hodv // rz3rire o p e r a t i o n always @(posedge clk) 20 i f (wr-en) a r r a y - r e g [w-addrl <= w - d a t a ; // read operation assign r-data = array-reg [r-addrl ; The code includes several new features. First, a two-dimensional array data type is defined, as in r e g [B-1:OI a r r a y - r e g [ 2 * * ~ - 1 0: 1 ; It indicates that the a r r a y - r e g variable is an array of [2**W-1: 01 elements and each element is with the data type of reg [B-I :01. Second, a signal is used as an index to access an SIMPLE DESIGN EXAMPLES 91 element in the array, as in a r r a y r e g [w-addrl . Although the description is very abstract, Xilinx software recognizes this language construct and can derive the correct implementa- tion accordingly. The array-reg [ . . . I = . . . and . . . = array-reg [. . .I statements infer decoding and multiplexing logic, respectively. Some applications may need to retrieve multiple data words at the same time. This can be done by adding an additional read port: r-data2 = array-reg [r-addr-21 ; 4.2.4 Storage components in a Spartan3 devicexilinX Specific In a Spartan-3 device, each logic cell contains a D FF with asynchronous reset and synchronous enable. These D FFs basically constitute the register of Figure 4.2. Since a logic cell also contains a four-input LUT, it will be wasteful if the cell is used simply as 1bit of a massive storage. The Spartan-3 device also has distributed RAM (random access memory) and block RAM modules, and they can be used for larger storage requirements. These modules can be configured for synchronous operation, and their characteristics are somewhat like a restricted version of the register file. The configuration and inference of these modules are discussed in Chapter 12. 4.3 SIMPLE DESIGN EXAMPLES We illustrate the construction of several simple, representative sequential circuits in this section. 4.3.1 Shift register Free-running shift register A free-running shift register shifts its content to the left or right by one position in each clock cycle. There is no other control signal. The code for an N-bit free-running shift-right register is shown in Listing 4.7. Listing 4.7 Free-running shift register module free-run-shift-reg #(parameter N=8) ( input wire clk, reset, 5 input wire s-in, output wire s-out 1; //signal declaration lo reg [N-1:0] r-reg; w i r e [ N - 1 :01 r-next ; // body // r e g i s t e r 15 always @ ( p o s e d g e clk, posedge reset) i f (reset) r-reg <= 0 ; e 1se r - r e g <= r - n e x t ; ZU // next-state logic a s s i g n r - n e x t = { s - i n , r - r e g [ N - 1 : 111 ; // olrtput logic assign s-out = r-reg[OI; 5 endmodule The next-state logic is a I-bit shifter, which shifts r - r e g right one position and inserts the serial input, s-in, to the MSB. Since the 1-bit shifter involves only reconnection of the input and output signals, no real logic is needed. Its propagation delay represents the smallest possible Tcornabn,d the corresponding f,,, represents the highest clock rate that can be achieved for a given device technology. Universal shift register A universal shift register can load parallel data, shift its content left or right, or remain in the same state. It can perform parallel-to-serial operation (first loading parallel input and then shifting) or serial-to-parallel operation (first shifting and then retrieving parallel output). The desired operation is specified by a 2-bit control signal, c t r l . The code is shown in Listing 4.8. Listing 4.8 Universal shift register module univ-shif t - r e g # ( p a r a m e t e r N=8) ( input wire clk, reset, input wire [1:01 c t r l , input wire [N-1:01 d , output wire CN-1:Ol q ); IO / / s i g n a l d e c l a r a t i o n reg [N-1:01 r - r e g , r - n e x t ; // body // register 15 always Q(posedge c l k , posedge r e s e t ) if (reset) r - r e g <= 0 ; else r - r e g <= r - n e x t ; 20 // next-state logic always a* case ( c t r l ) 2 'b00: r-next = r-reg; // no op 25 2'bOl: r-next = {I--reg[N-2:O], d[O]); // s h i f t l e f t 2'blO: r-next = {d[N-11, r-reg[N-1:ll); // s h i f t right default: r-next = d; // load endcase // ot~tput logic 10 assign q = r-reg; SIMPLE DESIGN EXAMPLES 93 endmodule The next-state logic uses a 4-to-1 multiplexer to select the desired next value of the register. Note that the LSB and MSB of d (i.e., d [O] and d [N-11) are used as serial input for the shift-left and shift-right operations. In a Xilinx Spartan-3 device, a logic cell's 4-input LUT is implemented by a 16-by-1 SRAM. The same SRAM can also be configured as a cascading chain of sixteen 1-bit SRAM Xilinx cells, which resembles a 16-bit shift register. This can be used to construct certain forms specific of shift register and leads to very efficient implementation. 4.3.2 Binary counter and variant Free-running binary counter A free-running binary counter circulates through a binary sequence repeatedly. For example, a 4-bit binary counter counts from "OOOO", "0001", . . ., to "1111" and wraps around. The code for a parameterized N-bit free-running binary counter is shown in Listing 4.9. Listing 4.9 Free-running binary counter module f ree-run-bin-counter #(parameter N=8) ( input wire clk, reset, 5 output wire max-tick, output wire [N-1:01 q 1; //signal declaration lo r e g [N-1:Ol r - r e g ; w i r e [N-1:01 r-next ; // body // register IS always @ ( p o s e d g e clk, posedge reset) i f (reset) r - r e g <= 0 ; / / { N { l b 'O}} e1se r - r e g <= r - n e x t ; 10 // next-.state logic assign r-next = r-reg + 1; // output logic assign q = r-reg; zs a s s i g n m a x - t i c k = ( r - r e g = = 2 * * N - 1 ) ? l'bl : l'bO; //can also use (r_reg=={N{l' b l ) ) ) endmodule The next-state logic is an incrementor, which adds 1 to the register's current value. By definition of the + operator, the addition implicitly wraps around after the r x e g reaches " 1. . .I". The circuit also consists of an output status signal, max-tick,which is asserted when the counter reaches the maximal value, "1. . .I" (which is equal to 2 N - 1). 94 REGULAR SEQUENTIAL CIRCUIT Table 4.1 Function table of a universal binary counter syn-clr load en up q* Operation 1 - - - 00. . .00 synchronous clear 0 1 - - d parallel load 0 0 1 1 q+l count up 0 0 1 0 q-1 count down 0 0 0- 9 pause The max-tick signal represents a special type of signal that is asserted for a single clock cycle. In this book, we call this type of signal a tick and use the suffix - t i c k to indicate a signal with this property. It is commonly used to interface with the enable signal of other sequential circuits. Universalbinary counter A universal binary counter is more versatile. It can count up or down, pause, be loaded with a specific value, or be synchronously cleared. Its hnctions are summarized in Table 4.1. Note the difference between the r e s e t and syn-clr signals. The former is asynchronous and should only be used for system initialization. The latter is sampled at the rising edge of the clock and can be used in normal synchronous design. The code for this counter is shown in Listing 4.10. Listing 4.10 Universal binary counter module univ-bin-counter #(parameter N=8) ( input wire clk, reset, % input wire syn-clr , load, en, up, input wire [N-1:OI d, output wire max-tick, min-tick, output wire [N-1:Ol q ); I I1 //signal declaration reg [N-1:Ol r-reg, r-next; // body 15 // register always @(posedge clk, posedge reset) i f (reset) r-reg <= 0 ; // else 20 r-reg <= r-next; // next-state logic always Q* i f (syn-clr) 25 r-next = 0; e l s e i f (load) r-next = d ; e l s e i f (en & up) SIMPLE DESIGN EXAMPLES 95 r-next = r-reg + 1; 30 else if (en & -up) r-next = r-reg - 1; else r-next = r-reg; 35 // output l o g i c assign q = r-reg; a s s i g n m a x - t i c k = ( r - r e g = = 2 * * N - 1 ) ? l'bl : l'bO; a s s i g n m i n - t i c k = ( r - r e g = = O ) ? l'bl : l'bO; - - The next-state logic follows the functional table and is described by an always block, which contains an if statement to prioritize the desired operations. Mod-m counter A mod-m counter counts from 0 to m - 1 and wraps around. A parameterized mod-m counter is shown in Listing 4.1 1. It has two parameters: M, which specifies the limit, rn;and N, which specifies the number of bits needed and should be equal to [log, MI. The code is shown in Listing 4.1 1, and the default value is for a mod-1 0 counter. Listing 4.11 Mod-m counter module mod-m-counter #( parameter N=4, // number of b i t s in counter M = 1 0 // mod-M 5 ( input wire clk, reset, output wire max-tick, output wire [N-1:Ol q 10 ); //signal declaration reg [N-1:01 r-reg; wire [N-1:0] r-next ; I5 // body // r e g i s t e r always @ (posedge clk , posedge reset 1 if (reset) 20 r-reg <= 0 ; else r-reg <= r - n e x t ; // next-state logic 25 a s s i g n r - n e x t = (r-reg==(M-1)) ? 0 : r - r e g + 1 ; // output logic assign q = r-reg; assign max-tick = (r-reg==(M-1)) ? l J b l : l'bO; 30 e n d m o d u l e The next-state logic is constructed by a conditional operator. If the counter reaches M-I, the new value is cleared to 0. Otherwise, it is incremented by 1. Inclusion of the N parameter in the code is somewhat redundant since its value depends on M. A more elegant way is to define a function that calculates N from M automatically. This scheme is discussed in Section 7.4. 4.4 TESTBENCH FOR SEQUENTIAL CIRCUITS A testbench is a program that mimics a physical lab bench, as discussed in Section 1.7. In this section, we illustrate the construction of a simple testbench for the previous universal binary counter. It can serve as a template for other sequential circuits. Development of a more sophisticated testbench is discussed in Section 7.5. The code for the simple testbench is shown in Listing 4.12. Listing 4.12 Testbench for a universal binary counter ' t i m e s c a l e 1 ns/lO ps // The ' t i m e s c a l e d i r e c t i v e s p e c i f i e s t h a t . / / t h e s i m ~ r l a t i o n tinre u n i t i s I trs and // the s i m u l a t o r tinrestep is 10 ps module bin-counter-tb ; // declaration 10 l o c a l p a r a m T = 2 0 ; // c l o c k p e r i o d reg clk, reset; reg syn-clr , load, en, up; reg [2:01 d; wire max-tick, min-tick; li wire [2:01 q ; // clock / / 20 11s c l o c k r u n n i n g f o r e v e r 25 always begin clk = l J b l ; #(T/2) ; clk = l'bO; 10 #(T/2) ; end // r e s e t f o r the f i r s t hu!f c y c l e initial 5 begin reset = 1 'bl; TESTBENCH FOR SEQUENTIAL CIRCUITS 97 #(T/2) ; reset = l'bO; end 40 // other stimulus initial begin / / ==== i n i t i a i n p u t ===== 45 syn-clr = l'bO; load = l'bO; en = l'bO; up = l ' b l ; // count up d = 3'bOOO; @(negedge r e s e t ) ; // wait reset to deassert @ (negedge clk) ; // wait for one clock / / ==== t e s t l o a d ===== load = l ' b l ; d = 3'b011; @ (negedge clk) ; // wait for one clock load = l'bO; repeat (2) @(negedge clk) ; / / ==== t e s t s y n - c l e a r ==== syn-clr = l ' b l ; // assert clear @ (negedge clk) ; s y n - c l r = 1'bO; / / ==== t e s t u p c o u n t e r a n d p a u s e ==== e n = 1' b l ; // c o u n t up = l ' b l ; repeat (lo) @(negedge clk) ; e n = 1'bO; // pause repeat (2) @ (negedge clk) ; en = l ' b l ; repeat (2) @(negedge clk) ; / / ==== t e s t down c o u n t e r ==== up = l ' b O ; repeat (10) @(negedge clk) ; / / ==== w a i t s t a t e m e n t ==== // c o n t i n u e u n t i l q=2 wait (q==2) ; @(negedge clk) ; up = l ' b l ; // continue u n t i l min-tick becomes 1 @(negedge clk) ; wait (min-tick) ; @(negedge clk) ; up = l ' b O ; / / ==== a b s o l u t e d e l a y ==== #(4*T); // w a i t f o r 80 ns e n = 1'bO; // pause #(4+T); // w a i t f o r 80 ns / / ==== s t o p s i m u l a t i o n ==== // return to i n t e r a c t i v e simulation mode $stop ; 98 REGULAR SEQUENTIAL CIRCUIT VI, end endmodule The code consists of a component instantiation statement, which creates an instance of a 3-bit counter, and three segments, which generate a stimulus for clock, reset, and regular inputs. The clock generation is specified by an always block: always begin clk = l'bl; #(T/2) ; clk = l'bO; #(T/2) ; end The T term is a constant that represents the number of time units in a clock period. It is defined as localparam T=20; // clock period Note that the always block has no sensitivity list and repeats itself forever. The clk signal is assigned between 0 and 1 alternately, and each value lasts for half a period. The reset stimulus is specified by an initial block: initial begin reset = 1' b l ; #(T/2) ; reset = l'bO; end An initial block is executed once at the beginning of a simulation. It indicates that the reset signal is set to 1 initially and changed to 0 after half a period. The block represents the "power-on" condition, in which the reset signal is asserted momentarily to clear the system to the initial state. Note that, by default, the x value (for unknown), not 0, is assigned to a variable. Using a short reset pulse is a good mechanism for performing system initialization. The second initial block generates a stimulus for other input signals. We first test the load and clear operations and then exercise counting in both directions. The final %stop function forces the simulator to stop simulation. For a synchronous system with positive edge-triggered FFs, an input signal must be stable around the rising edge of the clock signal to satisfy the setup and hold time constraints. One easy way to achieve this is to change an input signal's value during the I-to-0 transition of the clk signal. We can wait for this transition edge by using @ ( negedge c l k ) ; The negedge clk event specifies the condition that the clk signal changes to 0 (i.e., negative edge). Note that each statement represents a new falling edge, which corresponds to the advancement of one clock cycle. In our template, we generally use this statement to specify the progress of time. For multiple clock cycles, we can use a repeat statement, as in repeat (10) @(negedge c l k ) ; // repeat 10 times Several additional timing control constructs are shown at the end of the initial block. We can wait until a special condition, such as "when q is equal to 2" CASE STUDY 99 Figure 4.4 Testbench waveform. wait (q==2); or wait until a signal changes, such as wait (min-tick) ; or wait for an absolute time, such as #(4*T); // w a i t f o r 4 T If an input signal is modified after these statements, we need to make sure that the input change does not occur at the rising edge of the clock. An additional Q( n e g e d g e clk) ; statement should be added when needed. We can compile the code and perform simulation. Part of the simulated waveform is shown in Figure 4.4. 4.5 CASE STUDY After examining several simple circuits, we discuss the design of more sophisticated examples in this section. 4.5.1 LED time-multiplexing circuit The S3 board has four seven-segment LED displays, each containing seven bars and one small round dot. To reduce the use ofFPGA's I10 pins, the S3 board uses a time-multiplexing sharing scheme. In this scheme, the four displays have their individual enable signals but share eight common signals to light the segments. All signals are active low (i.e., enabled when a signal is 0). The schematic of displaying a "3" on the rightmost LED is shown in Figure 4.5. Note that the enable signal (i.e., an) is "1 110". This configuration clearly can enable only one display at a time. We can time-multiplex the four LED patterns by enabling the four displays in turn, as shown in the simplified timing diagram in Figure 4.6. If the refreshing rate of the enable signal is fast enough, the human eye cannot distinguish the on and off intervals of the LEDs and perceives that all four displays are lit simultaneously. This scheme reduces the number of 110 pins from 32 to 12 (i.e., eight LED segments plus four enable signals) but requires a time-multiplexing circuit. Two variations of the circuit are discussed in the following subsections. 100 REGULAR SEQUENTIAL CIRCUIT OaOb leI f- 0 g -. 1 dp - Figure 4.5 Time-multiplexed seven-segment LED display. Figure 4.6 Timing diagram of a time-multiplexed seven-segment LED display. CASE STUDY 101 disp-mux reset (a) Symbol in0 , in1 /8 / in2 '8 / in3 '8 8' 01 10 I / sseg 8 / / 18 q-next +I '/d - = q-reg ,/ q_reg[17:161 18 18 18 2 clk reset - 2-to-4 decoder / an 4 (b) Block diagram Figure 4.7 Symbol and block diagram of a time-multiplexing circuit. Time multiplexing with LED patterns The symbol and block diagram of the timemultiplexing circuit are shown in Figure 4.7. It takes four seven-segment LED patterns, in3, in2, i n l , and inO, and passes them to the output, sseg, in accordance with the enable signal. The refresh rate of the enable signal has to be fast enough to fool our eyes but should be slow enough so that the LEDs can be turned on and off completely. The rate around the range 1000 Hz should work properly. In our design, we use an 18-bit binary counter for this purpose. The two MSBs are decoded to generate the enable signal and are used as the selection signal for multiplexing. The refreshing rate of an individual bit, such as an [OI , becomes ~ H Z wh, ich is about 800 Hz. The code is shown in Listing 4.13. Listing 4.13 LED time-multiplexing circuit with LED patterns module disp-mux ( input wire clk, reset, i n p u t C7: 01 i n 3 , i n 2 , i n 1 , i n O , 5 output reg [3:0] an, // enable, I-out-of-4 o u t p u t r e g C7:OI s s e g // l e d s e g m e n t s asserted low ); // constant declaration 10 // r e f r e s h i n g r a t e arottnd 800 Hz (50 MHz/2"16) localparam N = 18; 102 REGULAR SEQUENTIAL CIRCUIT // signal declaration reg CN-1:OI q-reg; 15 wire [N-1:OI q-next ; // N-bit counter // r e g i s t e r always Q(posedge clk , posedge reset 20 if (reset) q-reg <= 0 ; else q-reg <= q-next; 2s // n e x t - s t a t e l o g i c assign q-next = q-reg + 1; // 2 MSBs o f c o u n t e r t o c o n t r o l 4 - t o - l m u l t i p l e x i n g // and to g e n e r a t e a c t i v e - l o w enable s i g n a l 30 a l w a y s Q * case (q-reg [N-1: N-21) 2'bOO: begin an = 4'blllO; sseg = inO; end 2'bOl: begin an = 4'bllOl; sseg = inl; end 2'blO: begin an = 4'b1011; sseg = in2; end default : begin an = 4'b0111; sseg = in3; end endcase endmodule We use the testing circuit in Figure 4.8 to verify operation of the LED time-multiplexing circuit. It uses four 8-bit registers to store the LED patterns. The registers use the same 8-bit switch as input but are controlled by individual enable signals. When we press a pushbutton, the corresponding register is enabled and the switch pattern is loaded to that register. The code is shown in Listing 4.14. Listing 4.14 Testing circuit for time multiplexing with LED patterns module disp-mux-test ( input wire clk, -d q en > I-d q- en > -in0 --. iinn12 in3 sseg . an sseg an I-d q en > disp-mux reset -d q en > Figure 4.8 LED time-multiplexing testing circuit. input wire [3:01 btn, 5 i n p u t w i r e C7:Ol sw, output wire [3:0] an, output wire [7:01 sseg 1; lo // s i g n a l d e c l a r a t i o n reg [7:0] d3_reg, d2_reg, dl-reg, do-reg; // i n s t a n t i a t e 7 - s e g LED d i s p l a y t i m e - m u l t i p l e x i n g module disp-mux disp-unit I5 . . ( . c l k ( c l k ) , . r e s e t ( l ' b o ) , .i n O ( d 0 - r e g ) , . i n l ( d l - r e g ) , .in2(d2_reg), .in3(d3_reg), an(an), sseg(sseg)) ; // registers for 4 led patterns always @(posedge clk) 20 begin if (btn[3]) d 3 - r e g <= sw; i f ( b t n [21) d2-reg <= sw; if (btnC11) d l - r e g <= sw; i f ( b t n [Ol) do-reg <= sw; end endmodule hex-to-7seg hex2 decoder sseg[6:0] hex3 clk 2-to-4 reset decoder Figure 4.9 Block diagram of a hexadecimal time-multiplexingcircuit. Time multiplexing with hexadecimal digits The most common application of a seven-segment LED is to display a hexadecimal digit. The decoding circuit is discussed in Section 3.9.1. To display four hexadecimal digits with the previous time-multiplexing circuit, four decoding circuits are needed. A better alternative is first to multiplex the hexadecimal digits and then decode the result, as shown in Figure 4.9. This scheme requires only one decoding circuit and reduces the width of the 4-to-1 multiplexer from 8 bits to 5 bits (i.e., 4 bits for the hexadecimal digit and 1 bit for the decimal point). The code is shown in Listing 4.15. In addition to clock and reset, the input consists of four 4-bit hexadecimal digits, hex3, hex2, hexl, and hex0, and four decimal points, which are grouped as one signal, dp-in. Listing 4.15 LED time-multiplexingcircuit with hexadecimal digits module disp-hex-mux ( input wire clk, r e s e t , input wire [3:0] h e x 3 , hex2, h e x l , h e x 0 , // hex d i g i t s 5 input wire [3:01 dp-in, // 4 decimal points o u t p u t r e g C3:OI a n , // e n a b l e I - o u t - o f - 4 a s s e r t e d low output reg [7:01 sseg // led segments 1; lo // constant d e c l a r a t i o n // r e f r e s h i n g r a t e around 800 Hz ( 5 0 MH.z/2"16) localparam N = 18; // internal signal declaration reg [N-1:OI q - r e g ; 15 wire [N-1:O] q - n e x t ; r e g [ 3 : 01 h e x - i n ; reg dp; // N-bit counter ro / / r e g i s t e r always @(posedge clk, posedge r e s e t ) if (reset) q-reg <= 0 ; else s q-reg <= q-next; // next-state logic a s s i g n q-next = q-reg + 1; 30 // 2 MSBs o f c o u n t e r t o c o n t r o l 4 - t o - l m u l t i p l e x i n g // and to generate active-low enable s i g n a l always B* c a s e (q-reg [N-1: N-21) 2'bOO: 35 begin an = 4'bIllO; hex-in = hex0; dp = dp-in 101 ; end 40 2'bOl: begin an = 4'bllOl; hex-in = hexl; dp = dp-in [l] ; end 2'blO: begin an = 4'blOll; hex-in = hex2; dp = dp-in [2] ; end default: begin an = 4'bOlll; 55 hex-in = hex3; dp = dp-in [31 ; end endcase 60 // hex t o seven-segment l e d d i s p l a y always B* begin c a s e (hex-in) 4'hO : sseg [6:01 = 7' b0000001; 65 4'hl: sseg[6:0] = 7'b1001111; 4'h2: sseg [6:0] = 7'b0010010; 4'h3: sseg [6:0] = 7'b0000110; 4'h4: sseg[6:0] = 7'b1001100; 4'h5: sseg[6:0] = 7'b0100100; 4'h6: sseg [6:0] = 7'b0100000; 4'h7: sseg[6:0] = 7'b0001111; 4'h8 : sseg [6:01 = 7'b0000000 ; 4'h9: sseg [6:0] = 7'b0000100; 4'ha: sseg [6:0] = 7'b0001000; 75 4'hb: sseg [6:0] = 7'b1100000; 4'hc: sseg [6:0] = 7'b0110001; 4'hd: sseg [6:0] = 7'b1000010; 4'he: sseg [6:0] = 7'b0110000; d e f a u l t : sseg [6:01 = 7'b0111000; / / 4 ' h f 80 endcase sseg C71 = dp; end endmodule To verify operation of this circuit, we define the 8-bit switch as two 4-bit unsigned numbers, add the two numbers, and show the two numbers and their sum on the four-digit seven-segment LED display. The code is shown in Listing 4.16. Listing 4.16 Testing circuit for time multiplexingwith hexadecimal digits module hex-mux-test ( i n p u t w i r e clk , i n p u t w i r e [7:01 sw, 5 o u t p u t w i r e [3:01 an, o u t p u t w i r e [7:0] sseg 1; // signal declaration 10 w i r e [3:01 a , b ; w i r e [7:01 sum; / / i n s t a n t i a t e 7 - s e g LED d i s p l a y module disp-hex-mux disp-unit IS (.clk(clk), .reset(llbO), .hex3 (sum [7:43 ) , . hex2 (sum C3:01) , . hex1 (b), .hexO(a) .dp_in(4'blOll), .an(an), .sseg(sseg)); // adder 20 a s s i g n a = sw[3:01 ; a s s i g n b = sw [7:41 ; a s s i g n sum = {4'bO,a) + {4'bO,b); endmodule Simulation consideration Many sequential circuit examples in the book operate at a relatively slow rate, as does the enable pulse of the LED time-multiplexing circuit. This can be done by generating a single-clock enable tick from a counter. An 18-bit counter is used in this circuit: localparam N = 18; r e g [N-1:Ol q-reg; w i r e [N-1 :01 q-next ; ... a s s i g n q-next = q-reg + 1; Because of the counter's size, simulating this type of circuit consumes a significant amount of computation time (i.e., 218 clock cycles for one iteration). Since our main interest is in CASE STUDY 107 the multiplexing part of the code, most simulation time is wasted. It is more efficient to use a smaller counter in simulation. We can do this by modifying the constant statement localparam N = 4; when constructing the testbench. This requires only 24 clock cycles for one iteration and allows us to better exercise and observe the key operations. Instead of using a constant and modifying code between simulation and synthesis, an alternative is to define N as a parameter. During instantiation, we can assign different values for simulation and synthesis. 4.5.2 Stopwatch We consider the design of a stopwatch in this subsection. The watch displays the time in three decimal digits, and counts from 00.0 to 99.9 seconds and wraps around. It contains a synchronous clear signal, clr, which returns the count to 00.0, and an enable signal, go, which enables and suspends the counting. This design is basically a BCD (binarycoded decimal) counter, which counts in BCD format. In this format, a decimal number is represented by a sequence of 4-bit BCD digits. For example, 13gI0is represented as "0001 00 1 1 1001" and the next number in sequence is 14OI0,which is represented as "000 1 0 100 0000". Since the S3 board has a 50-MHz clock, we first need a mod-5,000,000 counter that generates a one-clock-cycle tick every 0.1 second. The tick is then used to enable counting of the three-digit BCD counter. Design I Our first design of the BCD counter uses a cascading structure of three decade (i.e., mod-10) counters, representing counts of 0.1, 1, and 10 seconds, respectively. The decade counter has an enable signal and generates a one-clock-cycle tick when it reaches 9. We can use these signals to "hook" the three counters. For example, the 10-second counter is enabled only when the enable tick of the mod-5,000,000 counter is asserted and both the 0.1- and I -second counters are 9. The code is shown in Listing 4.17. Listing 4.17 Cascading description for a stopwatch module stop-watch-cascade ( input wire clk, input wire go, clr, 5 o u t p u t w i r e [3:0] d2, dl, do ); // declaration localparam DVSR = 5000000; 10 r e g [22:0] ms-reg; w i r e [22:01 ms-next ; reg [3:0] d2_reg, dl-reg, do-reg; w i r e [3:01 d2-next , dl-next , do-next ; wire dl-en, d2-en, do-en; 15 wire ms-tick, do-tick, dl-tick; // body // register always @ ( p o s e d g e clk) 20 begin ms-reg <= ms-next; d2-reg <= dl-next; dl-reg <= dl-next; do-reg <= do-next; 25 end // next-state logic // 0.1 sec tick generator: mod-5000000 a s s i g n ms-next = (clr I I (ms-reg==DVSR && go)) ? 4'bO : 30 (go) ? ms-reg + 1 : ms-reg ; a s s i g n ms-tick = (ms-reg==DVSR) ? l'bl : l J b O ; // 0.1 sec counter a s s i g n do-en = ms-tick; 3s a s s i g n do-next = (clr I I (do-en && dO_reg==9)) ? 4'bO : (do-en) ? do-reg + 1 : do-reg ; a s s i g n do-tick = (dO_reg==9) ? l'bl : 1 'bO; // I sec counter 40 a s s i g n dl-en = ms-tick & do-tick; a s s i g n dl-next = (clr I I (dl-en && dO_reg==9)) ? 4'bO : (dl-en) ? dl-reg + 1 : dl-reg; a s s i g n dl-tick = (dl-reg==9) ? l J b l : l'bO; // I0 sec counter a s s i g n d2-en = ms-tick & do-tick & dl-tick; a s s i g n d2-next = (clr I I (d2-en && d2_reg==9)) ? 4'bO : (d2-en) ? d2-reg + 1 : // output logic a s s i g n do = do-reg; a s s i g n dl = dl-reg; ss a s s i g n d2 = d2-reg; endmodule Note that all registers are controlled by the same clock signal. This example illustrates how to use a one-clock-cycle enable tick to maintain synchronicity. An inferior approach is to use the output of the lower counter as the clock signal for the next stage. Although it may appear to be simpler, it violates the synchronous design principle and is a very poor practice. Design I1 An alternative for the three-digit BCD counter is to describe the entire structure in a nested if statement. The nested conditions indicate that the counter reaches .9,9.9, and 99.9 seconds. The code is shown in Listing 4.18. Listing 4.18 Nested if-statement description for a stopwatch module stop-vatch-if ( i n p u t w i r e clk , CASE STUDY 109 input wire go, clr, o u t p u t w i r e [3:01 d2, dl, do ); // declaration l o c a l p a r a m DVSR = 5000000; r e g [22:01 ms-reg; w i r e [22:01 ms-next ; r e g [3:0] d2_reg, dl-reg, do-reg; r e g [3:01 d2-next , dl-next , do-next ; wire ms-tick; // body // r e g i s t e r a l w a y s @ ( p o s e d g e clk) begin ms-reg <= ms-next; d2-reg <= d2-next; dl-reg <= dl-next; do-reg <= do-next; end // next-state logic // 0 . 1 sec t i c k generator : mod-5000000 a s s i g n ms-next = (clr I I (ms-reg==DVSR && go)) ? 4'bO : (go) ? ms-reg + 1 : ms-reg ; a s s i g n ms-tick = (ms-reg==DVSR) ? l'bl : l'bO; // 3-digit bcd counter always Q* begin // d e f a u l t : keep the previous value do-next = do-reg; dl-next = dl-reg; d2-next = d2-reg; i f (clr) begin do-next = 4'bO; dl-next = 4'bO; d2-next = 4'bO; end e l s e i f (ms-tick) i f (do-reg ! = 9) do-next = do-reg + 1; else // reach XX9 begin do-next = 4'bO; i f (dl-reg ! = 9) dl-next = dl-reg + 1 ; else // reach X99 begin dl-next = 4'bO; i f (d2-reg ! = 9) 110 REGULAR SEQUENTIAL CIRCUIT d2-next = d2-reg + 1; else // reach 999 d2-next = 4'bO; end end end // output logic 65 assign do = do-reg; a s s i g n dl = dl-reg; assign d2 = d2-reg; endmodule Verification circuit To verify operation of the stopwatch, we can combine it with the previous hexadecimal LED time-multiplexing circuit to display the output of the watch. The code is shown in Listing 4.19. Note that the first digit of the LED is assigned to 0 and the go and clr signals are mapped to two pushbuttons of the S3 board. Listing 4.19 Testing circuit for a stopwatch module stop-watch-test ( input wire clk, i n p u t wire [1:01 btn, S output wire [3:01 an, output wire [7:01 sseg 1; // signal d e c l a r a t i o n IIJ w i r e [3:0] d 2 , d l , d o ; // i n s t a n t i a t e 7 - s e g LED d i s p l a y module disp-hex-mux disp-unit (.clk(clk), .reset(lJbO), Is . h e x 3 (4'b0), . h e x 2 (d2), . hex1 (dl), .hex0 (do) 9 . dp_in(4'bllOl), . an(an), .sseg(sseg)); // i n s t a n t i a t e stopwatch stop-watch-if counter-unit 10 (.clk(clk), .go(btn[ll), .clr(btnCOl), .d2(d2), .dl(dl), .dO(d0) 1; endmodule 4.5.3 FIFO buffer A FIFO (first-in-first-out) buffer is an "elastic" storage between two subsystems, as shown in the conceptual diagram of Figure 4.10. It has two control signals, wr and rd,for write and read operations. When wr is asserted, the input data is written into the buffer. The read operation is somewhat misleading. The head of the FIFO buffer is normally always available and thus can be read at any time. The rd signal actually acts like a "remove" FlFO buffer CASE STUDY 111 \ data written into FlFO data read from FlFO Figure 4.10 Conceptual diagram of a FIFO buffer. signal. When it is asserted, the first item (i.e., head) of the FIFO buffer is removed and the next item becomes available. FIFO buffer is a critical component in many applications and the optimized implementation can be quite complex. In this subsection, we introduce a simple, genuine circularqueue-based design. More efficient, device-specific implementation can be found in the Xilinx literature. Circular-queue-basedimplementation One way to implement a FIFO buffer is to add a control circuit to a register file. The registers in the register file are arranged as a circular queue with two pointers. The writepointer points to the head of the queue, and the readpointer points to the tail of the queue. The pointer advances one position for each write or read operation. The operation of an eight-word circular queue is shown in Figure 4.1 1. A FIFO buffer usually contains two status signals, f u l l and empty, to indicate that the FIFO is full (i.e., cannot be written) and empty (i.e., cannot be read), respectively. One of the two conditions occurs when the read pointer is equal to the write pointer, as shown in Figure 4.1 l(a), (0,and (i). The most difficult design task of the controller is to derive a mechanism to distinguish the two conditions. One scheme is to use two FFs to keep track of the empty and full statuses. The FFs are set to 1 and 0 during system initialization and then modified in each clock cycle according to the values of the w r and r d signals. The code is shown in Listing 4.20. Listing 4.20 FIFO buffer module fifo #( p a r a m e t e r B = 8 , // number of W=4 // number of s ) ( input wire clk, reset, input wire rd, wr, input wire [B-1:01 w-data, 10 output wire empty, full, output wire [B-1:OI r-data 1; b i t s in address a word bits //signal declaration 15 reg [B-1:Ol array-reg [2**W-1:Ol ; // r e g i s t e r a r r a y reg [W-1:Ol w-ptr-reg, w-ptr-next , w-ptr-succ; reg [W-1:01 r-ptr-reg , r-ptr-next , r-ptr-succ ; reg full-reg, empty-reg, full-next, empty-next; 112 REGULAR SEQUENTIAL CIRCUIT Figure 4.11 FIFO buffer based on a circular queue. CASE STUDY 113 wire wr-en; ?(I // body // register f i l e write operation a l w a y s @ ( p o s e d g e clk) i f (wr-en) 2s array-reg Cw-ptr-reg1 <= w-data; // register f i l e read operation a s s i g n r-data = array-reg [r-ptr-reg] ; // w r i t e enabled o n l y when FIFO i s not fzill a s s i g n wr-en = wr & -full-reg; 10 // f i f o control logic // r e g i s t e r for read and w'rite pointers a l w a y s @ ( p o s e d g e clk , p o s e d g e reset i f (reset) begin w-ptr-reg <= 0 ; r-ptr-reg <= 0 ; full-reg <= l'bO; empty-reg <= l'bl; end else begin w-ptr-reg <= w-ptr-next ; r-ptr-reg <= r-ptr-next; full-reg <= full-next; empty-reg <= empty-next ; end // next-state logic for read and write p o i n t e r s ro a l w a y s Q * begin // successive pointer values w-ptr-succ = w-ptr-reg + 1; r-ptr-succ = r-ptr-reg + 1; // default: keep old values w-ptr-next = w-ptr-reg; r-ptr-next = r-ptr-reg; full-next = full-reg; empty-next = empty-reg; c a s e ((wr, rd)) // 2 ' b O O : no op 2'bOl: // r e a d i f (-empty-reg) // not empty begin r-ptr-next = r-ptr-succ ; full-next = l'bO; i f (r-ptr-succ==w-ptr-reg) empty-next = l'bl; end 2'blO: // w r i t e i f ("full-reg) / / n o t f u l l 114 REGULAR SEQUENTIAL CIRCUIT begin w-ptr-next = w-ptr-succ ; empty-next = lJbO; i f (w-ptr-succ==r-ptr-reg) full-next = l'bl; end 2'bll: // write and read begin 80 w-ptr-next = w-ptr-succ; r-ptr-next = r-ptr-succ ; end endcase end 85 // output assign full = full-reg; assign empty = empty-reg; 90 e n d m o d u l e The code is divided into a register file and a FIFO controller. The controller consists of two pointers and two status FFs. Its next-state logic examinesthe w r and r d signals and takes actions accordingly. For example, let us consider the "10" case, which implies that only a write operation occurs. The status FF is checked first to ensure that the buffer is not full. If this condition is met, we advance the write pointer by one position and clear the empty status FF. Storing one extra word to the buffer may make it full. This happens if the new write pointer "catches" the read pointer, which is expressed by the w-ptr-succ==r-ptr-reg expression. Verificationcircuit The verification circuit examines the operation of a 24-by-3 FIFO buffer. We use three switches to generate the input data and use two buttons for the w r and r d signals. The 3-bit readout and the f u l l and empty status signals are displayed in five discrete LEDs. Because of bounces of the mechanical contact, a debouncing circuit is needed to generate a clean one-clock-cycle tick. The debouncing module, named debounce, is discussed in Section 6.2.1 but for now can be treated as a predesigned module. The original button inputs are b t n 101 and b t n [I], and the debounced signals are db-btn [O] and db-btn [I]. The code is shown in Listing 4.2 1. Listing 4.21 Testing circuit for a FIFO buffer module fi f o-test ( input wire clk, reset, input wire [1:01 btn, 5 input wire [2:01 sw, output wire [7:0] led ); // signal declaration lo wire [1:0] db-btn; // debounce circuit for btn[O] debounce btn-db-unit0 BIBLIOGRAPHIC NOTES 115 ( . clk(clk), .reset (reset), .sw(btn [Ol) , 15 . db-level (), . db-tick (db-btn LO1 ) ) ; // debounce c i r c u i t for b t n [ l ] debounce btn-db-unit1 ( . clk(clk), . r e s e t (reset), . sw(btn [I]), . d b - l e v e l 0 , . db-tick(db-btn [ll)) ; 20 / / i n s t a n t i a t e a 2 - 2 - b y - 3 f i f o f i f o #(.B(3), .W(2)) fifo-unit ( . clk (clk) , .reset (reset) , . rd(db-btn LO1 ) , .wr (db-btn [I]) , . w-data(sw), . I--data(led [2 :01 ) , . f u l l (led C71) , . empty (led ) ) ; 25 // disable unused leds assign led[5:3] = 3'bOOO; endmodule 4.6 BIBLIOGRAPHIC NOTES The bibliographic information for this chapter is similar to that for Chapter 3. 4.7 SUGGESTED EXPERIMENTS 4.7.1 Programmablesquare-wave generator A programmable square-wave generator is a circuit that can generate a square wave with variable on (i.e., logic 1) and off (i.e., logic 0) intervals. The durations of the intervals are specified by two 4-bit control signals, m and n, which are interpreted as unsigned integers. The on and off intervals are m* 100 ns and n*100 ns, respectively (recall that the period of the S3 onboard oscillator is 20 ns). Design a programmable square-wave generator circuit. The circuit should be completely synchronous. We need a logic analyzer or oscilloscope to verify its operation. 4.7.2 PWM and LED dimmer The duty cycle of a square wave is defined as the percentage of the on interval (i.e., logic 1) in a period. A PWM (pulse width modulation) circuit can generate an output with variable duty cycles. For a PWM with 4-bit resolution, a 4-bit control signal, w, specifies the duty cycle. The w signal is interpreted as an unsigned integer and the duty cycle is $. 1. Design a PWM circuit with 4-bit resolution and verify its operation using a logic analyzer or oscilloscope. 2. Modify the LED time-multiplexing circuit to include the PWM circuit for the an signal. The PWM circuit specifies the percentage of time that the LED display is on. We can control the perceived brightness by changing the duty cycle. Verify the circuit's operation by observing 1 bit of an on a logic analyzer or oscilloscope. 3. Replace the LED time-multiplexing circuit of Listing 4.19 with the new design and use the lower 4 bits of the 8-bit switch to control the duty cycle. Verify operation of the circuit. It may be necessary to go to a dark area to see the effect of dimming. Figure 4.13 Pattern for Experiment 4.7.4. 4.7.3 Rotating square circuit In a seven-segment LED display, a square pattern can be created by enabling the a, b, f, and g segments or the c, d, e, and g segments. We want to design a circuit that circulates the square patterns in the four-digit seven-segment LED display. The clockwise circulating pattern is shown in Figure 4.12. The circuit should have an input, en, which enables or pauses the circulation, and an input, cw, which specifies the direction (i.e., clockwise or counterclockwise) of the circulation. Design the circuit and verify its operation on the prototyping board. Make sure that the circulation rate is slow enough for visual inspection. 4.7.4 Heartbeat circuit We want to create a "heartbeat" for the prototyping board. It repeats the simple pattern in the four-digit seven-segment display, as shown in Figure 4.13, at a rate of 72 Hz. Design the circuit and verify its operation on the prototyping board. 4.7.5 Rotating LED banner circuit The prototyping board has a four-digit seven-segment LED display, and thus only four symbols can be displayed at a time. We can show more information if the data is rotated and moved continuously. For example, assume that the message is 10 digits (i.e., "0123456789"). The display can show the message as "0123", "1234", "2345", .. . , "6789", "7890m, . . . , "0123". The circuit should have an input, en, which enables or pauses the rotation, and an input, d i r , which specifies the direction (i.e., rotate left or right). Design the circuit and verify its operation on the prototyping board. Make sure that the rotation rate is slow enough for visual inspection. 4.7.6 Enhanced stopwatch Modify the stopwatch with the following extensions: Add an additional signal, up, to control the direction of counting. The stopwatch counts up when the up signal is asserted and counts down otherwise. Add a minute digit to the display. The LED display format should be like M. SS .D, where D represents 0.1 second and its range is between 0 and 9, SS represents seconds and its range is between 00 and 59, and M represents minutes and its range is between 0 and 9. Design the new stopwatch and verify its operation with a testing circuit. 4.7.7 Stack A stack is a last-in-first-out buffer in which the last stored data is retrieved first. Storing a data word to a stack is known as apush operation, and retrieving a data word from a stack is known as apop operation. The 110 signals of a stack are similar to those of a FIFO buffer except that we generally use the push and pop signals in place of the w r and r d signals. Design a stack using a register file and verify its operation with a testing circuit similar to the one in Listing 4.2 1. This Page Intentionally Left Blank CHAPTER 5 FSM 5.1 INTRODUCTION An FSM (finite state machine) is used to model a system that transits among a finite number of internal states. The transitions depend on the current state and external input. Unlike a regular sequential circuit, the state transitions of an FSM do not exhibit a simple, repetitive pattern. Its next-state logic is usually constructed from scratch and is sometimes known as "random" logic. This is different from the next-state logic of a regular sequential circuit, which is composed mostly of "structured components, such as incrementors and shifters. In this chapter, we provide an overview of the basic characteristics and representation of FSMs and discuss the derivation of HDL codes. In practice, the main application of an FSM is to act as the controller of a large digital system, which examines the external commands and status and activates proper control signals to control operation of a data path, which is usually composed of regular sequential components. This is known as an FSMD (finite state machine with data path) and is discussed in Chapter 6. 5.1.1 Mealy and Moore outputs The basic block diagram of an FSM is the same as that of a regular sequential circuit and is repeated in Figure 5.1. It consists of a state register, next-state logic, and output logic. An FSM is known as a Moore machine if the output is only a function of state, and is known as a Mealy machine if the output is a function of state and external input. Both types of output may exist in a complex FSM, and we simply refer to it as containing a Moore FPGA Protoyping by Verilog Examples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. 120 FSM I input - - next-state logic state-next d clk 1 I Mealy - output logic " state:eg - Moore output logic Mealy output Moore output Figure 5.1 B l o c k diagram of a synchronous FSM. output and a Mealy output. The Moore and Mealy outputs are similar but not identical. Understanding their subtle differences is the key for controller design. The example in Section 5.3.1 illustrates the behaviors and constructions of the two types of outputs. 5.1.2 FSM representation An FSM is usually specified by an abstract state diagram or ASMchart (algorithmic state machine chart), both capturing the FSM's input, output, states, and transitions in a graphical representation. The two representations provide the same information. The FSM representation is more compact and better for simple applications. The ASM chart representation is somewhat like a flowchart and is more descriptive for applications with complex transition conditions and actions. State diagram A state diagram is composed of nodes, which represent states and are drawn as circles, and annotated transitional arcs. A single node and its transition arcs are shown in Figure 5.2(a). A logic expression expressed in terms of input signals is associated with each transition arc and represents a specific condition. The arc is taken when the corresponding expression is evaluated true. The Moore output values are placed inside the circle since they depend only on the current state. The Mealy output values are associated with the conditions of transition arcs since they depend on the current state and external input. To reduce clutter in the diagram, only asserted output values are listed. The output signal takes the default (i.e., unasserted) value otherwise. A representative state diagram is shown in Figure 5.3(a). The FSM has three states, two external input signals (i.e., a and b), one Moore output signal (i.e., yl), and one Mealy output signal (i.e., yo). The y l signal is asserted when the FSM is in the SO or s l state. The yo signal is asserted when the FSM is in the SO state and the a and b signals are "1 1". ASM chart An ASM chart is composed of a network of ASM blocks. An ASM block consists of one state box and an optional network of decision boxes and conditional output boxes. A representative ASM block is shown in Figure 5.2(b). A state box represents a state in an FSM, and the asserted Moore output values are listed inside the box. Note that it has only one exit path. A decision box tests the input condition and determines which exit path to take. It has two exit paths, labeled T and F, which correspond to the true and false values of the condition. A conditional output box lists asserted Mealy output values and is usually placed after a decision box. It indicates that the listed output signal can be activated only when the corresponding condition in the decision box is met. INTRODUCTION 121 mo: Moore output me: Mealy output logic expression I me = value mo: Moore output me: Mealy output to other state to other state (a) Node state mo = value conditional output box ,....... 1exit to other ASM block 1exit to other ASM block (b) ASM block Figure 5.2 Symbol of a state. 122 FSM (a) State diagram (b) ASM chart Figure 5.3 Example of an FSM. A state diagram can easily be converted to an ASM chart, and vice versa. The corresponding ASM chart of the previous FSM state diagram is shown in Figure 5.3(b). 5.2 FSM CODE DEVELOPMENT The procedure of developing code for an FSM is similar to that of a regular sequential circuit. We first separate the state register and then derive the code for the combinational next-state logic and output logic. The main difference is the next-state logic. For an FSM, the code for the next-state logic follows the flow of a state diagram or ASM chart. For clarity and flexibility, we use symbolic constants to represent the FSM's states. For examples, the three states in Figure 5.3 can be defined as localparam [1:0] SO = 2'b00, sl = 2'b01, s2 = 2'blO; During synthesis, software usually can recognize the FSM structure and may map these symbolic constants to different binary representations (e.g., one-hot codes), a process known as state assignment. The complete code of the FSM is shown in Listing 5.1. It consists of segments for the state register, next-state logic, Moore output logic, and Mealy output logic. Listing 5.1 FSM example module f sm-eg-mult-seg ( input wire clk, reset, input wire a , b, 5 output wire yo, yl 1; // symbolic s t a t e declaration localparam [1:01 SO = 2jb00, s1 = 2 ' b 0 1 , s2 = 2'blO; // signal declaration reg [I :01 s t a t e - r e g , s t a t e - n e x t ; 15 // state register always Q(posedge clk , posedge reset) if (reset) s t a t e - r e g <= SO; 20 else s t a t e - r e g <= s t a t e - n e x t ; // next-state logic always Q* case (state-reg) SO: i f ( a ) if (b) state-next = s2; else state-next = s l ; else s t a t e - n e x t = SO; sl: if (a) s t a t e - n e x t = SO; else state-next = s1; s 2 : s t a t e - n e x t = SO; d e f a u l t : s t a t e - n e x t = SO; endcase 40 // Moore o u t p u t l o g i c assign yl = (state-reg==sO) I I (state-reg==sl); // Mealy output l o g i c 4s a s s i g n yo = ( s t a t e - r e g = = s O ) & a & b ; endmodule The key part is the next-state logic. It uses a case statement with the s t a t e r e g signal as the selection expression. The next state (i.e., s t a t e n e x t signal) is determined by the current state (i.e., s t a t e - r e g ) and external input. The code for each state basically follows the activities inside each ASM block of Figure 5.3(b). An alternative code is to merge next-state logic and output logic into a single combinational block, as shown in Listing 5.2. Listing 5.2 FSM with merged combinational logic module f sm-eg-2-seg ( input wire c l k , r e s e t , input wire a , b , 5 output reg yo, y l ); // symbolic state declaration localparam [1:01 SO = 2 'b00, 10 sl = 2'b01, s2 = 2'blO; // signal declaration reg [I :01 s t a t e - r e g , s t a t e - n e x t ; 15 // s t a t e r e g i s t e r always Q(posedge c l k , posedge r e s e t ) if (reset) s t a t e - r e g <= SO; else s t a t e - r e g <= s t a t e - n e x t ; // next-state logic and output logic a l w a y s O* begin 5 s t a t e - n e x t = s t a t e - r e g ; // d e f a u l t next s t a t e : the same yl = llbO; // d e f a u l t o u t p u t : 0 yo = l ' b o ; // default output: 0 case (state-reg) SO : begin yl = l'bl; if (a) i f (b) begin state-next = s2; yo = l ' b l ; end else state-next = s l ; end s l : begin yl = lJbl; if (a) s t a t e - n e x t = SO; end s2: state-next = SO; d e f a u l t : s t a t e - n e x t = SO; endcase end endmodule Note that the default output values are listed at the beginning of the code. The code for the next-state logic and output logic follows the ASM chart closely. Once a detailed state diagram or ASM chart is derived, converting an FSM to HDL code is almost a mechanical procedure. Listings 5.1 and 5.2 can serve as templates for this purpose. Xilinx ISE includes a utility program called StareCAD, which allows a user to draw a Xilinx state diagram in graphical format. The program then converts the state diagram to HDL specific code. It is a good idea to try it first with a few simple examples to see whether the generated code and its style are satisfactory, particularly for the output signals. 5.3 DESIGN EXAMPLES 5.3.1 Rising-edge detector The rising-edge detector is a circuit that generates a short one-clock-cycle tick when the input signal changes from 0 to 1. It is usually used to indicate the onset of a slow timevarying input signal. We design the circuit using both Moore and Mealy machines, and compare their differences. Moore-based design The state diagram and ASM chart of a Moore machine-based edge detector are shown in Figure 5.4. The z e r o and o n e states indicate that the input signal has been 0 and 1 for a while. The rising edge occurs when the input changes to 1 in the z e r o state. The FSM moves to the e d g state and the output, t i c k , is asserted in this state. A representative timing diagram is shown at the middle of Figure 5.5. The code is shown in Listing 5.3. Listing 5.3 Moore machine-based edge detector module edge-detect-moore ( input wire clk, reset, input wire level, i output reg tick ); // symbolic state declaration l o c a l p a r a m [I: 01 10 zero = 2'b00, edg = 2'b01, one = 2'blO; // signal declaration 15 r e g [I: 01 state-reg , state-next ; // s t a l e r e g i s t e r always Q (posedge clk , posedge reset) i f (reset) s t a t e - r e g <= z e r o ; else s t a t e - r e g <= state-next ; // n e x t - s t a t e l o g i c and output l o g i c 25 always Q* (a) State diagram (b) ASM chart Figure 5.4 Edge detector based on a Moore machine. clk level state zero Moore machine tick edg one zero I state zero one zero Mealy 1 machine tick Figure 5.5 Timing diagram of two edge detectors. DESIGN EXAMPLES 127 begin state-next = s t a t e - r e g ; // default tick = I'bO; // default case (state-reg) zero : if (level) state-next = edg; edg : begin tick = l'bl; if (level) state-next = one; else state-next = zero; end one : if (-level) state-next = zero; default : state-next = zero ; 45 endcase end endmodule s t a t e : the output: 0 same Mealy-based design The state diagram and ASM chart of a Mealy machine-based edge detector are shown in Figure 5.6. The zero and one states have a similar meaning. When the FSM is in the zero state and the input changes to 1, the output is asserted immediately. The FSM moves to the one state at the rising edge of the next clock and the output is deasserted. A representative timing diagram is shown at the bottom of Figure 5.5. Note that due to the propagation delay, the output signal is still asserted at the rising edge ofthe next clock (i.e., at t l ) .The code is shown in Listing 5.4. Listing 5.4 Mealy machine-based edge detector module edge-det ect-mealy ( input wire c l k , r e s e t , input wire l e v e l , 5 output reg t i c k 1; // symbolic s t a t e declaration localparam zero = l'bO, 10 one = l ' b l ; // signal declaration reg state-reg , state-next ; 15 // s t a t e r e g i s t e r always @ (posedge clk , posedge r e s e t if (reset) s t a t e - r e g <= z e r o ; else s t a t e - r e g <= s t a t e - n e x t ; (a) State diagram (b) ASM chart Figure 5.6 Edge detector based on a Mealy machine. // next-state l o g i c and output l o g i c always Q* begin s t a t e - n e x t = s t a t e - r e g ; // default tick = l'bO; // default case (state-reg) zero : if (level) begin tick = l'bl; state-next = one; end one : if (-level) state-next = zero; default : state-next = zero; endcase end JU endmodule s t a t e : the output: 0 same tick level clk Figure 5.7 Gate-level implementation of an edge detector. Direct implementation Since the transitions of the edge detector circuit are very simple, it can be implemented without using an FSM. We include this implementation for comparison purposes. The circuit diagram is shown in Figure 5.7. It can be interpreted that the output is asserted only when the current input is 1 and the previous input, which is stored in the register, is 0. The corresponding code is shown in Listing 5.5. Listing 5.5 Gate-level implementation of an edge detector module edge-det ect -gate ( input wire clk, reset, input wire level, 5 output wire tick 1; // signal declaration reg delay-reg ; I0 // delay r e g i s t e r always Q(posedge clk, posedge reset) if (reset) delay-reg <= l'bO; else delay-reg <= l e v e l ; // decoding logic assign tick = -delay-reg & level; 20 endmodule Although the descriptions in Listings 5.4 and 5.5 appear to be very different, they describe the same circuit. The circuit diagram can be derived from the FSM if we assign 0 and 1 to the z e r o and one states. Comparison Whereas both Moore machine- and Mealy machine-based designs can generate a short tick at the rising edge of the input signal, there are several subtle differences. The Mealy machine-based design requires fewer states and responds faster, but the width of its output may vary and input glitches may be passed to the output. The choice between the two designs depends on the subsystem that uses the output signal. Most of the time the subsystem is a synchronous system that shares the same clock signal. Since the FSM's output is sampled only at the rising edge of the clock, the width and glitches do not matter as long as the output signal is stable around the edge. Note that the Mealy output signal is available for sampling at t l ,which is one clock cycle faster than or~glnal sw~tchoutput debounced output (scheme 1) bounces (last less than 20 ms) -- *--4I 20 rns bounces (last less than 20 ms) - - , Y 20 ms I - debounced output (scheme 2) 4 C 20 ms Figure 5.8 Original and debounced waveforms. the Moore output, which is available at ta. Therefore, the Mealy machine-based circuit is preferred for this type of application. 5.3.2 Debouncing circuit The slide and pushbutton switches on the prototyping board are mechanical devices. When pressed, the switch may bounce back and forth a few times before settling down. The bounces lead to glitches in the signal, as shown at the top of Figure 5.8. The bounces usually settle within 20 ms. The purpose of a debouncing circuit is to filter out the glitches associated with switch transitions. The debounced output signals from two FSM-based design schemes are shown in the two bottom parts of Figure 5.8. The first design scheme is discussed in this subsection and the second scheme is left as an exercise in Experiment 5.5.2. A better alternative FSMD-based scheme is discussed in Section 6.2.1. An FSM-based design uses a free-running 10-ms timer and an FSM. The timer generates a one-clock-cycle enable tick (the m - t i c k signal) every 10 ms and the FSM uses this information to keep track of whether the input value is stabilized. In the first design scheme, the FSM ignores the short bounces and changes the value of the debounced output only after the input is stabilized for 20 ms. The output timing diagram is shown at the middle of Figure 5.8. The state diagram ofthis FSM is shown in Figure 5.9. The zero and one states indicate that the switch input signal, s w , has been stabilized with 0 and 1 values. Assume that the FSM is initially in the zero state. It moves to the w a i t 1-1state when s w changes to 1. At the w a i t l - I state, the FSM waits for the assertion of m - t i c k . If s w becomes 0 in this state, it implies that the width of the 1 value does not last long enough and the FSM returns to the zero state. This action repeats two more times for the w a i t l - 2 and w a i t l - 3 states. The operation from the one state is similar except that the s w signal must be 0. Since the 10-ms timer is free-running and the m - t i c k tick can be asserted at any time, the FSM checks the assertion three times to ensure that the s w signal is stabilized for at least 20 ms (it is actually between 20 and 30 ms). The code is shown in Listing 5.6. It includes a 10-ms timer and the FSM. Figure 5.9 State diagram of a debouncing circuit. Listing 5.6 FSM implementation of a debouncing circuit module db-f s m ( input wire input wire 5 output reg 1; clk, sw, db reset, // symbolic state declaration l o c a l p a r a m C2:OI 10 zero = 3'b000, waitl-1 = 3'b001, waitl-2 = 3'b010, waitl-3 = 3'b011, one = 3'b100, 15 waito-1 = 3'b101, wait0-2 = 3'b110, wait0-3 = 3 ' b l l l ; // number of c o u n t e r b i t s ( 2 " N * 2Ons = lOms t i c k ) 20 l o c a l p a r a m N = 1 9 ; // signal declaration r e g [N-1:Ol q - r e g ; w i r e [N-1 :01 q - n e x t ; 25 wire m-tick; reg [2:0] state-reg , state-next ; // body , ............................................... / / c o u n t e r t o g e n e r a t e 10 ms t i c k ............................................... always B(posedge clk) q - r e g <= q - n e x t ; 35 / / n e x t - s t a t e l o g i c assign q-next = q-reg + 1; // ozrtput t i c k assign m-tick = (q-reg==O) ? l J b l : lJbO; ............................................... // d e b o u n c i n g FSM ............................................... // state r e g i s t e r always 0 (posedge clk , posedge r e s e t ) if (reset) s t a t e - r e g <= z e r o ; else s t a t e - r e g <= s t a t e - n e x t ; so // n e x t - s t a t e l o g i c and o u t p u t l o g i c always B* begin state-next = s t a t e - r e g ; // default s t a t e : the same db = l J b O ; // default output: 0 case (state-reg) zero : if (SW) s t a t e - n e x t = w a i t 1-1 ; waitl-1 : if (-SW) state-next = zero; else if (m-tick) state-next = waitl-2 ; waitl-2 : if (-SW) state-next = zero; else if (m-tick) state-next = waitl-3; wait 1-3 : if (-SW) state-next = zero; else if (m-tick) state-next = one; one : begin db = l ' b l ; if (-SW) state-next = wait0-1; end wait0-1 : begin db = l ' b l ; if (SW) state-next = one; else if (m-tick) state-next = wait0-2; end begin db = l ' b l ; if (sw) state-next = one; else if (m-tick) state-next = wait0-3; end wait0-3 : begin db = l ' b l ; if (SW) state-next = one; else if (m-tick) state-next = zero; end 110 default : state-next = zero; endcase end endmodule DESIGN EXAMPLES 133 5.3.3 Testing circuit We use a bounce counting circuit to verify operation of the rising-edge detector and the debouncing circuit. The block diagram is shown in Figure 5.10. The input ofthe verification circuit is from a pushbutton switch. In the lower part, the signal is first fed to the debouncing circuit and then to the rising-edge detector. Therefore, a one-clock-cycle tick is generated each time the button is pressed and released. The tick in turn controls the enable input of an 8-bit counter, whose content is passed to the LED time-multiplexing circuit and shown on the left two digits of the prototyping board's seven-segment LED display. In the upper - btn[l] - level tick en q - > edge detector counter > (--hheexx01 sseg an- sseg an hex2 hex3 sw - db level tick -en q disp-rnux-hex > clk - debouncing > edge detector counter > reset Figure 5.10 Debouncing testing circuit. part, the input signal is fed directly to the edge detector without the debouncing circuit, and the number is shown on the right two digits of the prototyping board's seven-segment LED display. The bottom counter thus counts one desired 0-to-1 transition as well as the bounces. The code is shown in Listing 5.7. It basically uses component instantiation to realize the block diagram. Listing 5.7 Verification circuit for a debouncing circuit and rising-edge detector module debounce-test ( input wire clk, r e s e t , input wire [1:0] btn, output wire [3:01 an, output wire [7:01 sseg 1; // signal declaration 10 reg [7:01 b-reg, d-reg; w i r e 17: 01 b - n e x t , d - n e x t ; reg btn-reg , db-reg; wire db-level , db-tick , btn-tick , c l r ; 15 / / i n s t a n t i a t e 7-seg LED d i s p l a y t i m e - m u l t i p l e x i n g m o d u l e disp-hex-mux disp-unit (. clk(c1k) , .reset (reset), . h e x 3 ( b - r e g C7: 41 ) , .h e x 2 ( b - r e g [ 3 : 01 ) , .hexl (d-reg [7:41) , .hexO(d-reg [3:01) , LO .dp_in(4'blOll), .an(an), .sseg(sseg)); // instantiate debouncing circuit db-f sm d b - u n i t ( . c l k ( c l k ) , . r e s e t ( r e s e t ) , .sw(btn [ I ] ) , .db(db-level)) ; 25 // edge detection c i r c u i t s always @(posedge clk) begin b t n - r e g <= b t n El] ; d b - r e g <= d b - l e v e l ; BIBLIOGRAPHIC NOTES 135 end assign btn-tick = -btn-reg & btn [I] ; assign db-tick = "db-reg & db-level; 35 // two counters a s s i g n c l r = b t n [O] ; always @(posedge clk) begin b-reg <= b - n e x t ; 40 d-reg <= d-next; end assign b-next = (clr) ? 8'bO : (btn-tick) ? b-reg + 1 : b-reg; assign d-next = (clr) 7 8'bO : JS (db-tick) ? d-reg + 1 : d-reg; endmodule The seven-segment display shows the accumulated numbers of 0-to-1 edges of bounced and debounced switch input. After pressing and releasing the pushbutton switch several times, we can determine the average number of bounces for each transition. 5.4 BIBLIOGRAPHIC NOTES The article "Coding and Scripting Techniques for FSM Designs with Synthesis-Optimized, Glitch-Free Outputs" by C. E. Cummings provides a detailed discussion on various coding styles of FSM. 5.5 SUGGESTED EXPERIMENTS 5.5.1 Dual-edge detector A dual-edge detector is similar to a rising-edge detector except that the output is asserted for one clock cycle when the input changes from 0 to 1 (i.e., rising edge) and 1 to 0 (i.e., falling edge). 1. Design a circuit based on the Moore machine and draw the state diagram and ASM chart. 2. Derive the HDL code based on the state diagram of the ASM chart. 3. Derive a testbench and use simulation to verify operation of the code. 4. Replace the rising detectors in Section 5.3.3 with dual-edge detectors and verify their operations. 5. Repeat steps 1 to 4 for a Mealy machine-based design. 5.5.2 Alternative debouncing circuit One problem with the debouncing design in Section 5.3.2 is the delayed response of the onset of a switch transition. An alternative is to react to the first edge in the transition and then wait for a small amount of time (at least 20 ms) to have the input signal settled. The output timing diagram is shown at the bottom of Figure 5.8. When the input changes from .). entering lot Figure 5.11 Conceptual diagram of gate sensors. 0 to 1, the FSM responds immediately. The FSM then ignores the input for about 20 ms to avoid glitches. After this amount of time, the FSM starts to check the input for the falling edge. Follow the design procedure in Section 5.3.2 to design the alternative circuit. 1. Derive the state diagram and ASM chart for the circuit. 2. Derive the HDL code. 3. Derive the HDL code based on the state diagram and ASM chart. 4. Derive a testbench and use simulation to verify operation of the code. 5. Replace the debouncing circuit in Section 5.3.3 with the alternative design and verify its operation. 5.5.3 Parking lot occupancy counter Consider a parking lot with a single entry and exit gate. Two pairs of photo sensors are used to monitor the activity of cars, as shown in Figure 5.1 1. When an object is between the photo transmitter and the photo receiver, the light is blocked and the corresponding output is asserted to 1. By monitoring the events of two sensors, we can determine whether a car is entering or exiting or a pedestrian is passing through. For example, the following sequence indicates that a car enters the lot: Initially, both sensors are unblocked (i.e., the a and b signals are "00"). Sensor a is blocked (i.e., the a and b signals are " 10"). Both sensors are blocked (i.e., the a and b signals are "1 1"). Sensor a is unblocked (i.e., the a and b signals are "01"). Both sensors becomes unblocked (i.e., the a and b signals are "00"). Design a parking lot occupancy counter as follows: 1. Design an FSM with two input signals, a and b, and two output signals, e n t e r and e x i t . The e n t e r and e x i t signals assert one clock cycle when a car enters and one clock cycle when a car exits the lot, respectively. 2. Derive the HDL code for the FSM. 3. Design a counter with two control signals, i n c and dec, which increment and decrement the counter when asserted. Derive the HDL code. 4. Combine the counter and the FSM and LED multiplexing circuit. Use two debounced pushbuttons to mimic operation of the two sensor outputs. Verify operation of the occupancy counter. This Page Intentionally Left Blank CHAPTER 6 FSMD 6.1 INTRODUCTION An FSMD (finite state machine with data path) combines an FSM and regular sequential circuits. The FSM, which is sometimes known as a control path, examines the external commands and status and generates control signals to specify operation of the regular sequential circuits, which are known collectively as a data path. The FSMD is used to implement systemsdescribedby RT(register transfer)methodology,in which the operations are specified as data manipulation and transfer among a collection of registers. 6.1.1 Single RT operation An RT operation specifies data manipulation and transfer for a single destination register. It is represented by the notation where rdest is the destination register, rsrcl,rsrc2,and rSrcnare the source registers, and f (.) specifiesthe operation to be performed. The notation indicatesthat the contentsofthe source registers are fed to the f (.) hnction, which is realized by a combinational circuit, and the result is passed to the input of the destination register and stored in the destination register at the next rising edge of the clock. Following are several representative RT operations: rl + 0. A constant 0 is stored in the r1 register. rl t rl. The content of the rl register is written back to itself FPGA Protoyping by VerilogExamples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. a-next clk (a) Block diagram clk A1- r L a-reg 9X 7 15 (b) Timing diagram Figure 6.1 Block and timing diagrams of an RT operation. r2 + r2 >> 3. The r2 register is shifted right three positions and then written back to itself. r2 + rl. The content of the rl register is transferred to the r2 register. i + i + 1. The content of the i register is incremented by 1 and the result is written back to itself. d +- sl + s2 + s3. The summation of the sl,s2,and s3 registers is written to the d register. y + a*a. The a squared is written to the y register. A single RT operation can be implemented by constructing a combinational circuit for the f (.) function and connecting the input and output ofthe registers. For example, consider the a + a-b+l operation. The f (.) function involves a subtractor and an incrementor. The block diagram is shown in Figure 6.l(a). For clarity, we use the r e g and n e x t suffixes to represent the input and output of a register. Note that an RT operation is synchronized by an embedded clock. The result from the f (.) function is not stored to the destination register until the next rising edge of the clock. The timing diagram of the previous RT operation is shown in Figure 6.l(b). 6.1.2 ASMD chart A circuit based on the RT methodology specifies which RT operations should be executed in each step. Since an RT operation is done on a clock-by-clock basis, its timing is similar to a state transition of an FSM. Thus, an FSM is a natural choice to specify the sequencing rl trl state-reg (a) ASMD segment (b) Block diagram Figure 6.2 Realization of an ASMD segment. of an RT algorithm. We extend the ASM chart to incorporate RT operations and call it an ASMD (ASM with data path) chart. The RT operations are treated as another type of activity and can be placed where the output signals are used. A segment of an ASMD chart is shown in Figure 6.2(a). It contains one destination register, r l , which is initialized with 8, added with content of the 1-2 register, and then shifted left two positions. Note that the rl register must be specified in each state. When r l is not changed, the r l t rl operation should be used to maintain its current content, as in the s3 state. In hture discussion, we assume that r t r is the default RT operation for the r register and do not include it in the ASMD chart. Implementing the RT operations of an ASMD chart involves a multiplexing circuit to route the desired next value to the destination register. For example, the previous segment can be implemented by a 4-to- 1 multiplexer, as shown in Figure 6.2(b). The current state (i.e., the output of the state register) of the FSM controls the selection signal of the multiplexer and thus chooses the result of the desired RT operation. An RT operation can also be specified in a conditional output box, as the r 2 register shown in Figure 6.3(a). Depending on the a>bcondition, the FSMD performs either r 2 +r2+aor r 2 + r2+b. Note that all operations are done in parallel inside an ASMD block. We need to realize the a>b, r2+a, and r2+b operations and use a multiplexer to route the desired value to r2. The block diagram is shown in Figure 6.3(b). 6.1.3 Decision box with a register The appearance of an ASMD chart is similar to that of a normal flowchart. The main difference is that the RT operation in an ASMD chart is controlled by an embedded clock signal and the destination register is updated when the FSMD exits the current ASMD block, but not within the block. The r + r-1 operation actually means that: r n e x t = r-reg - 1; r-reg <= r n e x t at the rising edge of the clock (i.e., when the FSMD exits the current block). 4 (a) ASM block state-reg (b) Block diagram Figure 6.3 Realization of an RT operation in a conditional output box (a) Use old value o f r (b) Use new value of r Figure 6.4 ASM block affected by a delayed store. This "delayed store" may introduce subtle errors when a register is used in a decision box. Consider the FSMD segment in Figure 6.4(a). The r register is decremented in the state box and used in the decision box. Since the r register is not updated until the FSMD exits the block, the old content of r is used for comparison in the decision box. If the new value of r is desired, we should use the output of the combinational logic (i.e., r n e x t ) in the decision box (i.e., replace the r = = O expression with rnext==O), as shown in Figure 6.4(b). Block diagram of an FSMD The conceptual block diagram of an FSMD is divided into a data path and a control path, as shown in Figure 6.5. The data path performs the required RT operations. It consists oE Data registers: store the intermediate computation results Functional units: perform the functions specified by the RT operations Routing network: routes data between the storage registers and the functional units The data path follows the c o n t r o l signal to perform the desired RT operations and generates the i n t e r n a l s t a t u s signal. The control path is an FSM. As a regular FSM, it contains a state register, next-state logic, and output logic. It uses the external command signal and the data path's s t a t u s signal as the input and generates the c o n t r o l signal to control the data path operation. The FSM also generates the e x t e r n a l s t a t u s signal to indicate the status of the FSMD operation. Note that although an FSMD consists of two types of sequential circuits, both circuits are controlled by the same clock, and thus the FSMD is still a synchronous system. 6.2 CODE DEVELOPMENT OF AN FSMD We use an improved debouncing circuit to demonstrate derivation of the FSMD code. Although the debouncing circuit in Section 5.3.2 uses an FSM and a timer (which is a regular sequential circuit), it is not based on the RT methodology because the two units are running independently and the FSM has no control over the timer. Since the 10-ms enable tick can be asserted at any time, the FSM does not know how much time has elapsed when the first tick is detected in the w a i t l - l or wait0-l state. Thus, the waiting period in this data output data input ....................................... ............................... internal status control signal ............................................................. command - next-state Jd logic > state-q.register output ' logic external status ................................ control path Figure 6.5 Block diagram of an FSMD. design is between 20 and 30 ms but is not an exact interval. This deficiency can be overcome by applying the RT methodology. In this section, we use this improved debouncing circuit to illustrate FSMD code development. 6.2.1 Debouncing circuit based on RT methodology With the RT methodology, we can use an FSM to control the initiation of the timer to obtain the exact interval. The ASMD chart is shown in Figure 6.6. The circuit is expanded to include two output signals: db-level, which is the debounced output, and db-t ick, which is a one-clock-cycle enable pulse asserted at the zero-to-one transition. The z e r o and one states mean that the s w input has been stabilized for 0 and 1, respectively. The wait 1and wait0 states are used to filter out short glitches. The s w signal must be stable for a certain amount of time or the transition will be treated as a glitch. The data path contains one register, q, which is 21 bits wide. Assume that the FSMD is originally in the z e r o state. When the s w input signal becomes 1, the FSMD moves to the wait 1state and initializes q to "1. . . 1". In the wait1 state, the q decrements in each clock cycle. If s w remains as 1, the FSMD returns to this state repeatedly until q reaches "0. . . O w and then moves to the one state. Recall that the 50-MHz (i.e., 20-ns period) system clock is used on the prototyping board. Since the FSMD stays in the w a i t l state for 2'l clock cycles, it is about 40 ms Figure 6.6 ASMD chart of a debouncing circuit. (i.e., 221*20ns). We can modify the initial value of the q register to obtain the desired wait interval. There are two ways to derive the HDL code: one with explicit description of the data path components and the other with implicit description of the data path components. 6.2.2 Code with explicit data path components The first approach to FSMD code development is to separate the control FSM and the key data path components. From an ASMD chart, we first identify the key components in the data path and the associated control signals and then describe these components in individual code segments. The key data path component of the debouncing circuit ASMD chart is a custom 21-bit decrement counter that can: Be initialized with a specific value Count downward or pause Assert a status signal when the counter reaches 0 We can create a binary counter with a q-load signal to load the initial value and a q-dec signal to enable the counting. The counter also generates a q-zero status signal, which is asserted when the counter reaches zero. The complete data path is composed of the q register and the next-state logic of the custom decrement counter. A comparison circuit is included to generate the q-zero status signal. The control path consists of an FSM, which takes the s w input and the q-zero status and asserts the control signals, q-load and q-dec, according to the desired action in the ASMD chart. The HDL code follows the data path specification and the ASMD chart, and is shown in Listing 6.1. Listing 6.1 Debouncing circuit with an explicit data path component module debounce-explicit ( input wire clk, reset, input wire sw, output reg db-level , db-tick 1; // symbolic s t a t e declaration l o c a l p a r a m [I :01 IO zero = 2'b00, wait0 = 2'b01, one = 2'b10, wait1 = 2'bll; I5 // number of counter b i t s ( 2 - N * 20ns = 40ms) localparam N=21; // signal declaration r e g [I:01 s t a t e - r e g , s t a t e - n e x t ; 20 r e g CN-1:Ol q-reg; w i r e [N-1: 01 q-next ; wire q-zero; reg q-load, q-dec; // fsmd s t a t e & data r e g i s t e r s always Q (posedge clk , posedge reset) if (reset) begin s t a t e - r e g <= z e r o ; q - r e g <= 0 ; end e 1se begin s t a t e - r e g <= s t a t e - n e x t ; q - r e g <= q - n e x t ; end // FSMD d a t a p a t h ( c o u n t e r ) n e x t - s t a t e l o g i c 40 a s s i g n q - n e x t = ( q - l o a d ) ? ( N ( l ' b 1 ) ) : / / l o a d 1 . . 1 (q-dec) ? q-reg - 1 : // decrement q-reg; // status signal a s s i g n q-zero = (q-next ==O); 45 // FSMD c o n t r o l p a t h n e x t - s t a t e l o g i c a l w a y s Q* begin s t a t e - n e x t = s t a t e - r e g ; // default s t a t e : the same q-load = l'bO; // default output: 0 q-dec = 1 'bO; // default output: 0 db-tick = l'bO; // default output: 0 case (state-reg) zero : begin db-level = l'bO; if (SW) begin state-next = waitl; q-load = l ' b l ; end end waitl : begin db-level = l'bO; i f (sw) begin q-dec = l ' b l ; if (q-zero) begin state-next = one; db-tick = l ' b l ; end end e l s e // sw==O state-next = zero; end one : begin db-level = l ' b l ; if (-sw) begin state-next = wait0; q-load = l ' b l ; end end wait0 : begin d b - l e v e l = 1' b l ; if (-sw) begin q-dec = 1' b l ; if (q-zero) state-next = zero; end else // sw==I state-next = one; end default : state-next = zero; endcase end endmodule 6.2.3 Code with implicit data path components An alternative coding style is to embed the RT operations within the FSM control path. Instead of explicitly defining the data path components,we just list RT operationswith the corresponding FSM state. The code of the debouncing circuit is shown in Listing 6.2. Listing 6.2 Debouncing circuit with an implicit data path component module debounce ( input wire c l k , r e s e t , input wire sw, s output reg db-level , db-tick 1; // symbolic s t a t e declaration l o c a l p a r a m [ I :01 10 zero = 2'b00, wait0 = 2'b01, one = 2'b10, wait1 = 2'bll; 15 // number o f c o u n t e r b i t s ( 2 - N * 2Ons = 40ms) localparam N=21; // signal declaration reg [N-1:0] q-reg, q-next; lo r e g [ I :01 s t a t e - r e g , s t a t e - n e x t ; // body // fsmd s t a t e & data r e g i s t e r s always @(posedge clk, posedge reset) 5 if (reset) begin s t a t e - r e g <= z e r o ; q - r e g <= 0 ; end else begin s t a t e - r e g <= s t a t e - n e x t ; q - r e g <= q - n e x t ; end 35 // next-state logic & data path functional units /routing always @* begin state-next = s t a t e - r e g ; // default s t a t e : the same q-next = q-reg; // default q: unchnaged db-tick = l'bO; // default output: 0 case (state-reg) zero : begin db-level = l'bO; if (SW) begin state-next = waitl; q-next = CN.El'bl}); // load I . . ] end end wait 1: begin db-level = l'bO; if (SW) begin q-next = q-reg - 1; i f (q-next==O) begin state-next = one; db-tick = l ' b l ; end end e l s e // sw==O state-next = zero; end one : begin db-level = l ' b l ; if (-SW) begin state-next = wait0; q-next = {N{l'bl)); // end end wait0 : begin db-level = l ' b l ; i f ("sw) begin q-next = q-reg i f (q-next ==O) state-next = zero; end e l s e // sw==l state-next = one; load I.. I end default : state-next = zero; 90 endcase end endmodule The code consists of a memory segment and a combinational logic segment. The former contains the state register of the FSM and the data register of the data path. The latter basically specifies the next-state logic of the control path FSM. Instead of generating control signals, the next data register values are specified in individual states. The next-state logic of the data path, which consists of functional units and a routing network, is created accordingly. 6.2.4 Comparison Code with implicit data path components essentially follows the ASMD chart. We just convert the chart to an HDL description. Although this approach is simpler and more descriptive, we rely on synthesis software for data path construction and have less control. This can best be explained by an example. Consider the ASMD segment in Figure 6.7. The implicit description becomes case (state-reg) sl: begin dl-next = a * b; ... end s2 : begin * d 2 - n e x t = b c ; end s3 : begin d3-next ... end = a * c; Figure 6.7 ASMD segment with sharing opportunity. ... endcase The synthesis software may infer three multipliers. Since a combinational multiplier is a complex circuit, it is more efficient to share the circuit. We can use explicit description to isolate the multiplier: case (state-reg) sl: begin in1 = a; in2 = b; dl-next = m-out; ... end s2 : begin in1 = b; in2 = c; d2-next = m-out; ... end s3 : begin in1 = a; in2 = c; d3-next = m-out; - btn[l] > - .level tick -en q - edge detector >Counter -hheexx10 sseg an- sseg an hex2 hex3 sw dbtick -en q disp-mux-hex > clk - debouncing > counter reset Figure 6.8 Debouncing testing circuit. end endcase // e x p l i c i t d e s c r i p t i o n of a s i n g l e m u l t i p l i e r // outside the always block a s s i g n m-out = i n 1 * i n 2 ; The code ensures that only one multiplier is inferred during synthesis. The implicit and explicit descriptions can be mixed for a complex FSMD design. We frequently isolate and extract complex data path components for code clarity and efficiency. 6.2.5 Testing circuit The debouncing testing circuit discussed in Section 5.3.3 can be used to verify operation of the new design. Since the revised debouncing circuit's outputs include a one-clock-cycle tick signal, no edge detector is needed after the debouncing circuit. The revised block diagram is shown in Figure 6.8, and the corresponding code is shown in Listing 6.3. Listing 6.3 Verification circuit for a debouncing circuit module debounce-f smd-test ( input wire c l k , r e s e t , input wire [1:0] btn, output wire [3:01 an, output wire [7:01 sseg 1; // signal d e c l a r a t i o n lo reg [7:0] b-reg , d-reg; wire [7:01 b-next , d-next; reg btn-reg; wire db-tick , btn-tick , c l r ; 15 / / i n s t a n t i a t e 7 - s e g LED d i s p l a y t i m e - m u l t i p l e x i n g m o d u l e disp-hex-mux disp-unit (. clk(clk), .reset (reset), // i n s t a n t i a t e debouncing c i r c u i t debounce db-unit (.clk(clk1, .reset ( r e s e t ) , .sw(btn [I]) , zs .db-level0 , .db-tick(db-tick)) ; // edge detection c i r c u i t for un-debounced input always @(posedge clk) b t n - r e g <= btn [ l ] ; 30 a s s i g n b t n - t i c k = " b t n - r e g & b t n [ l l ; // two counters a s s i g n c l r = b t n [O] ; always @(posedge clk) 35 begin d - r e g <= d - n e x t ; b-reg <= b - n e x t ; end //next-state logic for the counter 40 assign b-next = ( c l r ) ?O: (btn-tick) ? b-reg + 1 : assign d-next = ( c l r ) (db-tick) b-reg ; ?O: ? d-reg + 1 : 45 d-reg ; endmodule 6.3 DESIGN EXAMPLES 6.3.1 Fibonacci number circuit The Fibonacci numbers constitute a sequence defined as ifi = O ifi = 1 + f ib(i - 1) fib(i - 2) if i > 1 One way to calculate f ib(i) is to construct the function iteratively, from 0 to the desired i. This approach requires two temporary registers to store the two most recently calculated values [i.e., f ib(i - 1) and f ib(i - 2)] and one index register to keep track of the number of iterations. The ASMD chart is shown in Figure 6.9, in which t 1 and to are temporary storage registers and n is the index register. In addition to the regular data input and output signals, i and f , we include a command signal, s t a r t , which signals the beginning of operation, and two status signals: ready, which indicates that the circuit is idle and ready to take new input, and done-tick, which is asserted for one clock cycle when the operation is completed. Since this circuit, like many other FSMD designs, is probably a part of a larger system, these signals are needed to interface with other subsystems. Figure 6.9 ASMD chart of a Fibonacci circuit. The ASMD chart has three states. The i d l e state indicates that the circuit is currently idle. When s t a r t is asserted, the FSMD moves to the op state and loads initial values to three registers. The t o and t I registers are loaded with 0 and 1, which represent f i b ( 0 ) ..and f i b ( l ) ,respectively. The n register is loaded with i,the desired number of iterations. The main computation is iterated through the op state by three RT operations: tl + tl + t o t o t tl n+n - I The first two RT operations obtain a new value and store the two most recently calculated values in t 1and t o . The third RT operation decrements the iteration index. The iteration ended when n reaches 1 or its initial value is 0 [i.e., f i b ( 0 ) l . Unlike a regular flowchart, the operations in an ASMD block can be performed concurrently in the same clock cycle. We put all comparison and RT operations in the op state to reduce the computation time. Note that the new values of the t I and t o registers are loaded at the same time when the FSMD exits the op state (i.e., at the next rising edge of the clock). Thus, the original value o f t I, not t l + t O , is stored to t o . The purpose of the done state is to generate the one-clock-cycle done-tick signal to indicate completion of the computation. This state can be omitted if this status signal is not needed. The code follows the ASMD chart and is shown in Listing 6.4. Note that the Fibonacci function grows rapidly and the output signal should be wide enough to accommodate the desired result. Listing 6.4 Fibonacci number circuit module f i b ( input wire clk, r e s e t , input wire s t a r t , c input wire [4:01 i , output reg ready, done-tick, output wire [19:01 f 1; 10 // s y m b o l i c s t a t e d e c l a r a t i o n l o c a l p a r a m [ I : 01 idle = 2 'b00, op = 2 ' b 0 1 , done = 2'blO; Ic // signal declaration r e g [ I : 01 s t a t e - r e g , s t a t e - n e x t ; reg [19:01 to-reg, to-next, t l - r e g , t l - n e x t ; reg [4:01 n-reg , n-next ; 20 // bod,v / / FSMD s t a t e & d a t a r e g i s t e r s always @ (posedge clk , posedge reset ) if (reset) 21 begin s t a t e - r e g <= i d l e ; t o - r e g <= 0 ; t l - r e g <= 0 ; n - r e g <= 0 ; 30 end else begin s t a t e - r e g <= s t a t e - n e x t ; t o - r e g <= t o - n e x t ; t l - r e g <= t l - n e x t ; n - r e g <= n - n e x t ; end / / FSMD n e x t - s t a t e l o g i c always Q* 40 begin state-next = state-reg; ready = l'bO; done-tick = lJbO; to-next = to-reg; tl-next = tl-reg; n-next = n-reg; case (state-reg) idle : begin ready = l ' b l ; if (start) begin to-next = 0; tl-next = 20Jdl; n-next = i ; state-next = op; end end op : if (n-reg==O) begin tl-next = 0; state-next = done; end else if (n-reg==l) state-next = done; else begin tl-next = tl-reg + to-reg; to-next = tl-reg; n-next = n-reg - 1; end done : begin done-tick = l J b l ; state-next = idle; end default : state-next = idle ; endcase 80 end // output --divisor / 00110 - quotient 0010/00001101- dividend 0010 0001 - remainder Figure 6.10 Long division of two 4-bit unsigned integers. assign f = tl-reg; endmodule 6.3.2 Division circuit Because of complexity, the division operator cannot be synthesized automatically. We use an FSMD to implement the long-division algorithm in this subsection. The algorithm is illustrated by the division of two Cbit unsigned integers in Figure 6.10. The algorithm can be summarized as follows: 1. Double the dividend width by appending 0's in front and align the divisor to the leftmost bit of the extended dividend. 2. If the corresponding dividend bits are greater than or equal to the divisor, subtract the divisor from the dividend bits and make the corresponding quotient bit 1. Otherwise, keep the original dividend bits and make the quotient bit 0. 3. Append one additional dividend bit to the previous result and shift the divisor to the right one position. 4. Repeat steps 2 and 3 until all dividend bits are used. The sketch of the data path is shown in Figure 6.1 1. Initially, the divisor is stored in the d register and the extended dividend is stored in the r h and r l registers. In each iteration, the r h and r l registers are shifted to the left one position. This corresponds to shifting the divisor to the right of the preceding algorithm. We can then compare r h and d and perform subtraction if r h is greater than or equal to d. When r h and r l are shifted to the left, the rightmost bit of r l becomes available. It can be used to store the current quotient bit. After we iterate through all dividend bits, the result of the last subtraction is stored in r h and becomes the remainder of the division, and all quotients are shifted into r l . The ASMD chart of the division circuit is somewhat similar to that of the previous Fibonacci circuit. The FSMD consists of four states: i d l e , op, l a s t , and done. To make the code clear, we extract the compare and subtract circuit to separate code segments. The main computation is performed in the op state, in which the dividend bits and divisor are compared and subtracted and then shifted left 1 bit. Note that the remainder should not be shifted in the last iteration. We create a separate state, l a s t , to accommodate this special requirement. As in the preceding example, the purpose of the done state is to generate a one-clock-cycle done-tick signal to indicate completion of the computation. The code is shown in Listing 6.5. I I I compare and subtract Figure 6.1 1 Sketch of division circuit's data path. Listing 6.5 Division circuit module div #( parameter W = 8 , CBIT = 4 // CBIT=log2 (W)+I 5 1 ( input wire c l k , r e s e t , input wire s t a r t , input wire [W-1:0] d v s r , dvnd, 10 output reg ready, done-tick , o u t p u t w i r e [W-1:Ol q u o , rmd 1; // symbolic state declaration 15 localparam [1:01 idle = 2 'b00, op = Z'b01, l a s t = 2'b10, done = 2 ' b l l ; // signal declaration r e g [ I :01 s t a t e - r e g , s t a t e - n e x t ; r e g [W-1:0] r h - r e g , r h - n e x t , r l - r e g , r l - n e x t , r h - t m p ; r e g [W-1:Ol d - r e g , d - n e x t ; zr r e g [CBIT -1 :01 n - r e g , n - n e x t ; reg q-bit; // body // FSMD s t a t e & d a t a r e g i s t e r s 30 a l w a y s @ ( p o s e d g e c l k , p o s e d g e r e s e t ) if (reset) begin s t a t e - r e g <= i d l e ; r h - r e g <= 0 ; r l - r e g <= 0 ; d - r e g <= 0 ; n - r e g <= 0 ; end else begin s t a t e - r e g <= s t a t e - n e x t ; r h - r e g <= r h - n e x t ; r l - r e g <= r l - n e x t ; d - r e g <= d - n e x t ; n-reg <= n - n e x t ; end / / FSMD n e x t - s t a t e l o g i c always O* ro b e g i n state-next = state-reg; ready = l'bO; done-tick = l'bO; rh-next = rh-reg; rl-next = rl-reg; d-next = d-reg; n-next = n-reg; case (state-reg) idle : begin ready = l ' b l ; if (start) begin rh-next = 0; rl-next = dvnd; // dividend d-next = dvsr; // d i v i s o r n-next = C B I T ; // index state-next = op; end end op : begin // s h i f t rh and rl l e f t r l - n e x t = { r l - r e g [W-2:01 , q - b i t ) ; r h - n e x t = { r h - t m p [W-2: 01 , r l - r e g [ W - l l ) ; // decrease index n-next = n-reg - 1 ; if (n-next ==l) state-next = l a s t ; end l a s t : // last i t e r a t i o n begin r l - n e x t = Crl-reg [W-2:Ol , q - b i t ) ; rh-next = rh-tmp; state-next = done; end done : begin done-tick = l J b l ; state-next = idle; end default : state-next = idle; endcase end 95 // compare and s u b t r a c t c i r c u i t always O* i f ( r h - r e g >= d - r e g ) begin rh-tmp = rh-reg - d-reg; q - b i t = 1' b l ; end else begin 10s rh-tmp = rh-reg; q-bit = llbO; end //output IIO a s s i g n quo = r l - r e g ; a s s i g n rmd = r h - r e g ; endmodule 6.3.3 Binary-to-BCD conversion circuit We discussed the BCD format in Section 4.5.2. In this format, a decimal number is represented as a sequence of 4-bit BCD digits. A binary-to-BCD conversion circuit converts a binary number to the BCD format. For example, the binary number "0010 0000 0000" becomes "0101 0001 0010" (i.e., 51210)after conversion. The binary-to-BCD conversion can be processed by a special BCD shift register, which is divided into 4-bit groups internally, each representing a BCD digit. Shifting a BCD sequence to the left requires adjustment if a BCD digit is greater than after shifting. For example, if a BCD sequence is "0001 0111" (i.e., 1710),it should become "0011 0100" (i.e., 3410)ratherthan "0010 1110". The adjustmentrequires subtracting lolo (i.e., "1010") from the right BCD digit and adding 1 (which can be considered as a carry-out) to the next BCD digit. Note that subtracting lolo is equivalentto adding for a 4-bit binary number. Thus, the foregoing adjustment can also be achieved by adding 610 to the right BCD digit. The carry-out bit is generated automatically in this process. In the actual implementation, it is more efficient to first perform the necessary adjustment on a BCD digit and then shift. We can check whether a BCD digit is greater than and, if this is the case, add to the digit. After all the BCD digits are corrected, we can then shift the entire register to the left one position. A binary-to-BCD conversion circuit can DESIGN EXAMPLES 161 Table 6.1 Binary-to-BCD conversion example shift left 1 bit Bit 3 BCD digit 0 adjustment shift left 1 bit Bit 2 BCD digit 0 adjustment shift left 1 bit Bit 1 no adjustment shift left 1 bit Bit 0 BCD digit 1 adjustment shift left 1 bit 1 (110) 1 (1 10) 1 11 (310) 110 (610) 1001 0010 (2I 0) 111 (7I 0) 1010 0101 (510) 1000 0001 (1 10) 1111 111 11 0011 1 (310) 0011 0111 (710) be constructed by shifting the binary input to a BCD shift register bit by bit, from MSB to LSB. Its operation can be summarized as follows: 1 . For each Cbit BCD digit in a BCD shift register, check whether the digit is greater than 4. If this is the case, add 310 to the digit. 2. Shift the entire BCD register left one position and shift in the MSB of the input binary sequence to the LSB of the BCD register. 3. Repeat steps 1 and 2 until all input bits are used. The conversion process of a 7-bit binary input, "111 1111" (i.e., 12710),is demonstrated in Table 6.1. The code of a 13-bit conversion circuit is shown in Listing 6.6. It uses a simple FSMD to control the overall operation. When the s t a r t signal is asserted, the binary input is stored to the p2s register. The FSM then iterates through the 13 bits, similar to the process described in previous examples. Four adjustment circuits are used to correct the four BCD digits. For clarity, they are isolated from the next-state logic and described in a separate code segment. Listing 6.6 Binary-to-BCDconversion circuit module bin2bcd ( input wire clk, reset, input wire start, 5 i n p u t w i r e [12:0] bin, output reg ready, done-tick, o u t p u t w i r e [3:0] bcd3, bcd2, bcdl, bcdO 1; 10 // s y m b o l i c s t a t e d e c l a r a t i o n l o c a l p a r a m [I :01 idle = 2 'b00, op = 2'b01, done = 2 'b10; IS // signal declaration r e g [I:01 state-reg , state-next ; r e g 112:01 p2sdreg, p2s-next ; r e g [3:01 n-reg , n-next ; 20 r e g [3:01 bcd3_reg, bcd2_reg, bcdl-reg , bcd0-reg ; r e g [3:01 bcd3-next , bcd2-next , bcdl-next , bcd0-next ; w i r e C3:01 bcd3_tmp, bcd2-tmp , bcdl-tmp , bcd0-tmp ; 25 // body // FSMD s t a t e & d a t a r e g i s t e r s a l w a y s Q ( p o s e d g e clk , p o s e d g e reset 1 i f (reset) begin state-reg <= idle; p2s-reg <= 0; n-reg <= 0 ; bcd3-reg <= 0 ; bcd2-reg <= 0 ; bcdl-reg <= 0 ; bcd0-reg <= 0 ; end else begin state-reg <= state-next; p2s-reg <= p2s-next ; n-reg <= n-next; bcd3-reg <= bcd3-next ; bcd2-reg <= bcd2-next ; bcdl-reg <= bcdl-next ; bcd0-reg <= bcd0-next ; end so / / FSMD n e x t - s t a t e l o g i c always Q* begin state-next = state-reg; ready = l'bO; done-tick = l'bO; n-next = n-reg; c a s e (state-reg) idle : begin ready = l'bl; i f (start) begin state-next = op; bcd3-next = 0 ; bcdl-next = 0; bcd0-next = 0; n-next = 4'b1101; // i n d e x p2s-next = bin; // s h i f t r e g i s t e r state-next = op; end end op : begin // s h i f t in binary bit p2s-next = p2s-reg << 1; / / s h i f t 4 BCD d i g i t s //{bcd3_next, bcd2_next, bcdl-next, bcdO-next)= //{ bcd3-tmp [2:0], bcd2_tmp, bcdl-tmp , bcd0-tmp , // p 2 s _ r e g [ l 2 ] ) bcd0-next = CbcdO-tmp [2:01 , p2s-reg [I21 ; bcdl-next = {bcdl-tmp C2:Ol , bcd0-tmp C311; bcd2-next = Cbcd2-tmp [2:01 , bcdl-tmp [31); bcd3-next = (bcd3-tmp [2 :01 , bcd2-tmp [31) ; n-next = n-reg - 1; i f (n-next==O) state-next = done; end done : begin done-tick = l'bl; state-next = idle; end d e f a u l t : state-next = idle; endcase end // data path function units lor a s s i g n bcd0-tmp = (bcdO-reg > 4) ? bcdO_reg+3 : bcd0-reg; a s s i g n bcdl-tmp = ( b c d l - r e g > 4) ? b c d l _ r e g + 3 : b c d l - r e g ; a s s i g n bcd2-tmp = ( b c d 2 - r e g > 4) ? b c d 2 _ r e g + 3 : b c d 2 - r e g ; a s s i g n bcd3-tmp = ( b c d 3 - r e g > 4) ? b c d 3 _ r e g + 3 : b c d 3 - r e g ; 110 // output assign bcdO = bcd0-reg; assign bcdl = bcdl-reg; assign bcd2 = bcd2-reg; assign bcd3 = bcd3-reg; 115 endmodule 6.3.4 Period counter A period counter measures the period of a periodic input waveform. One way to construct the circuit is to count the number of clock cycles between two rising edges of the input signal. Since the frequency of the system clock is known, the period of the input signal can be derived accordingly. For example, if the frequency of the system clock is f and the number of clock cycles between two rising edges is N, the period of the input signal is N*f. The design in this subsection measures the period in milliseconds. Its ASMD chart is shown in Figure 6.12. The period counter takes a measurement when the s t a r t signal is asserted. We use a rising-edge detection circuit to generate a one-clock-cycle tick, edge, to indicate the rising edge of the input waveform. After s t a r t is asserted, the FSMD moves to the waite state to wait for the first rising edge of the input. It then moves to the count state when the next rising edge of the input is detected. In the count state, we use two registers to keep track of the time. The t register counts for 50,000 clock cycles, from 0 to 49,999, and then wraps around. Since the period of the system clock is 20 ns, the t register takes 1 ms to circulate through 50,000 cycles. The p register counts in terms of milliseconds. It is incremented once when the t register reaches 49,999. When the FSMD exits the count state, the period of the input waveform is stored in the p register and its unit is milliseconds. The FSMD asserts the done-tick signal in the done state, as in previous examples. The code follows the ASMD chart and is shown in Listing 6.7. We use a constant, CLKMS-COUNT, for the boundary ofthe millisecond counter. It can be replaced if a different measurement unit is desired. Listing 6.7 Period counter module period-counter ( input wire clk, reset, input wire start, si, 5 output reg ready, done-tick , output wire [9:01 prd ); // symbolic s t a t e d e c l a r a t i o n IO localparam [1:01 idle = 2'b00, waite = 2'b01, count = 2'b10, DESIGN EXAMPLES 165 Figure 6.12 ASMD chart of a period counter. done = 2 ' b l l ; 15 // constant declaration l o c a l p a r a m CLK-MS-COUNT= 50000; / / I ms t i c k // signal declaration 20 reg [1:01 s t a t e - r e g , state-next ; reg [15:01 t - r e g , t - n e x t ; // up to 50000 reg [9:01 p-reg, p-next; // up to 1 sec reg delay-reg ; wire edg; 25 // body // FSMD s t a t e & d a t a r e g i s t e r s always Q(posedge c l k , posedge r e s e t ) if (reset) begin s t a t e - r e g <= i d l e ; t - r e g <= 0 ; p - r e g <= 0 ; d e l a y - r e g <= 0 ; end else begin s t a t e - r e g <= s t a t e - n e x t ; t - r e g <= t - n e x t ; p - r e g <= p - n e x t ; d e l a y - r e g <= s i ; end // rising-edge tick 45 assign edg = -delay-reg & s i ; // FSMD n e x t - s t a t e l o g i c always Q* begin state-next = state-reg; ready = 1 'bO; done-tick = l'bO; p-next = p-reg; t-next = t-reg; case (state-reg) idle : begin ready = l ' b l ; if (start) state-next = waite; end waite: // wait for the f i r s t edge if (edg) begin state-next = count; t-next = 0; p-next = 0; end count : i f (edg) // 2nd edge arrived state-next = done; else // otherwise count i f ( t - r e g == CLK-MS-COUNT-1) begin t-next = 0; p-next = p-reg + 1; end else t-next = t-reg + 1; done : begin done-tick = l ' b l ; state-next = idle; end default : state-next = idle; endcase end // I ms tick // ouput 911 assign prd = p-reg; endmodule 6.3.5 Accurate low-frequency counter A frequency counter measures the frequency of a periodic input waveform. The common way to construct a frequency counter is to count the number of input pulses in a fixed amount of time, say, 1 second. Although this approach is fine for high-frequency input, it cannot measure a low-frequency signal accurately. For example, if the input is around 2 Hz, the A). measurement cannot tell whether it is 2.123 Hz or 2.567 Hz. Recall that the frequency is the reciprocal of the period (i.e., frequency = An alternative approach is to measure the period of the signal and then take the reciprocal to find the frequency. We use this approach to implement a low-frequency counter in this subsection. This design example demonstrates how to use the previously designed parts to construct a large system. For simplicity, we assume that the frequency of the input is between 1 and 10 Hz (i.e., the period is between 100 and 1000 ms). The operation of this circuit includes three tasks: 1. Measure the period. 2. Find the frequency by performing a division operation. 3. Convert the binary number to BCD format. We can use the period counter, division circuit, and binary-to-BCD converter to perform the three tasks and create another FSM as the master control to sequence and coordinate the operation of the three circuits. The block diagram is shown in Figure 6.13(a), and the ASM chart of the master control is shown in Figure 6.13(b). The FSM uses the start and done-tick signals of these circuits to initialize each task and to detect completion of the task. The code is shown in Listing 6.8. si start b prd-start 4 prd-done-tick 1 si done-tick period-counter prd main control FSM 1000000,0 4 div-start ,start dvnd ddvsr * , done-tick div div-done-tick quo rmd * b2b-start start bin 4 b2b-done-tick done-tick bin2bcd > bcd3 bcd2 bcdl bcdO bcdo ,bcdl (a) Top-level b l o c k diagram I prd-start = I .....................,............. . ................................... prd-donetick==l T v div-start = I I T T L ................................... 8 (b) ASM chart o f main control Figure 6.13 Accurate low-frequency counter. Listing 6.8 Low-frequency counter module low-freq-counter ( input wire clk, reset, input wire start, si, i o u t p u t w i r e [3:01 bcd3, bcd2, bcdl, bcdO 1; // svmbolic localparam state [I : 01 idle count frq b2b declaration = 2'b00, = 2'b01, = 2'b10, = 2'bll; 15 // s i g n a l d e c l a r a t i o n r e g [I:01 state-reg , state-next ; w i r e [9:0] prd; w i r e [19:01 dvsr , dvnd, quo; reg prd-start , div-start , b2b-start ; 20 w i r e prd-done-tick , div-done-tick , b2b-done-tick; ................................................. // component i n s t a n t i a t i o n ................................................. 25 // i n s t a n t i a t e period counter period-counter prd-count-unit ( . clk(c1k) , .reset(reset), . start (~rd-start), . si(si), .ready(), .done-tick(prd-done-tick), .~rd(~rd)); // instantiate division circuit M div # ( . W (20) , . CBIT ( 5 ) ) div-unit ( . clk (clk) , . reset (reset), . start (div-start ) , . dvsr (dvsr) , . dvnd (dvnd) , . quo (quo) , . rmd , .ready(), .done-tick(div-done-tick)); // i n s t a n t i a t e binary-to-BCD convertor 35 bin2bcd b2b-unit ( . clk (clk) , . reset (reset), . start (b2b-start), . bin(quo [12:O]) , .ready( ) , . d o n e _ t i c k ( b 2 b _ d o n e _ t i c k ) , .bcd3(bcd3), . bcd2 (bcd2), . bcdl (bcdl) , .bcd0 (bcdo)) ; // signal width extension 40 a s s i g n dvnd = 20'd1000000; a s s i g n dvsr = IlO'b0, prd); ................................................. // master FSM ................................................. a l w a y s Q ( p o s e d g e clk , p o s e d g e reset i f (reset) state-reg <= idle; else 50 state-reg <= state-next ; always Q* begin state-next = state-reg; prd-start = l'bO; div-start = l'bO; case (state-reg) idle : if (start) begin prd-start = l'bl; state-next = count; end count : if (prd-done-t ick) begin div-start = l'bl; state-next = frq; end frq: if (div-done-tick) begin b2b-start = l ' b l ; 71 state-next = b2b; end b2b : if (b2b-done-tick) state-next = idle; xo endcase end endmodule 6.4 BIBLIOGRAPHIC NOTES FSMD is usually discussed in the context of high-level synthesis. Principles of Digital Design by D. D. Gajski contains a comprehensive chapter discussing relevant issues and algorithms of FSMD design and implementation. 6.5 SUGGESTED EXPERIMENTS 6.5.1 Alternative debouncing circuit Consider the alternative debouncing circuit in Experiment 5.5.2. Redesign the circuit using the RT methodology: 1. Derive the ASMD chart for the circuit. 2 . Derive the HDL code based on the ASMD chart. 3. Replace the debouncing circuit in Section 6.2.5 with the alternative design and verify its operation. 6.5.2 BCD-to-binary conversion circuit A BCD-to-binary conversion converts a BCD number to the equivalent binary representation. Assume that the input is an 8-bit signal in BCD format (i.e., two BCD digits) and the output is a 7-bit signal in binary representation. Follow the procedure in Section 6.3.3 to design a BCD-to-binary conversion circuit: 1. Derive the conversion algorithm and ASMD chart. 2. Derive the HDL code based on the ASMD chart. 3. Derive a testbench and use simulation to verify operation of the code. 4. Synthesize the circuit, program the FPGA, and verify its operation. 6.5.3 Fibonacci circuit with BCD 110: design approach 1 To make the Fibonacci circuit more user friendly, we can modify the circuit to use the BCD format for the input and output. Assume that the input is an 8-bit signal in BCD format (i.e., two BCD digits) and the output is displayed as four BCD digits on the seven-segment LED display. Furthermore, the LED will display "9999" if the resulting Fibonacci number is larger than 9999 (i.e., overflow). The operation can be done in three steps: convert input to the binary format, compute the Fibonacci number, and convert the result back to BCD format. The first design approach is to follow the procedure outlined in Section 6.3.5. We first construct three smaller subsystems, which are the BCD-to-binary conversion circuit, Fibonacci circuit, and binary-to-BCD conversion circuit, and then use a master FSM to control the overall operation. Design the circuit as follows: 1. Implement the BCD-to-binary conversion circuit in Experiment 6.5.2. 2. Modify the Fibonacci number circuit in Section 6.3.1 to include an output signal to indicate the overflow condition. 3. Derive the top-level block diagram and the master control FSM state diagram. 4. Derive the HDL code. 5. Derive a testbench and use simulation to verify operation of the code. 6. Synthesize the circuit, program the FPGA, and verify its operation. 6.5.4 Fibonacci circuit with BCD 110: design approach 2 An alternative to the "subsystem approach" in Experiment 6.5.3 is to integrate the three subsystems into a single system and derive a customized FSMD for this particular application. The approach eliminates the overhead of the control FSM and provides opportunities to share registers among the three tasks. Design the circuit as follows: 1. Redesign the circuit of Experiment 6.5.3 using one FSMD. The design should eliminate all unnecessary circuits and states, such as the various done-tick signals and the done states, and exploit the opportunity to share and reuse the registers in different steps. 2. Derive the ASMD chart. 3. Derive the HDL code based on the ASMD chart. 4. Derive a testbench and use simulation to verify operation of the code. 5. Synthesize the circuit, program the FPGA, and verify its operation. 6. Check the synthesisreport and compare the number of LEs used in the two approaches. 7. Calculate the number of clock cycles required to complete the operation in the two approaches. 6.5.5 Auto-scaled low-frequency counter The operation ofthe low-frequency counter in Section 6.3.5 is very restricted. The frequency range of the input signal is limited between 1 and 10 Hz. It loses accuracy when the frequency is beyond this range. Recall that the accuracy of this frequency counter depends on the accuracy of the period counter of Section 6.3.5, which counts in terms of millisecond ticks. We can modify the t counter to generate a microsecond tick (i.e., counting from 0 to 49) and increase the accuracy 1000-fold. This allows the range of the frequency counter to increase to 9999 Hz and still maintain at least four-digit accuracy. Using a microsecond tick introduces more than four accuracy digits for low-frequency input, and the number must be shifted and truncated to be displayed on the seven-segment LED. An auto-scaled low-frequency counter performs the adjustment automatically, displays the four most significant digits, and places a decimal point in the proper place. For example, according to their range, the frequency measurements will be shown as " 1.234", " 12.34", "123.4", or "1234". The auto-scaled low-frequency counter needs an additional BCD adjustment circuit. It first checks whether the most significant BCD digit (i.e., the four MSBs) of a BCD sequence is zero. If this is the case, the circuit shifts the BCD sequence to the left four positions and increments the decimal point counter. The operation is repeated until the most significant BCD digit is not "0000". The complete auto-scaled low-frequency counter can be implemented as follows: 1. Modify the period counter to use the microsecond tick. 2. Extend the size of the binary-to-BCD conversion circuit. 3. Derive the ASMD chart for the BCD adjustment circuit and the HDL code. 4. Modify the control FSM to include the BCD adjustment in the last step. 5. Design a simple decoding circuit that uses the decimal-point counter's output to activate the desired decimal point of the seven-segment LED display. 6. Derive a testbench and use simulation to verify operation of the code. 7. Synthesize the circuit, program the FPGA, and verify its operation. 6.5.6 Reaction timer Eye-hand coordination is the ability of the eyes and hands to work together to perform a task. A reaction timer circuit measures how fast a human hand can respond after a person sees a visual stimulus. This circuit operates as follows: 1. The circuit has three input pushbuttons, corresponding to the c l e a r , s t a r t , and s t o p signals. It uses a single discrete LED as the visual stimulus and displays relevant information on the seven-segment LED display. 2. A user pushes the c l e a r button to force the circuit to return to the initial state, in which the seven-segment LED shows a welcome message, "HI," and the stimulus LED is off. 3. When ready, the user pushes the s t a r t button to initiate the test. The seven-segment LED goes off. 4. After a random interval between 2 and 15 seconds, the stimulus LED goes on and the timer starts to count upward. The timer increases every millisecond and its value is displayed in the format of "0.000" second on the seven-segment LED. 5. After the stimulus LED goes on, the user should try to push the s t o p button as soon as possible. The timer pauses counting once the s t o p button is asserted. The seven- segment LED shows the reaction time. It should be around 0.15 to 0.30 second for most people. 6. If the s t o p button is not pushed, the timer stops after 1 second and displays " 1.00OU. 7. If the s t o p button is pushed before the stimulus LED goes on, the circuit displays "9.999" on the seven-segment LED and stops. Design the circuit as follows: 1. Derive the ASMD chart. 2. Derive the HDL code based on the ASMD chart. 3. Synthesize the circuit, program the FPGA, and verify its operation. 6.5.7 Babbage difference engine emulation circuit The Babbage difference engine is a mechanical digital computation device designed to tabulate a polynomial function. It was proposed by Charles Babbage, an English mathematician, in the nineteenth century. The engine is based on Newton's method of differences and avoids the need for multiplication. For example, consider a second-order polynomial + + f ( n )= 2n2 3n 5. We can find the difference between f ( n )and f ( n- I ) : Assume that 71 is an integer and n 2 0. The f ( n )can be defined recursively as ifn =0 f(n)={ ?(n-l)+4n+l ifn>o + + This process can be repeated for the 4n 1expression. Let g(n)= 4n 1. We can find the difference between g(n)and g(n - 1 ) : The g(n)can be defined recursively as and f ( n )can be rewritten as Note that only additions are involved in the recursive definitions o f f ( n )and g(n). Based on the definition of the last two recursive equations, we can derive an algorithm to compute f ( n ) .TWOtemporary registers are needed to keep track of the most recently calculated f ( n )and g(n),and two additions are needed to update f ( n )and g(n).Assume that n is a 6-bit input and interpreted as an unsigned integer. Design this circuit using the RT methodology: 1. Derive the ASMD chart. 2. Derive the HDL code based on the ASMD chart. 3. Derive a testbench and use simulation to verify operation of the code. 4. Synthesize the circuit, program the FPGA, and verify its operation. + + + 5. Let h(n)= n3 2n2 2n 1. Use the method above to find the recursive rep- resentation of h(n)(note that three levels of recursive equations are needed for a three-order polynomial). Repeat steps 1 to 4. This Page Intentionally Left Blank CHAPTER 7 SELECTED TOPICS OF VERILOG Since the main focus of this book is on digital design, we just introduce the minimal subset of Verilog and rely on some simple guidelines and templates. In this chapter, we examine several selected Verilog topics in more detail. Except for the last section, which provides an overview of simulation-related constructs, these topics are related to synthesis and help us to develop more sophisticated codes. This chapter can be skipped without affecting the remaining chapters. 7.1 BLOCKING VERSUS NONBLOCKING ASSIGNMENT Thereare two kinds of assignments that can be used in an alwaysblock: blockingassignment and nonblocking assignment. Three simple guidelines were given in the earlier chapters: Separatethe circuit into registers and combinational circuits. Select a proper template for the registers, which use nonblocking assignments inside. Use blocking assignments to describe the combinational circuits. We examine the two kinds of assignments and explain the rationale behind the guidelines in this section, and introduce an alternative coding style in the next section. 7.1.1 Overview Blockingassignment The basic syntax of a blocking assignment is [var] = [expressionl ; FPGA Protoyping by VerilogExamples. By Pong P.Chu Copyright @ 2008 John Wiley & Sons,Inc. 176 SELECTED TOPICS OF VERILOG When the assignment is executed, the right-hand-side expression is evaluated and assigned to the left-hand-side variable without intenuption from any other statements. Thus, it "blocks" the other assignments until execution of the current assignment is completed. The behavior of the blocking assignment is similar to the variable assignment in the C language. Nonblocking assignment The basic syntax of a nonblocking assignment is [var] <= [expression] ; The behavior of a nonblocking assignment is more subtle and can best be explained from a hardware's perspective. Recall that an always block can be thought of as an abstract hardware part. Timing control constructs can be added to the block to model the propagation delays. When there is no explicit timing control, as in our synthesizable codes, an implicit hypothetical time step is used to model the delay. When an always block is activated, the right-hand-side expressions of nonblocking assignments are evaluated at the beginning of the time step. When the execution reaches the end of the always block (i.e., at the end of the time step), the evaluated values are assigned to the left-hand-side variables of the nonblocking assignment. The assignment is known as "nonblocking" since other statements can be executed between the evaluation and the assignment. Let x be the variable assigned in a nonblocking assignment. While the actual scheduling in the Verilog model is quite complex, the behavior of a nonblocking assignment can be interpreted as follows: The value of x is assigned to xent,, in the beginning of the always block. xeZLtreplaces x in left-hand-side variable. x,,,~,., replaces x in right-hand-side expressions. The value of x , , , ~is assigned to x at the end of the always block. An interpretation is shown in the comments of the following code segment: always Q* begin // Xentry = X ... end // x = xezLt Example To understand the difference between the blocking and nonblocking assignments, let us reconsider the three-input and circuit discussed in Section 3.3.4. The code is repeated in Listing 7.1. It uses blocking assignments and the inferred circuit is shown in Figure 3.3(a). Listing 7.1 And circuit using blocking assignments module and-block ( input wire a , b, c , output reg y 5 1; always @* begin y = a; I0 y=y&b; y=y&c; end endmodule The behavior of the assignments is similar to the sequential statements in the C language and y gets the values of a & b & c in the end. Note that the code is just for demonstration purposes. It is a poor practice to describe hardware using sequential semantics. If we replace the blocking assignments with nonblocking assignments, the revised code is shown in Listing 7.2. The interpretation of the use of y is shown as comments. Listing 7.2 And circuit using nonblocking assignments module and-nonblock ( input wire a, b, c, output reg y 5 1; always Q* begin y <=a; 10 y <= y & b ; y <= y & C; end // yentry =Y // yextt = a // yextt =yentry & b // Yexzt =Yentry & C / / .v = y e x , t endmodule Note that the first two assignments have no effect and the code is the same as always Q* y <= y & c ; The corresponding circuit diagram is shown in Figure 3.3(b) and it is not the desired circuit. 7.1.2 Combinational circuit The example of the previous subsection is an extreme case. Except for the default value, most codes for combinational circuits do not assign the same variable multiple times. Both blocking and nonblocking assignments can be used to describe the same circuit. However, there are subtle differences. The following example explains the differences. Let us consider the 1-bit equality circuit discussed in Section 1.2. The revised code using blocking assignments is shown in Listing 7.3. We explicitly list the variables in the sensitivity list. Listing 7.3 Equality circuit using blocking assignments module eql-block ( input wire iO, i1, output reg eq 5 1; reg pO, PI; a l w a y s @(iO,il) / / o n l y iO and i l i n s e n s i t i v i t y l i s t lo // the order of statements is important begin PO = -iO & -il; pl = i0 & il; eq = pO I pi; I? end endmodule Note that the sensitivity list consists of only i O and i l . When one of them changes, the always block is activated, PO, p l , and eq are evaluated sequentially, and eq is updated at the end of the first time step. The order of the statements is important. Assume that we move the last statement to the beginning: always @(iO, ill begin eq = pO I pi; PO = -iO & -il; pl = i0 & il; end In the first statement, since pO and p l have not yet been assigned new values, the values from the previous activation will be used. The previous values infer latches and thus the code is not correct. We can replace the blocking assignments with nonblocking assignments, as shown in Listing 7.4. The interpretations of these assignments are shown as comments. Listing 7.4 Equality circuit using nonblocking assignments module eql-non-block ( input wire iO, il, output reg eq s 1; always Q(iO,il,pO,pl) //pO,plalso~nsensitivitylist l o / / the order of statements is not important begin / / P O W L ~ , , =PO;plent,, =p l ; - p O <= - i O & i l ; / / pOezzt = iO & i l ; pl <= i O & i l ; / / p l , , , t = i O & i l eq <= PO I pl ; 15 end // eq,,,t =pO,,t,, Ipl,,t,, / / eq = eq,,,t;pO = p O e Z t t ; p l= p l e z Z t ; endmodule Note that pO and p l are also included in the sensitivity list. When i O or il changes, the always block is activated and the new values are assigned to pO and p i in the end of the first time step. Since eq is based on the old values of pO and p l (i.e., pOentryand pientry), it remains the same. After completion of the execution of the current time step, the always block is activated again because pO and p l change (and this is the reason that pO and p l are included in the sensitivity list). The eq variable is updated with the new values of pO and p l at the end of the second time step. Note that the result will be the same if we change the order of these statements. While both codes describe the same circuits, it takes more time to simulate the code with nonblocking assignments. Because of this, the guideline recommends using blocking assignments to describe combinational circuits. 7.1.3 Memory element In the memory element templates in Section 4.2, nonblocking assignments are used to infer memory. For example, the code for a D FF is always Q(posedge clk) q <= d ; It is possible to infer a memory element using a blocking assignment, as in always Q (posedge clk) q = d; Although the code works properly for an isolated FF, there are some subtle problems when multiple registers interact with each other. Consider two registers that switch data in every clock cycle. With blocking assignments, the code becomes always Q(posedge clk) a = b; always Q(posedge clk) b = a; At the rising edge of c l k , both always blocks are activated and operated in parallel. The two operations should be completed in a time step. According to the Verilog standard, the execution of the two always blocks can be scheduled in any order. If the first always block is executed first, a gets the value of b immediately because of the blocking assignment. When the second always block is executed, b gets the updated value of a, which is its original value and thus its value remains the same. Similarly, a gets its original value if the second always block is executed first. This is known as a race condition in Verilog. From Verilog's point of view, both results are valid. Now let us revise the code with nonblocking assignments (the begin and end delimiters are added to accommodate the comments): always Q(posedge clk) begin // bentTy = b a <= b ; / / aez,t = bentry end // a = aer,t always Q(posedge clk) begin // arnt7.y - a b <= a ; / / bezit = sent,, end / / b = b,,it The interpretation of blocking assignment is shown in the comments. Since the original entry values are used in assignments, both a and b get the correct values regardless of the order of execution. Figure 7.1 Circuits inferred by mixed assignment. Because the blocking assignments model the desired behavior and avoid the race condition, the templates in Section 4.2 always use nonblocking assignments to infer FFs and registers. 7.1.4 Sequential circuit with mixed blocking and nonblocking assignments The memory element templates discussed in Section 4.2 are the simplest sequential codes. It is possible to put multiple assignments, including both blocking and nonblocking assignments, in the same always block. We use a simple example to explain the behaviors of various combinations and to better understand the assignments. Consider the circuit in Figure 7.l(b). It performs the and operation over a and b and stores the result to a D FF at the rising edge of the clock. Based on our previous approach, we can separate memory and the combinational circuit and derive the two-segment code, as shown in Listing 7.5. Listing 7.5 Two-segment implementation module ab-f f -2seg ( input wire clk, input wire a , b , 5 output reg q ); reg q-next; 10 // D FF always Q(posedge clk) q <= q - n e x t ; // combinational c i r c u i l 15 always Q* q-next = a & b ; endmodule Alternatively, we can combine the two segments and describe the circuit in a single always block. Six attempts, with various combinations of blocking and nonblocking assignments, are made in Listing 7.6. Listing 7.6 Mixed assignment example module ab-f f - a l l ( input wire clk, input wire a , b, 5 o u t p u t r e g qO, q l , q 2 , q 3 , q 4 , q5 1; reg abO, a b l , a b 2 , ab3, ab4, ab5; lo // attempt 0 always Q(posedge clk) begin abO = a & b ; qO <= abO; 15 end // attempt I always Q(posedge clk) begin // ablent,, = abl; qlentTy= q l ; 20 a b l <= a & b ; / / a b l e z i t = a & b q l <= a b l ; // qlezit = ablentry end // abl = ableztt;q l = qlezit / / attempt 2 25 a l w a y s Q ( p o s e d g e c l k ) begin ab2 = a & b ; q2 = ab2; 30 end / / attempt 3 (switch the order of attempt 0) always Q (posedge clk) begin 35 q3 <= a b 3 ; ab3 = a & b; end // attempt 4 (switch the order of attempt I) 40 a l w a y s Q ( p o s e Q g e c l k ) begin // ab4,,tTy = ab4; q4,,tTY = q4; q4 <= a b 4 ; // q4ezit = ab4entry ab4 <= a & b ; // ab4,,,t = a & b end // ab4 = able,,t; q4 = q4,,it 45 / / attempt 5 (switch the order of attempt 2) always Q(posedge clk) begin 182 SELECTED TOPICS OF VERILOG q5 = ab5; 50 ab5 = a & b ; end endmodule In attempt 0, assignments to abO and qO infer two registers initially, one to store the registered abO and one to store the registered qO. Since abO is updated immediately by the blocking assignment, qO gets the value of a & b. The corresponding circuit diagram is shown in Figure 7.l(a). Since abO is not used outside the always block, the registered abO output is not needed and thus the corresponding register can be removed. The resulting diagram is shown in Figure 7.l(b), which is the desired circuit. In attempt 1, a blocking assignment is used for abl. The corresponding interpretation is shown in the comments. Note that q l gets abIent,,, not ablezit.The ablent,, is the previous stored value of abl and corresponds to the registered output. The corresponding diagram is shown in Figure 7.l(c). An unintended input buffer is inferred and the storage of a & b is delayed by one clock cycle. In attempt 2, blocking assignments are used for both ab2 and q2. The circuit inferred is identical to that in attempt 0, as shown in Figure 7.l(a) and (b). Since using blocking assignments to infer FFs may introduce a race condition, as discussed in Section 7.1.3, this type of code is not recommended. For demonstration purposes, let us examine what happens after switching the order of the assignments of attempts 0, 1, and 2. The results are shown in attempts 3, 4, and 5. In attempt 3, ab3 is used before it is assigned a new value. Thus, q3 gets the "previous value" from the earlier activation. The value is stored in a register and corresponds to the registered a & b. The inferred circuit corresponds to the diagram in Figure 7.l(c). In attempt 4, switching the order has no effect on the code, as explained by the interpretation in the comments. It is identical to the code in attempt 1. In attempt 5, ab5 is used before it is assigned a new value and thus q5 gets the registered a & b. It infers a circuit identical to that in attempt 3. In summary, only the code in attempt 0 describes the desired circuit correctly and reliably. 7.2 ALTERNATIVE CODING STYLE FOR SEQUENTIAL CIRCUIT Our sequential code template follows the block diagram in Figure 4.2 and separates the register to an individual code segment. With an understanding of blocking and nonblocking assignments, we can merge the register and the next-state logic into a single always block. This style of coding tends to be more compact. The code should follow the approach of attempt 1 in Section 7.1.4: Use blocking assignments to obtain intermediate results ofthe next-state logic. These assignments should be sequenced in proper order. Use nonblocking assignments to assign the intermediate results to registers. In the following subsections, we use several examples to illustrate this style. 7.2.1 Binary counter The free-running counter is discussed in Section 4.3.2. We can revise the code in Listing 4.9 to combine the next-state logic and the register, as shown in Listing 7.7. Listing 7.7 Free-running binary counter with merged register and next-state logic module bin-counter-merge #(parameter N=8) ( input wire clk, reset, 5 output wire max-tick, output wire [N-1:Ol q ); //signal declaration lo reg [N-1:Ol r-next, r-reg; // body // r e g i s t e r and next-state l o g i c always @(posedge clk, posedge reset) 15 if (reset) r-reg <= 0 ; // { N { l b ' 0 ) ) else begin // next-state logic r-next = r-reg + 1; // r e g i s t e r r-reg <= r - n e x t ; end // otttpttt logic 25 assign q = r-reg; a s s i g n max-tick = (r-reg==2**N-1) ? l'bl : l J b O ; endmodule Note that the output logic description a s s i g n max-tick = (r-reg==2**N-1) ? l'bl : l'bO; must be placed outside the always block. If it is within the block, an extra FF is inferred for max-tick and introduces a delay of one clock cycle. Since r n e x t is not used in another place, we can merge the two statements r-next = r-reg + 1; r-reg <= r-next; into r-reg <= r-reg + 1; After we replace r - r e g with q, the code can be simplified further, as shown in Listing 7.8. Listing 7.8 Free-running binary counter with compact code module bin-counter-terse #(parameter N=8) ( input wire clk, reset, 5 output wire max-tick, output reg [N-1:Ol q 1; // body 10 always Q(posedge c l k , posedge r e s e t ) if (reset) q <= 0 ; else q <= q + 1 ; 15 // o u t p u t l o g i c assign max-tick = (q==2**N-1) ? l ' b l : l J b O ; endmodule In this code, q in the right-hand-side expression is the output of the register and q on the left-hand side is the new value, which is stored to the register at the rising edge of the next clock. The universal binary counter in Listing 4.10 can be modified in a similar way and the code is shown in Listing 7.9. Listing 7.9 Universal binary counter with merged register and next-state logic module univ-bin-counter-merged #(parameter N=8) ( input wire clk, reset, input wire syn-clr , load, en, up, input wire [N-1:Ol d , output wire max-tick, min-tick, output reg [N-1:01 q ); 10 // body // r e g i s t e r and next-state l o g i c always Q (posedge c l k , posedge r e s e t ) if (reset) q <= 0 ; / / else if (syn-clr) q <= 0 ; else if (load) q <= d ; else if (en & up ) q <= q + 1 ; else if (en & -up ) q <= q - 1 ; / / no e l s e b r a n c h s i n c e q <= q i s implicitly implied // ozctput l o g i c assign max-tick = (q==2**N-1) ? l J b l : l J b O ; assign min-tick = (q==O) ? l ' b l : l'bO; Note that the last else branch is omitted. It implies that q gets its previous value, i.e., This is exactly the desired behavior. 7.2.2 FSM The state register and next-state logic of an FSM can be merged in a similar way. For example, consider the FSM in Listing 5.1. The revised code is shown in Listing 7.10. Listing 7.10 FSM with merged register and next-state logic module f sm-eg-merged ( input wire clk, r e s e t , input wire a , b, 5 output wire yo, yl ); // symbolic s t a t e d e c l a r a t i o n parameter [1:0] SO = 2'b00, 10 sl = 2'b01, s2 = 2'blO; // signal declaration reg [1:01 s t a t e - r e g ; I5 // s t a t e r e g i s t e r and n e x t - s t a t e l o g i c always @ ( posedge clk , posedge r e s e t ) if (reset) s t a t e - r e g <= SO; else case (state-reg) SO: i f ( a ) if (b) s t a t e - r e g <= s 2 ; else s t a t e - r e g <= s l ; else s t a t e - r e g <= SO; s l : if (a) s t a t e - r e g <= SO; else s t a t e - r e g <= s l ; s 2 : s t a t e - r e g <= SO; d e f a u l t s t a t e - r e g <= SO; endcase // Moore o u t p u t l o g i c assign yl = (state-reg==sO) I I (state-reg==sl); 40 // Mealy output l o g i c a s s i g n yo = ( s t a t e - r e g = = s O ) & a & b ; endmodule Since the outputs are not registered, the corresponding statements must be placed outside the always block. 7.2.3 FSMD We can apply the same approach to an FSMD as well. Consider the division FSMD example in Listing 6.5. The revised code is shown in Listing 7.1 1. Listing 7.11 Division FSMD with merged register and combinational circuit module div-combined #( parameter W = 8, CBIT = 4 // CBIT=log2 (W)+l 5 ( input wire clk, r e s e t , input wire s t a r t , i n p u t w i r e [W-1:Ol d v s r , d v n d , 10 output wire ready, done-tick , o u t p u t w i r e [W-1:Ol q u o , rmd 1; // symbolic state declaration IS localparam [1:01 idle = 2'b00, op = 2 ' b 0 1 , l a s t = 2'b10, done = 2 ' b l l ; // signal declaration r e g [ I : 01 s t a t e - r e g ; reg [W-1:0] r h - r e g , r l - r e g , r h - t m p , d - r e g ; r e g [CBIT -1 :01 n - r e g , n - n e x t ; s reg q-bit; // fsmd r e g i s t e r s and next-state logic always O(posedge clk , posedge reset begin 30 if (reset) begin s t a t e - r e g <= i d l e ; r h - r e g <= 0 ; r l - r e g <= 0 ; d-reg <= 0 ; n - r e g <= 0 ; end else begin ................................................ // data path functional units // to get intermediate r e s u l t s ................................................ // compare and subtract c i r c u i t i f ( r h - r e g >= d - r e g ) begin rh-tmp = rh-reg - d-reg; q-bit = l ' b l ; end else begin rh-tmp = rh-reg; q-bit = l'bO; end // index decrement c i r c u i t n-next = n-reg - 1; // s t a t e and data r e g i s t e r s and next-state logic ................................................ case (state-reg) idle : begin if (start) begin r h - r e g <= 0 ; r l - r e g <= d v n d ; / / d i v i d e n d d - r e g <= d v s r ; / / d i v i s o r n-reg <= C B I T ; // index s t a t e - r e g <= o p ; end end op : begin // s h i f t rh and r l l e f t r l - r e g <= { r l - r e g [W-2:01 , q - b i t ) ; r h - r e g <= {rh-tmp [w-2: O I , r l - r e g [W-11); // decrease index n - r e g <= n - n e x t ; if (n-next==l) s t a t e - r e g <= l a s t ; end l a s t : // last i t e r a t i o n begin r l - r e g <= { r l - r e g [w-2:0l , q - b i t 3 ; r h - r e g <= rh-tmp; s t a t e - r e g <= d o n e ; end done : s t a t e - r e g <= i d l e ; d e f a u l t : s t a t e - r e g <= i d l e ; endcase end end 95 // output assign quo = r l - r e g ; a s s i g n rmd = r h - r e g ; // unregistered output loo a s s i g n ready = ( s t a t e - r e g = = i d l e ) ; assign done-tick = (state-reg==done) ; endmodule The code is more complex and includes a section for data path functional units, which generates the intermediate results. Note that some intermediate variables, such as nnext, are used in multiple places later. 7.2.4 Summary In summary, it is possible to merge the next-state logic and register in one always block. This style tends to be more compact and requires fewer variables. However, the code must be crafted carefully to avoid unintended registers. It is recommended only after we have a good comprehension of blocking and nonblocking assignments. 7.3 USE OF THE SIGNED DATA TYPE 7.3.1 Overview Depending on the nature of an application, we can use an unsigned integer, which consists of zero and the positive numbers, or a signed integer, which consists of zero and both negative and positive numbers, in a digital system. We may even need to use both types in a complex system. The signed integer is usually represented in 2's-complement format. A 4-bit "binary wheel" is shown in Figure 7.2, which lists the binary representations and the corresponding unsigned and signed numbers. Close observation shows that the addition and subtraction operations are identical for the two types of numbers. The addition and subtraction of a positive amount corresponds to moving clockwise and counterclockwise along the wheel. For example, " 1001"+"0100" means to move four positions clockwise from "1001" and the result is "1 101". In the unsigned integer format, it is interpreted as (+9) + (+4) = +13, and in the signed integer format, it is interpreted as (-7) + (+4) = -3. The overflow in addition corresponds to a move over the "threshold" of the binary wheel. Note that the thresholds are different for the unsigned and signed interpretations. It is between "1111" and "0000" for the unsigned integer and between "0111" and "1000" for the signed integer. The behavior of a physical adder or subtractor is just like the movement in the binary wheel. The same circuit can be applied to both unsigned and signed formats as long as all operands and the result have the same bit length. For example, let a, b, and sum be three 8-bit signals. The statement sum = a + b ; infers the same hardware and uses the same binary representations regardless of whether these signals are interpreted as unsigned or signed format. This observation is also correct in other arithmetic operations (however, it cannot be applied for nonarithmetic operations, such as relational operations or overflow status generation). On the other hand, we need to distinguish the format when the operands or the result have different bit lengths. This is due to the different requirements in width extension. The 0's Threshold of overtlow for unsigned format add a positive amount Threshold of overflow for signed format Figure 7.2 Four-bit binary wheel. are appended to the front for the unsigned format, which is known as zero extension, but the sign bits are appended to the front for the signed format, which is known as sign extension. For example, the 4-bit representation of -5 is "101 1". It becomes " 1 111-101 1", not "0000-101 1" when extended to 8 bits. For example, let a and sum be two 8-bit signals and b be a 4-bit signal, b3b2bl bO. The statement sum = a + b ; requires b to be extended to 8 bits. The extended b becomes 0000b3b2b1bo if it is in the unsigned format but becomes b3b3b3b3b3b2blb0if it is in the signed format. The inferred hardware for this statement consists of the width extension circuit and an adder. Since the extension circuit is different for the unsigned and signed formats, the statement infers different hardware implementations for the unsigned and signed formats. 7.3.2 Signed number in Verilog-1995 In Verilog-1995, only the integer data type is interpreted as a signed number, and the reg and wire data types are interpreted as unsigned numbers. Since the integer data type has a fixed size (usually 32 bits), it is not flexible. To achieve the signed operation, we frequently need to manipulate the code manually. The signed and unsigned operations are illustrated in the following code segment: r e g [7:01 a , b; r e g [3:01 c ; r e g [7:01 suml , sum2, sum3, sum4; // same w i d t h , can be applied to signed and unsigned suml = a + b ; // automatic 0 extension sum2 = a + c ; / / rnanztal 0 e x t e n s i o n sum3 = a + {4(l'b0), c); // manual sign extension sum4 = a + (4CcC313, c l ; In the first statement, a, b, and suml have identical width and thus infer the same adder circuit regardless of whether they are interpreted as unsigned or signed numbers. In the second statement, c is only 4 bits wide. Its bit length is adjusted according to the rules discussed in Section 3.2.8. Since the reg type is treated as an unsigned number, zero extension is performed and four zeros are appended in front of c. In the third statement, we manually append four zeros in front of c and achieve the same effect as in the previous statement. In the fourth statement, we interpret the variables as signed numbers. To achieve the desired behavior, c must be sign-extended to 8 bits. This can only be done manually. In the code, we replicate the MSB of c four times (i.e., 4{c [31)) to create the sign-extended 8-bit number. 7.3.3 Signed number in Verilog-2001 In Verilog-2001, the signed format is extended to the reg and wire data types. This is done by adding the keyword, signed, in declaration, as in r e g s i g n e d [7:01 a , b; With the signed data type, the previous code segment can be revised as r e g s i g n e d [7:01 a , b; r e g s i g n e d [3:01 c ; r e g s i g n e d [7:01 suml , sum4; ... // same w i d t h , can be applied lo signed and unsigned suml = a + b; // automatic sign extension sum4 = a + c ; The first statement infers a regular adder since a, b, and suml have identical bit length. The signed data type just helps us to be aware of the interpretation of the binary representation. In the second statement, all variables in the right-hand-side expression are with the signed data type and c is sign-extended to 8 bits automatically. Thus, we don't need to pad the variable manually. In a small digital system, we usually use either unsigned or signed format. However, a larger system may contain subsystems of different formats. Verilog is a loosely typed language and the unsigned and signed variables can be mixed in the same expression. USE OF FUNCTION IN SYNTHESIS 191 According to the Verilog standard, the sign extension is performed only if all variables in the right-hand-side expression are with the signed data type. Otherwise, zero extension is performed for all variables. Consider the code segment reg s i g n e d [7:01 a, sum; reg s i g n e d [3:01 b ; reg [3:01 c ; ... sum = a + b + c; Since c is not with the signed data type, the variables in the right-hand-side expression, b and c, are zero extended. Verilog consists of two system functions, $signed( ) and $unsigned( ), which convert the enclosed expression to the signed and unsigned data types, respectively. For example, we can convert the data type of c in the preceding statement: sum = a + b + $ s i g n e d (c); Now all three variables in the right-hand-side expression are with the signed data type and thus b and c are sign extended. Mixed signed and unsigned data types in a complex expression can introduce subtle errors and should be avoided. If it is really necessary, the expression should be kept simple and the conversion functions should be used to ensure the consistency of the data type. 7.4 USE OF FUNCTION IN SYNTHESIS 7.4.1 Overview In a Verilog module, some expressions may occur at many places. Instead of repeating the code, the commonly used part should be abstracted into a routine. This can be achieved by definingfunctions within a module. A Verilog function takes one or more input arguments and returns a single value. During synthesis, the functions are expanded and "flattened" and mapped to hardware. Thus, for synthesis purposes, functions should be kept simple and treated as shorthand for a complex expression. The basic syntax of a function is module ... // f u n c t i o n d e f i n e d w i t h i n module function [result-type] [func-id] ([input-argl) ; begin [statements] ; end endfunction ... endmodule A function is defined within the function and endfunction delimiters. The optional [result-type] specifies the data type of the returned result, which is usually reg with range or integer. The input arguments are declared in [input-argl and the name of the function is specified by [func-id] . A function is described by the statements and the result is returned by a statement like 7.4.2 Examples Consider the binary-to-BCD conversion circuit in Listing 6.6. During the conversion, each BCD digit needs to be incremented in a specific way. To make the FSMD portion clear, we use a separate segment in code: module . . . ... a s s i g n b c d 0 - t m p = ( b c d O - r e g > 4) ? b c d O _ r e g + 3 : b c d 0 - r e g ; a s s i g n b c d l - t m p = ( b c d l - r e g > 4) ? b c d l _ r e g + 3 : b c d l - r e g ; a s s i g n b c d 2 - t m p = (bcd2-reg > 4) ? b c d 2 _ r e g + 3 : b c d 2 - r e g ; a s s i g n b c d 3 - t m p = ( b c d 3 - r e g > 4) ? b c d 3 _ r e g + 3 : b c d 3 - r e g ; endmodule Instead of repeating the same expression four times, we can define a function, b a 0 , for this purpose. The revised code segment becomes module . . . assign bcd0-tmp = ba(bcd0-reg) ; assign bcdl-tmp = ba(bcd1-reg) ; assign bcd2-tmp = ba(bcd2-reg) ; assign bcd3-tmp = ba(bcd3-reg) ; ... // function d e f i n i t i o n (ba: bcd a d j u s t ) f u n c t i o n [3: 11 b a ( r e g [3:0] bcd-in) ; begin ba = ( b c d - i n > 4) ? bcd-in + 3 : b c d - i n ; end endfunction ... endmodule The function b a 0 (for BCD adjust) is defined in the end. It takes a 4-bit argument and returns a Cbit result. We can use this function to replace the previous expression. In fact, we can use bc ( b c d o r e g ) to substitute bcd0-tmp directly and eliminate these variables from the code. Another common application of a function is to calculate the constants whose values depend on other parameters. Consider the mod-m counter discussed in Listing 4.1 1. There are two parameters: M, which specifies the m value, and, N, which specifies the number of bits needed in the counter. The value of N is [log, M1 and should not be an independent parameter. A better approach is to specify N as a local constant and calculate its value inside the module. This can be achieved by using a function. The modified code is shown in Listing 7.12. Listing 7.12 Mod-m counter with function module mod-m-counter-f c # ( p a r a m e t e r M=10) // mod-M ( input wire clk, reset, 5 output wire max-tick , output wire [log2 (M) -1 :O] q ); ADDITIONAL CONSTRUCTS FOR TESTBENCH DEVELOPMENT 193 //signal declaration 10 localparam N = log2(M); // number of b i t s f o r M reg [N-1:0] r-reg; wire CN-1: 01 r - n e x t ; // body I5 // r e g i s t e r always Q(posedge c l k , posedge r e s e t ) if (reset) r - r e g <= 0 ; else 20 r - r e g <= r - n e x t ; // next-state logic assign r-next = (r-reg==(M-1)) ? 0 : r-reg + 1; // output logic 25 assign q = r-reg; assign max-tick = (r-reg==(M-1)) ? 17bl : l'bO; // log2 constant function function integer log2 (input integer n) ; 30 integer i ; begin log2 = 1; for (i = 0 ; 2**i < n ; i = i + 1) log2 = i + 1; 35 end endfunction endmodule A function, log2() , which computes [log, ( x ) l, is defined inside the module and used to obtain the local parameter N. Since the computation is performed when the code is elaborated,the value is determined before synthesis and no physical circuit will be inferred for this function. 7.5 ADDITIONAL CONSTRUCTS FOR TESTBENCH DEVELOPMENT Since our focus is mainly on hardware development, we examine only a small synthesizable subset of Verilog and use two basic testbench templates for verification. Although detailed coverage of the Verilog language and testbench is beyond the scope of this book, in this section we provide a brief overview of several language constructs that help us to develop a more sophisticated testbench. Unlike the synthesizable code, the testbench code is fed to a simulator and executed on a host computer. We can include complex language constructs and sequential algorithms in the code. Many of Verilog constructs resemble those in the C language and can be used in a similar way. 7.5.1 Always block and initial block Verilog has two types of procedural blocks: always block and initial block. An always block contains procedural statements inside and models an abstract circuit part. We examine one special type of always block in Section 3.3. It is intended for synthesis. The block has a sensitivity list but contains no other explicit timing control constructs. Activation and execution of the always block are trigged by the designated events of the sensitivity list. For modeling purposes, an always block can contain timing constructs to specify the relevant propagation delays of various constructs or to wait for a specific event. The sensitivity list can sometimes be omitted. For example, we can use the following segment to model a clock signal, which alternates between 0 and 1 every 20 time units and runs forever. always begin clk = l'bl; #20; clk = l'bO; #20; end An initial block also contains procedural statements inside. However, it is executed only once at the beginning of simulation. The simplified syntax is initial begin [procedural statements] end An initial block is frequently used to set the initial values of variables. In Listing 1.7, it is used to generate the entire testing sequence. The "run-once" behavior of an initial block usually cannot be synthesized. 7.5.2 Procedural statements Procedural statements are used within initial blocks, always blocks, functions, and tasks. Commonly used procedural statements are a Blocking assignment a Nonblocking assignment a If statement a Various case statements a Various loop statements We discuss the blocking and nonblocking assignments in Section 7.1 and the if and case statements in Sections 3.4 and 3.5. Verilog supports four loop constructs: for, while, repeat, and forever. The simplified syntax of the for loop is for ([initial-assignment]; [end-condition]; begin [procedural-statements;] end [step-assignment]) For example, we can clear the content of a 16-word register file: integer i; for (i=O; i<16; i=i+l) reg-file [il = 0 ; Note that the begin and end delimiters can be omitted if there is only one statement inside the body. The simplified syntax of the while loop is while ([end-condition]) begin [procedural-statements ;I end The statements in the loop body are repeated continuously until the condition specified by the [end-condition]expression is met. For example, the previous clearing register operation can also be done with a while loop: integer i; ... i=O; while (i(16) begin reg-file [i] = 0; i=i+1; end The simplified syntax of the repeat loop is repeat([number]) begin [procedural-statements ;I end The statements in the loop body are repeated a specific number of times, which is specified by [number].For example, the previous operation can also be done with a repeat loop: integer i; ... i=O; repeat (16) begin reg-file [i] = 0 ; i=i+1; end The simplified syntax of the forever loop is forever begin [procedural-statements ;I end The forever loop, as its name shows, repeats its body until the end of the simulation. The loop body usually contains certain timing control constructs and thus is suspended periodically. For example, the following segment is another way to describe a clock signal, which toggles its value every 10 time units and runs forever. initial begin clk = l'bO; forever # I 0 clk = -elk; end 7.5.3 Timing control In a testbench, we must specify the time that various signals are activated and deactivated or wait for certain events or conditions. There are three timing control constructs: Delay control: # [delay-time1 Event control: Q ( [eventl , [eventl , . . .1 Wait statement: wait ( ~boolean~expression1l In addition, a compiler directive, 'timescale, is also related to the timing specification. 7.5.4 Delay control Delay control is indicated by the # symbol, followed by the amount of the time unit to be delayed. It delays execution of a procedural statement by the amount specified. If the delay control is placed on the left-hand side, execution of the entire statement is delayed. For example, consider the segment + Assume that the current simulation time is t. The statements mean that a gets 0 at t 10 + and after another 5 time units (i.e., at t 15)the a I b expression is evaluated and the result is assigned to y. If the delay control is placed on the right-hand side, the expression is executed immedi- ately but the assignment to the left-hand-side variable is delayed. Consider the segment + + Again, a gets 0 at t 10. The a I b expression is evaluated immediately (i.e., at t 10) but + the result is assigned to y at t 15. Instead ofmodeling the propagation delay, we generally use the delay control to generate a stimulus in the testbench. The following format makes the code more intuitive: a = lJbO; #lo; a = 1 'bl; #5 a = 1' b O ; #20 // a gets 0 // the 0 value l a s t s // a changes to I // the 1 value l a s t s // a changes to 0 // the 0 value l a s t s 10 t i m e u n i t s 5 time units 20 time u n i t s 7.5.5 Event control Event control is indicated by the @ symbol, followed by the sensitivity list, which specified the desired events. The event control is similar to that used in an always block. An event is the occasion that a signal in the sensitivity list changes its value (i.e., a signal transition). The posedge and negedge keywords can be added to specify the desired transition edge (i.e., rising edge or falling edge). In a testbench, the execution is suspended until one of the specified events occurs. One common application of event control is to synchronize the stimulus generation with a clock signal. For example, the following segment activated the enable signal, en, for one clock cycle: localparam delta=l; ... Q(posedge clk) // wait f o r t h e r i s i n g edge o f c l k #delta; // wait for delta to avoid hold-time violation en = l'bl; // assert en to 1 Q(posedge clk) // wait for the next r i s i n g edge o f clk #delta; // wait for delta to avoid hold-time v i o l a t i o n en = l'bO; // deassert en to 0 Alternatively, we can also assert and deassert en at the falling edge of the clock signal: Q(negedge clk) // wait for the f a l l i n g edge of clk en = l'bl; // assert en to I Q(negedge clk) // wait for the next f a l l i n g edge o f clk en = l'bO; // deassert en to 0 7.5.6 Wait statement The wait statement waits for a specific condition. The simplified syntax is wait [boolean-expression] Execution of the subsequent statements is suspended until the condition specified by the [boolean-expression] term is evaluated to be true. For example, we can write code like wait (state==READ && men-ready==l 'bl) [statement-to-get-data] ; We can also use the wait statement to suspend the execution. For example, we can wait for a counter to reach 15 and then activate certain signals: wait (counter==4'bl111); // wait u n i t c o u n t e r i s 15 ... // continue The wait statement is somewhat similar to the event control. The latter waits for the transition edges of certain signals and the former waits for a specific condition and is sometimes known as level-sensitive. 7.5.7 Timescale directive Compiler directives are used to control the compiling and processing of Verilog code. They are preceded by the grave accent mark ( 0 ,which is usually located in the top-left comer of the keyboard. A timing-related directive is the 'timescale directive, whose syntax is 'timescale [time-unit] / [time-precision] The [time-unit] term specifies the unit of measurement for time and delays and the [time-precision] term specifies the "resolution" of simulation. For example, the directive 'timescale 10 ns / 1 ns indicates that he simulation unit is 10ns and the resolution is 1ns. When a delay is specified in the code, as in it indicates that the actual delay is 50 ns (i.e., 5 * 10 ns). The delay specification can be a fraction of a unit, as in which indicates that the actual delay is 51.2345ns. Since the precision is 1ns, the number is rounded to 5 1 ns in simulation. Finer precision can increase the accuracy of the simulation but may reduce the simulation speed. The number portion of the [time-unit] and [time-precision] terms can be 1, 10, or 100, and the time units can be s (second), ms (millisecond), us (microsecond), ns (nanosecond), ps (picosecond), or fs (femtosecond). 7.5.8 System functions and tasks Verilog has a set of predefined system functions and tasks. They perform system-related operations, such as simulation control and file access. Their names begin with a dollar sign ($). We examine several commonly used functions and tasks in this subsection. Data type conversion functions The $unsigned and $signed functions perform the conversion between the unsigned and signed data types. Their use is discussed in Section 7.3. Simulation time functions Simulation time functions return the current simulation time. The $time, Sstime, and $realtime functions return the time as a 64-bit integer, a 32-bit integer, and a real number, respectively. Simulation control tasks There are two simulation control tasks: $finish and $stop. The $finish task terminates the simulation and exits the simulation program. The $stop task suspends simulation. In ModelSim, it returns simulation to the interactive mode. In our development flow, we usually stay within the ModelSim environment to do further editing or to examine the waveform, and thus $stop is used in the code. Display tasks The development flow discussed in Section 2.4 resembles doing an experiment at a lab bench. The simulated result is shown in waveform format in ModelSim, which emulates a logic analyzer used at a lab bench. An alternative is to display the results in textual format. The four main display system tasks are $display, $write, $strobe, and $monitor. They have similar syntax and display the text during simulation. In ModelSim, the text is shown in the console panel. The format of $display is similar to the print function in the C language. Its simplified syntax is ADDITIONAL CONSTRUCTS FOR TESTBENCH DEVELOPMENT 199 . $ d i s p l a y ([format-string] , [argument], [argument], . . ) ; The Cf ormat-string1 term contains regular character and "escape sequences" to specify the format of the corresponding arguments. When the string is displayed, the values of the corresponding arguments are substituted into the string and shown in the designated format. For example, in the the statement $ d i s p l a y ("at %d; signal x = %bb",$ t i m e , x); %dand %bare escape sequences and specify that current simulation time and x are to be displayed in the decimal and binary formats, respectively. The rustling display looks like at 5 1 0 0 ; signal x = OO11OOO1 The commonly used escape sequences in our simulation include %d,%b,%o,%h,%c, %s, and %g,which are for decimal, binary, octal, hexadecimal, character, string, and real number, respectively. The $write task is almost identical to the $display task except that $write does not add a newline character in the end. The output of the display-related task continues from the current position. The newline character, \n, must be added to the string manually to create a line break. Verilog incorporates the concept of a time step to model the propagation delay, as discussed in Section 7.5.7. Many activities can take place within a time step. The $strobe task is similar to the $display task. Instead of being executed immediately, the $strobe task is executed at the end of the current simulation time step. It avoids mismatched data display due to the race condition. The $monitor task is a very versatile command. Whereas the $display, $write, or $strobe task displays the text once every time it is executed, the $monitor task displays text when an argument changes its value. The $monitor task provides a simple and flexible way to keep track of the simulation. For example, we can add the following segment to the testbench in Listing 1.7: initial begin $display ("time $monitor ("%d $time, end test-in0 %b test-in0 , test-in1 %b test-in1 , test-out "1 ; %b" , test-out) ; The textual simulation result is displayed in the control console panel: time 0 200 400 600 800 1000 1200 test-in1 00 00 11 10 00 I1 01 test-out 1 0 0 1 0 1 0 File I/O system functions and tasks Verilog provides a set of functions and tasks to access external data files. A file can be opened and closed by the $fopen and $fclose functions. The simplified syntax of using $fopen is [mcd-name] = $ f o p e n ( " [f ile-name1 " ) ; 200 SELECTED TOPICS OF VERILOG The $fopen function returns a 32-bit multichannel descriptor associated with the file. The descriptor can be thought of as a 32-bit flag, in which each bit represents a file (i.e., a channel). The LSB is resewed for the standard output (i.e., the console). When the function is called and the file is opened successfully, it returns a descriptor value with one bit asserted. For example, 0 . . .0010 is returned for the first opened file, 0 . . .0100 is returned for the second opened file, and so on. The function returns all 0's if the open operation fails. Once a file is opened, we can write data to the file with four modified display system tasks: Sfdisplay, Sfwrite, Sfstrobe, and $fmonitor. These tasks are similar to the original ones except that a multichannel descriptor is used as the first argument, as in A simple example segment is shown in Listing 7.13. Listing 7.13 File write example integer log-f i l e , both-f i l e ; localparam con-f ile=16 'h0000~0001; // console initial 5 begin log-f i l e = Sfopen ("my-log") ; i f ( l o g - f i l e ==O) Sdisplay("Fai1 t o open l o g f i l e " ) ; // write console both-file = log-file I con-file; lo // write to both console and log f i l e Sfdisplay (both-file ,"Simulation s t a r t e d " ) ; ... // write to log f i l e only IS Sfdisplay (log-f i l e , ...) ; // write to both console and log f i l e Sfdisplay (both-f i l e ,"Simulation ended") ; Sfclose (log-f i l e ) ; zo end Note that we can create a descriptor by performing a bitwise or operation over the multichannel descriptors, as for the b o t h f i l e variable. When b o t h f i l e is used, the text will be written to the console and the log file. There are two simple system tasks to retrieve data from an external file: $readmemb and Sreadmemh. These tasks assume that the external file stores the content of a memory array and reads the content into a variable. The Sreadmemb and Sreadmemh tasks further assume that the content is in the binary and hexadecimal formats, respectively. The simplified syntax is $readmemb(" [f ile-name] " ,[mem-variable]) ; $readmemhcu [f ile-name] " ,[mem-variable]) ; The following code segment illustrates the retrieval of an 8 - b y 4 memory array: r e g C3:01 v-mem [O: 71 ; ... $readmemb ( " v e c t o r . t x t " , v-mem) ; ADDITIONAL CONSTRUCTS FOR TESTBENCH DEVELOPMENT 201 The file should contain eight 4-bit binary data separated by white spaces. With the file operation functions and tasks, it is possible to use external files to specify the test patterns and to record the simulation result. Consider the testbench in Listing 1.7. We can modify it using file operations, as shown in Listing 7.14. Listing 7.14 Testbench based on file operation 'timescale 1 ns/lO ps module eq2-f i l e - t b ; // signal d e c l a r a t i o n 5 reg [1:0] t e s t - i n 0 , t e s t - i n l ; wire test-out ; integer log-f i l e , console-f i l e , out-f i l e ; r e g [ 3 : 01 v-mem CO: 71 ; integer i ; 10 // i n s t a n t i a t e the c i r c u i t under t e s t eq2-sop uut (.a(test-inO), .b(test-inl), .aeqb(test-out)); 15 initial begin // setup output f i l e log-f ile=$fopen ( "eqlog .t x t " ) ; if ( ! log-f i l e ) 20 $display ("Cannot open log f i l e " ) ; c o n s o l e - f i l e = 32'hOOOO-0001; out-f i l e = log-f i l e 1 console-f i l e ; // read t e s t vector 25 sreadmemb ( " v e c t o r . t x t " , v-mem) ; // t e s t generator i t e r a t i n g through 8 patterns for (i=O; i<8; i = i + l ) begin 30 { t e s t - i n 0 , t e s t - i n l ) = v-mem [ i l ; #200; end // stop simulation 35 $fclose (log-f i l e ) ; $stop ; end // text display 40 i n i t i a l begin $fdisplay (out-f i l e , " time test-in0 test-in1 test-out"); Sfdisplay (out-f i l e , " (a) (b (aeqb) "1; Sfmonitor (out-f i l e , "%10d %b %b %b", 45 $time, test-in0 , test-in1 , test-out) ; end 202 SELECTED TOPICS OF VERILOG endmodule The test patterns are specified in 4-bit binary format and are stored in the v e c t o r . t x t file. The content of the file is The file is read into the two-dimensional vAem variable. The test pattern generator uses a for loop to iterate through the eight patterns. The simulated result is written to the console and the log file, eqlog .t x t . The content of the log file is time test-out (aeqb) I 0 0 1 0 1 0 0 The log file is a regular text file and can be examined later by any text editor. 7.5.9 User-defined functions and tasks A comprehensive testbench can be lengthy and involved. One way to manage the complexity is to divide the code into smaller portions. The functions and tasks can help us to achieve this. We discuss Verilog functions in Section 7.4. A function takes input arguments and returns a single value. When called, a function is executed immediately and thus no timing control construct is allowed within the function. A task is more flexible and versatile. It can have input, output, and bidirectional arguments and can incorporate timing control constructs. Multiple values can be returned via the output and bidirectional arguments. As with a function, a task must be declared within a module. The basic syntax of a task is task [task-id] ([arg] ; begin [statements] ; end endtask The [argl term is the argument declaration. Its format is similar to the port declaration of a module except that the default data type is reg and the wire data type cannot be used. The example in Listing 7.15 shows the modeling of a 2-bit equality comparator using a task. Listing 7.15 Two-bit comparator using a task module eq2-task ( input wire [1:01 a , b , output reg aeqb 5 ); reg eO, e l ; always O* 10 b e g i n equ-tsk(2, a[Ol, b[01, eO); equ-tsk(2, all] , b[ll , e l ) ; a e q b = eO & e l ; end 15 // task definition task equ-tsk ( input integer delay, 20 input iO, i l , output eql ); begin # d e l a y e q l = ( - i ~& " i l ) I ( i O & i l ) ; 25 end endtask endmodule Note that the propagation delay of the operation is specified by #delay and its value is passed into the task via the delay argument. For comparison purposes, we rewrite the code using a function, as shown in Listing 7.16. Listing 7.16 Two-bit comparator using a function module eq2-f unction ( input wire [1:01 a , b , output reg aeqb 5 ); reg eO, e l ; always Q* 10 begin #2 eO = e q u - f n c (aC01 , b LO]) ; #2 e l = equ-fnc(aC11 , b Ell) ; a e q b = eO & e l ; end 15 // function definition function equ-fnc(input begin iO, i l l ; 204 SELECTED TOPICS OF VERILOG Figure 7.3 Block diagram of a comprehensive testbench. equ-fnc = (-iO & " i l ) I (iO & i l l ; 20 end endfunction endmodule Note that a hnction cannot incorporate timing control. To achieve the same effect, the delay must only be specified in the always block. 7.5.10 Example of a comprehensive testbench After learning additional language constructs, we can develop a more sophisticated testbench. Let us consider the testbench again for the universal binary counter in Listing 4.10. The conceptual block diagram of a new testbench is shown in Figure 7.3. There are three modules. In addition to the counter, the bin-gen module generates the testing vector and the monitor module monitors the input stimulus and the output responses. Test vector generator module Generating test vectors directly, as in Listing 4.12, is a lengthy and tedious process. A better alternative is to develop a set of abstract procedures that correspond to various operations. This makes the code better organized and easier to comprehend. An individual procedure can be done by a task. For example, in the preceding testbench, we can define a task to perform the counter's data load operation: task l o a d - d a t a ( i n p u t wire [N-1:OI d a t a - i n ) ; begin Q(negedge c l k ) ; // wait for f a i l i n g edge load = l ' b l ; d = data-in; Q (n e g e d g e c l k ) ; load = 1 'bO; end endtask In the task, load is asserted for one clock cycle between two falling edges and the data, data-in, is placed on d. Several other tasks are defined in a similar way: clr-counter-async: clear the counter asynchronously by generating a short r e s e t pulse. clr-counter-sync: clear the counter synchronously by activating the s y n - c l r signal for one clock cycle. count: enable the counter to count up or down for a certain number of cycles. i n i t i a l i z e : set up the initial values for simulation and generate a r e s e t pulse. With these procedures, we can generate the test vector in a more abstract way: initial begin initialize 0 ; count(l2, 1); // c o u n t up 12 c y c l e s count (6, 0); // count down 6 c y c l e s load-data (3' boll) ; // load 01I count (2, 1); // count up 2 cycles clr-counter-sync 0 ; // clear counter s y n c h r o n o u s l ~ ~ count ( 3 , 1); // count up 3 c y c l e s clr-counter-async 0 ; // clear counter asynchronously count ( 5 , 1); // count up 5 c y c l e s $stop ; // stop simulation end The complete code is shown in Listing 7.17. Listing 7.17 Test vector generator module bin-gen #(parameter N=8, T=20) ( output reg clk, reset, 5 output reg syn-clr, load, en, up, output reg [N-1:Ol d ); lo // clock // clock running forever always begin clk = l'bl; #(T/2) ; clk = 1 'bO; #(T/2) ; end // rest procedure initial begin initialize 0 ; count (12, 1) ; count (6, 0); load-data(3'bOll) ; // count up I2 cycles // count down 6 c y c l e s // count down 6 c y c l e s count (2, 1 ) ; / / count up 2 c y c l e s c l r - c o u n t e r - s y n c 0; count (3, 1) ; // count up 3 c y c l e s clr-counter-async 0 ; count (5, 1 ) ; // count up 3 c y c l e s $stop ; // stop simulation end 35 ........................................ // task definitions ........................................ // assert reset between clock edges .lo task clr-counter-async 0 ; begin Q(negedge c l k ) ; // wait for f a i l i n g edge reset = l'bl; #(T/4) ; // assert 4 / T 45 reset = l'bO; end endtask task initialize 0; 50 // s y s t e m i n i t i a l i z a t i o n begin up = 0; load = 0; syn-clr = 0; d = 3'bOOO; clr-counter-async0; end endtask // a s s e t s y n - c l r one clock cycle task clr-counter-sync 0 ; begin Q(negedge c l k ) ; // wait for f a i l i n g syn-clr = l ' b l ; // assert clear Q(negedge clk) ; syn-clr = l'bO; end endtask edge // load register task load-data( input wire [N-1:01 d a t a - i n ) ; begin @(negedge c l k ) ; // wait for f a i l i n g edge load = l'bl; d = data-in; Q (negedge clk) ; load = l'bO; end XU endtask // count up or down f o r C c y c l e s t a s k c o u n t ( i n p u t i n t e g e r C, i n p u t i n t e g e r UP-DOWN); begin 85 Q ( n e g e d g e clk); / / w a i t f o r f a i l i n g e d g e en = l'bl; i f (UP-DOWN==1) // count up i f up-down i s I up = l'bl; r e p e a t (C) @ ( n e g e d g e clk) ; 90 en = l'bO; up = l'bO; end endtask Monitor module The monitor module monitors and records the activities of the counter and verifies its operation. The complete code is shown in Listing 7.18. Listing 7.18 Monitor module bin-monitor # ( p a r a m e t e r N=3) ( input wire clk, reset, 5 input wire syn-clr, load, en, up, i n p u t w i r e [N-1:0] d , i n p u t wire max-tick, min-tick, i n p u t w i r e [N-1:0] q ); 10 r e g [N-1:O] q-old, d-old, gold; r e g syn-clr-old , en-old , load-old , up-old; r e g [39:01 err-msg; / / 5 - l e t t e r m e s s a g e 15 initial // head $ d i s p l a y ("time syn-clr/load/en/up q\n") ; a l w a y s Q ( p o s e d g e elk) begin 20 // - o l d : the value sampled at the previous clock edge syn-clr-old <= syn-clr ; en-old <= en; load-old <= load; up-old <= u p ; 25 q-Old <= q ; d-old <= d ; // calculate the desired "gold" value i f (syn-clr-old) 30 gold = 0 ; e l s e i f (load-old) gold = d-old; else if (en-old & up-old) gold = q-old + 1; else if (en-old & -up-old) gold = q-old - 1; e1se gold = q-old; // error message if (q==gold) err-msg = " " ; // r e s u l t passes else err-msg = "ERROR"; // r e s u l t f a i l s // % d i s p l a y( " % 5 d , % b % b % b % b% d % s ", $time, syn-clr , load, en, up, q, end err-rnsg); 50 e n d m o d u l e Since the counter is a synchronous sequential circuit, the monitor module focuses on the activities at the rising edge of the clock signal. The key is to check the correctness of the counter operation. Since the circuit under test is a simple counter, we can record the sampled input values and counter state from the previous sampling edge and determine the new counter state. For example, if the previous sampled value of syn-clr is 1, the counter is cleared and becomes 0 in the next rising edge of the clock. The main part of the code is an always block, which is activated at the rising edge of the clock. There are three segments. The first segment uses nonblocking statements to infer registers, which are designated with the -old suffix and store the values sampled from the previous sampling edge. The second segment uses these values to calculate the expected counter output, gold. The last segment compares the expected counter output with the actual output and displays the values of the sampled input signals and the counter output. If a mismatch occurs, an ERROR message will be generated. Note that in Verilog a character is treated as an 8-bit number and thus the five-character message, errmsg, is declared as reg [39:01. Top-levelmodule The code of the top-level testbench module is shown in Listing 7.19, which follows the block diagram in Figure 7.3. Listing 7.19 Top-level module of testbench 'timescale 1 ns/lO ps module bin-counter-tb3 0; 5 // declaration localparam T=20; // clock period wire c l k , r e s e t ; wire syn-clr , load, en, up; wire [2:01 d ; lo wire max-tick , rnin-tick; wire [2:01 q ; // uut i n s t a n t i a t i o n u n i v - b i n - c o u n t e r # ( . N (3)) uut I5 (.clk(cik), .reset(reset), .syn_clr(syn-clr), . load(1oad) , .en(en), .up(up), .d(d), .max-tick(max-tick), .min-tick(min-tick), .q(q)); // test vector. generator bin-gen # ( .N (3) , . T (20) ) gen-unit ( . clk(clk), .reset (reset), . syn-clr ( s ~ n - c l r )3 . load(load), . en(en), .up(up), .d(d)); // bin-monitor i n s t a n t i a t i o n bin-monitor # ( . N (3) man-unit (.cik(clk), .reset(reset), .syn-clr(sYn-clr), .load(load), .en(en), .up(up), .d(d), .max-tick(max-tick), .min-tick(min-tick), .q(q)); In addition to the waveform, the testbench also generates textual output on the console panel: time syn-clr/load/en/up q x ERROR 0 ERROR 0 1 2 3 4 5 6 7 0 1 2 3 4 4 3 2 1 0 7 6 6 3 3 4 5 5 210 SELECTED TOPICS OF VERILOG 0000 0011 0011 0011 0000 0000 0011 0011 0011 0011 0011 0 0 1 2 3 0 ERROR 0 1 2 3 4 There are three ERROR messages. The messages at times 0 and 20 occur during system initialization and are not real errors. The message at time 660 is due to the clr-counter-async() operation, which generates a short asynchronous pulse between the sampling edges of 640 and 660. Since the testbench monitors only synchronous activities, it misses the asynchronous reset and reports it as an error. 7.6 BIBLIOGRAPHIC NOTES VerilogHDL,Zndedition, by S. PalnitkarandStarter 's Guide to Verilog2001 by M. D. Ciletti covers Verilog's syntax and constructs. IEEE Standard Verilog Hardware Description Language, IEEE Std 1364-2001, gives the rules regarding adjustment of an expression with mixed signed and unsigned data types. Writing Testbenches: Functional Verijication of HDL Models, 2nd edition, by J. Bergeron, provides detailed discussion of testbench development. The article "Nonblocking Assignments in Verilog Synthesis, Coding Styles That Kill!" by C. E. Cummings gives guidelines for proper use of blocking and nonblocking assignments. 7.7 SUGGESTED EXPERIMENTS 7.7.1 Shift register with blocking and nonblocking assignments The codes shown in Listing 7.20 are three attempts to describe a shift register. Derive the inferred circuits by the three attempts and determine whether they infer a shift register. Listing 7.20 Code for Experiment 7.7.1 module expl ( input wire clk , input wire xO, yo, 20, 5 output reg x3, y3, 23 1; reg xl, x2, yl, y2, 21, 22; // attempt 1 10 always @(posedge clk) begin xl <= x o : x 2 <= x l ; x3 <= x2; IS end // attempt 2 always Q(posedge clk) begin ?O yl = yo; y2 = yl; y3 = y2; end zr // a t t e m p t 3 always Q(posedge clk) begin 21 = 20; 23 = 2 2 ; 10 22 = 21; end endmodule SUGGESTED EXPERIMENTS 211 7.7.2 Alternative coding style for BCD counter Rewrite the BCD counter in Listing 4.18 using the coding style discussed in Section 7.2. Resynthesize the circuit and verify its operation. 7.7.3 Alternative coding style for FIFO buffer Rewrite the FIFO buffer in Listing 4.20 using the coding style discussed in Section 7.2. Resynthesize the circuit and verify its operation. 7.7.4 Alternative coding style for Fibonacci circuit Repeat the Fibonacci circuit discussed in Section 6.3.1 using the coding style discussed in Section 7.2. 7.7.5 Dual-mode comparator A dual-mode comparator takes the two 8-bit data inputs, a and b, as unsigned or signed integers. A control signal, mode, indicates the desired mode. The circuit has one output, agtb,which is asserted when the interpreted value of a is greater than the interpreted value of b. 1. Assume that the signed data type is allowed. Design the circuit and derive the code. 2. Synthesize the circuit and verify its operation. 3. Assume that the signed data type is not allowed in the code. Repeat steps 1 and 2. 212 SELECTED TOPICS OF VERILOG 7.7.6 Enhanced binary counter monitor The monitor module in Section 7.5.10 is intended to monitor a synchronous system and only checks the activities at the rising edges of the clock signal. The asynchronous reset operation is reported as an error. Modify the monitor circuit to take the asynchronous operation into consideration. Recreate the testbench and perform simulation to verify its operation. 7.7.7 Testbench for FIFO buffer Follow the example in Section 7.5.10 to design a compressive testbench to verify operation of the FIFO buffer discussed in Section 4.5.3. The test vector generator module should generate various combinations of write and read operations and introduce the full and empty conditions. The monitor module should continuously watch data written into and retrieved from the buffer and check the correctness of the operations. PART II I10 MODULES This Page Intentionally Left Blank CHAPTER 8 UART 8.1 INTRODUCTION A universal asynchronous receiver and transmitter (UART) is a circuit that sends parallel data through a serial line. UARTs are frequently used in conjunction with the EIA (Electronic Industries Alliance) RS-232 standard, which specifies the electrical, mechanical, functional, and procedural characteristics of two data communication equipment. Because the voltage level defined in RS-232 is different from that of FPGA 110, a voltage converter chip is needed between a serial port and an FPGA's 110 pins. The S3 board has an RS-232 port with a standard nine-pin connector. The board contains the necessary voltage converter chip and configures the various RS-232's control signals to automatically generate acknowledgment for the PC's serial port. A standard straightthrough serial cable can be used to connect the S3 board and PC's serial port. The S3 board basically handles the RS-232 standard and we only need to concentrate on design of the UART circuit. A UART includes a transmitter and a receiver. The transmitter is essentially a special shift register that loads data in parallel and then shifts it out bit by bit at a specific rate. The receiver, on the other hand, shifts in data bit by bit and then reassembles the data. The serial line is 1 when it is idle. The transmission starts with a start bit, which is 0, followed by data bits and an optional parity bit, and ends with stop bits, which are 1 . The number of data bits can be 6, 7, or 8. The optional parity bit is used for error detection. For odd parity, it is set to 0 when the data bits have an odd number of I 's. For even parity, it is set to 0 when the data bits have an even number of 1's. The number of stop bits can be 1, 1.5, FPGA ProtoQping by Verilog Examples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. 216 UART stop bit Figure 8.1 Transmission of a byte. or 2. Transmission with 8 data bits, no parity, and 1 stop bit is shown in Figure 8.1. Note that the LSB of the data word is transmitted first. No clock information is conveyed through the serial line. Before the transmission starts, the transmitter and receiver must agree on a set of parameters in advance, which include the baud rate (i.e., number of bits per second), the number of data bits and stop bits, and use of the parity bit. The commonly used baud rates are 2400,4800, 9600, and 19,200 bauds. We illustrate the design of the receiving and transmitting subsystems in the following sections. The design is customized for a UART with a 19,200 baud rate, 8 data bits, 1 stop bit, and no parity bit. 8.2 UART RECEIVING SUBSYSTEM Since no clock information is conveyed from the transmitted signal, the receiver can retrieve the data bits only by using the predetermined parameters. We use an oversampling scheme to estimate the middle points of transmitted bits and then retrieve them at these points accordingly. 8.2.1 Oversampling procedure The most commonly used sampling rate is 16 times the baud rate, which means that each serial bit is sampled 16 times. Assume that the communication uses N data bits and M stop bits. The oversampling scheme works as follows: 1. Wait until the incoming signal becomes 0, the beginning of the start bit, and then start the sampling tick counter. 2. When the counter reaches 7, the incoming signal reaches the middle point of the start bit. Clear the counter to 0 and restart. 3. When the counter reaches 15, the incoming signal progresses for one bit and reaches the middle of the first data bit. Retrieve its value, shift it into a register, and restart the counter. 4. Repeat step 3 N-1 more times to retrieve the remaining data bits. 5. If the optional parity bit is used, repeat step 3 one time to obtain the parity bit. 6. Repeat step 3 hf more times to obtain the stop bits. The oversampling scheme basically performs the function of a clock signal. Instead of using the rising edge to indicate when the input signal is valid, it utilizes sampling ticks to estimate the middle point of each bit. While the receiver has no information about the exact &. onset time of the start bit, the estimation can be off by at most The subsequent data bit & retrievals are off by at most from the middle point as well. Because of the oversampling, the baud rate can be only a small fraction of the system clock rate, and thus this scheme is not appropriate for a high data rate. rx clk + tick baud rate generator 1 r I-, rx dout I- s-tick m-done-tick Ib 4 receiver circuit LI Figure 8.2 Conceptual block diagram of a UART receiving subsystem. The conceptual block diagram of a UART receiving subsystem is shown in Figure 8.2. It consists of three major components: a UART receiver: the circuit to obtain the data word via oversampling a Baud rate generator: the circuit to generate the sampling ticks a Interface circuit: the circuit that provides a buffer and status between the UART receiver and the system that uses the UART 8.2.2 Baud rate generator The baud rate generator generates a sampling signal whose frequency is exactly 16 times the UART's designated baud rate. To avoid creating a new clock domain and violating the synchronous design principle, the sampling signal should function as enable ticks rather than the clock signal to the UART receiver, as discussed in Section 4.3.2. For the 19,200 baud rate, the sampling rate has to be 307,200 (i.e., 19,200*16) ticks per second. Since the system clock rate is 50 MHz, the baud rate generator needs a mod-163 i:;::) (i.e., - counter, in which a one-clock-cycle tick is asserted once every 163 clock cycles. The parameterized mod-m counter discussed in Section 4.3.2 can be used for this purpose by setting the M parameter to 163. 8.2.3 UART receiver With an understanding of the oversampling procedure, we can derive the ASMD chart accordingly, as shown in Figure 8.3. To accommodate future modification, two constants are used in the description. The DBIT constant indicates the number of data bits, and the SB-TICK constant indicates the number of ticks needed for the stop bits, which is 16, 24, and 32 for 1, 1.5, and 2 stop bits, respectively. DBIT and SB-TICK are assigned to 8 and 16 in this design. The chart follows the steps discussed in Section 8.2.1 and includes three major states, s t a r t , d a t a , and s t o p , which represent the processing of the start bit, data bits, and stop bit. The s - t i c k signal is the enable tick from the baud rate generator and there are 16 ticks in a bit interval. Note that the FSMD stays in the same state unless the s - t i c k signal is asserted. There are two counters, represented by the s and n registers. The s register keeps track of the number of sampling ticks and counts to 7 in the s t a r t state, to 15 in the d a t a state, and to SB-TICK in the s t o p state. The n register keeps track of the number of data bits received in the d a t a state. The retrieved bits are shifted into and reassembled in the b Figure 8.3 ASMD chart of a UART receiver. register. A status signal, rx-done-tick,is included. It is asserted for one clock cycle after the receiving process is completed. The corresponding code is shown in Listing 8.1. Listing 8.1 module uart-rx #( parameter DBIT = 8 , SB-TICK = 16 5 1 ( input wire clk, r e s e t , input wire r x , s-tick, output reg rx-done-tick, 10 output wire [7:01 dout 1; UART receiver // # data bits // # t i c k s for stop bits // symbolic s t a t e declaration localparam [ I :01 IS idle = 2'b00, s t a r t = 2' b01, data = 2'b10, stop = 2'bll; zo // s i g n a l d e c l a r a t i o n r e g [ I : 01 s t a t e - r e g , s t a t e - n e x t ; reg [3:0] s-reg , s-next ; reg [2:0] n-reg , n-next ; reg [7:0] b-reg , b-next ; 2s / / bod,v // FSMD s t a t e & d a t a r e g i s t e r s a l w a y s Q (p o s e d g e c l k , p o s e d g e r e s e t ) if (reset) 30 begin s t a t e - r e g <= i d l e ; s - r e g <= 0 ; n - r e g <= 0 ; b - r e g <= 0 ; end else begin s t a t e - r e g <= s t a t e - n e x t ; s - r e g <= s - n e x t ; n - r e g <= n - n e x t ; b - r e g <= b - n e x t ; end // FSMD n e x t - s t a t e l o g i c 15 a l w a y s Q * begin state-next = state-reg ; rx-done-tick = l'bO; s-next = s-reg; 50 n-next = n-reg; b-next = b-reg; case (state-reg) idle : if (-rx) begin state-next = s t a r t ; s-next = 0; end start : if (s-tick) if (s_reg==7) begin state-next = data; s-next = 0; n-next = 0; end else s-next = s-reg + 1; data : if (s-tick) if (s_reg==15) begin s-next = 0; b - n e x t = ( r x , b - r e g [7: 11 1 ; if (n-reg==(DBIT-1)) state-next = stop ; else n-next = n-reg + 1; end else s-next = s-reg + 1; stop: if (s-tick) if (s-reg==(SB-TICK-1)) begin state-next = idle; rx-done-tick = l ' b l ; end else s-next = s-reg + 1; endcase end // output assign dout = b-reg; 95 endmodule 8.2.4 Interface circuit In a large system, a UART is usually a peripheral circuit for serial data transfer. The main system checks its status periodically to retrieve and process the received word. The UART RECEIVING SUBSYSTEM 221 receiver's interface circuit has two functions. First, it provides a mechanism to signal the availability of a new word and to prevent the received word from being retrieved multiple times. Second, it can provide buffer space between the receiver and the main system. There are three commonly used schemes: A flag FF A flag FF and a one-word buffer A FIFO buffer Note that the UART receiver asserts the rx-ready-tick signal one clock cycle after a data word is received. The first scheme uses aflag FF to keep track of whether a new data word is available. The FF has two input signals. One is set-f lag, which sets the flag FF to 1, and the other is clr-f lag, which clears the flag FF to 0. The rx-ready-tick signal is connected to the set-f l a g signal and sets the flag when a new data word arrives. The main system checks the output of the flag FF to see whether a new data word is available. It asserts the clr-f l a g signal one clock cycle after retrieving the word. The top-level block diagram is shown in Figure 8.4(a). To be consistent with other schemes, the flag FF's output is inverted to generate the final rx-empty signal, which indicates that no new word is available. In this scheme, the main system retrieves the data word directly from the shift register of the UART receiver and does not provide any additional buffer space. If the remote system initiates a new transmission before the main system consumes the old data word (i.e., the flag FF is still asserted), the old word will be overwritten, an error known as data overrun. To provide some cushion, a one-word buffer can be added, as shown in Figure 8.4(b). When the rx-ready-tick signal is asserted, the received word is loaded to the buffer and the flag FF is set as well. The receiver can continue the operation without destroying the content of the last received word. Data overrun will not occur as long as the main system retrieves the word before a new word arrives. The code for this scheme is shown in Listing 8.2. Listing 8.2 Interface with a flag FF and buffer module f lag-buf #(parameter W = 8) // # b u f f e r b i t s ( input wire c l k , r e s e t , 5 input wire clr-f l a g , set-f l a g , i n p u t w i r e [W-1:O] d i n , output wire f l a g , o u t p u t w i r e [W-1:Ol d o u t 1; 10 // signal d e c l a r a t i o n r e g [ W - 1 : 01 buf - r e g , buf - n e x t ; reg f lag-reg , f lag-next ; 1i // bod-v // FF & r e g i s t e r always @ (posedge clk , posedge reset) if (reset) 29 begin b u f - r e g <= 0 ; 4rx - clk -F tick baud rate generator > rx clk -F tick baud rate generator > rx clk --t tick baud rate generator > rx . - Idout rx-done-tick s-tick receiver > r-data lset-flag +clr-flag flag > flag FF rx-empty -rd-uart (a) F l a g F F - ~ r x dout rxdone-tick s-tick II receiver > . d 4 t en > register . r-data +-+ b set-flag +clr-flag flag rx-empty > flag FF rrd-uart - . (b) Flag F F and one-word buffer CTX dout . w-data rx-done-tick s-tick + wr t full . r-data rd 4 empty . r-data rd-uart rx-empty receiver > FIFO > (c) F I F O buffer Figure 8.4 Interface circuit of a UART receiving subsystem flag-reg <= l J b O ; end else 25 begin buf -reg <= buf -next ; flag-reg <= f lag-next ; end 30 // n e x t - s t a t e l o g i c always Q* begin buf-next = buf -reg; flag-next = flag-reg; 35 if (set-flag) begin buf-next = din; flag-next = l'bl; end JO e l s e i f (clr-flag) flag-next = l'bO; end // output logic assign dout = buf-reg; 45 a s s i g n flag = f l a g - r e g ; endmodule The third scheme uses a FIFO buffer discussed in Section 4.5.3. The FIFO buffer provides more buffering space and further reduces the chance of data overrun. We can adjust the desired number of words in FIFO to accommodate the processing need of the main system. The detailed block diagram is shown in Figure 8.4(c). The rx-ready-t i c k signal is connected to the w r signal of the FIFO. When a new data word is received, the w r signal is asserted one clock cycle and the corresponding data is written to the FIFO. The main system obtains the data from FIFO's read port. After retrieving a word, it asserts the r d signal of the FIFO one clock cycle to remove the corresponding item. The empty signal of the FIFO can be used to indicate whether any received data word is available. A data-overrun error occurs when a new data word arrives and the FIFO is full. 8.3 UART TRANSMITTING SUBSYSTEM The organization of a UART transmitting subsystem is similar to that of the receiving subsystem. It consists of a UART transmitter, baud rate generator, and interface circuit. The interface circuit is similar to that of the receiving subsystem except that the main system sets the flag FF or writes the FIFO buffer, and the UART transmitter clears the flag FF or reads the FIFO buffer. The UART transmitter is essentially a shift register that shifts out data bits at a specific rate. The rate can be controlled by one-clock-cycle enable ticks generated by the baud rate generator. Because no oversampling is involved, the frequency of the ticks is 16 times slower than that of the UART receiver. Instead of introducing a new counter, the UART transmitter usually shares the baud rate generator of the UART receiver and uses an internal counter to keep track of the number of enable ticks. A bit is shifted out every 16 enable ticks. The ASMD chart of the UART transmitter is similar to that of the UART receiver. After assertion of the t x - s t a r t signal, the FSMD loads the data word and then gradually progresses through the s t a r t , data, and s t o p states to shifi out the corresponding bits. It signals completion by asserting the tx-done-tick signal for one clock cycle. A 1-bit buffer, tx-reg, is used to filter out any potential glitch. The corresponding code is shown in Listing 8.3. Listing 8.3 UART transmitter module u a r t - t x #( parameter DBIT = 8 , SB-TICK = 16 > // # data bits // # ticks for ( input wire c l k , r e s e t , input wire t x - s t a r t , s - t i c k , input wire [7:01 d i n , output reg tx-done-tick , output wire t x 1; stop bits // synlbolic s t a t e declaration (5 localparam [1:01 idle = 2'b00, start = 2'b01, data = 2'b10, stop = 2'bll; ?o // signal declaration r e g [ I : 01 s t a t e - r e g , s t a t e - n e x t ; reg [3:0] s-reg , s-next; reg [2:0] n-reg, n-next; 2.; reg [7:01 b-reg , b-next; reg tx-reg , tx-next ; // bod?/ / / FSMD s t a t e & d a t a r e g i s t e r s o always Q(posedge clk, posedge reset) if (reset) begin s t a t e - r e g <= i d l e ; s - r e g <= 0 ; n - r e g <= 0 ; b - r e g <= 0 ; t x - r e g <= l ' b l ; end else begin s t a t e - r e g <= s t a t e - n e x t ; s - r e g <= s - n e x t ; n - r e g <= n - n e x t ; b - r e g <= b - n e x t ; t x - r e g <= t x - n e x t ; end // FSMD n e x t - s t a t e l o g i c & f u n c t i o n a l u n i t s always Q* so b e g i n state-next = state-reg; tx-done-tick = lJbO; s-next = s-reg; n-next = n-reg; b-next = b-reg; tx-next = tx-reg ; case (state-reg) idle : begin tx-next = l ' b l ; if (tx-start) begin state-next = start; s-next = 0; b-next = d i n ; end end start : begin tx-next = l'bO; if (s-tick) if (s_reg==15) begin state-next = data; s-next = 0; n-next = 0; end else s-next = s-reg + 1; end data: begin tx-next = b-reg [O] ; if (s-tick) if (s_reg==15) begin s-next = 0; b-next = b-reg >> 1 ; if (n-reg==(DBIT-1)) state-next = stop ; else n-next = n-reg + 1; end else s-next = s-reg + 1; Figure 8.5 Block diagram of a complete UART. end stop : begin tx-next = 1' b l ; if (s-tick) i f (s-reg==(SB-TICK -1)) begin state-next = idle; tx-done-tick = l ' b l ; end else s-next = s - r e g + 1; end endcase IIO end // output assign t x = tx-reg; endmodule 8.4 OVERALL UART SYSTEM 8.4.1 Complete UART core By combining the receiving and transmitting subsystems, we can construct the complete UART core. The top-level diagram is shown in Figure 8.5. The block diagram can be described by component instantiation, and the corresponding code is shown in Listing 8.4. Listing 8.4 UART top-level description module uart #( // Default s e t t i n g : // 1 9 , 2 0 0 baud, 8 data bits , I s t o p b i t , 2 ' 2 FIFO parameter DBIT = 8 , // # data bits SB-TICK = 1 6 , // # t i c k s f o r s t o p b i t s , // 16/24/32 for 1/1.5/2 bits DVSR = 163, / / baud r a t e d i v i s o r // DVSR = 5 0 M / ( 1 6 * baud r a t e ) DVSR-BIT = 8, // # b i t s o f DVSR IU FIFO-W = 2 // # addr b i t s o f FIFO // # words in FIFO=2"FIFO-W 1 ( i n p u t w i r e clk, reset , IS i n p u t w i r e rd-uart , wr-uart , rx, input wire [ 7 : 0 ] w-data, output wire tx-full, rx-empty, tx, output wire [7:01 r-data 1; 20 // signal declaration wire tick, rx-done-tick , tx-done-tick; wire tx-empty, tx-fifo-not-empty; w i r e [ 7 : 01 tx-f ifo-out , rx-data-out ; 25 //body mod-m-counter #(.M(DVSR), .N(DVSR-BIT)) baud-gen-unit ( . clk(c1k) , .reset(reset), . q O , .max-tick(tick)) ; uart-rx # ( . DBIT(DB1T) , . SB-TICK (SB-TICK)) uart-rx-unit ( . clk(clk), .reset (reset), .rx(rx), . s-tick(tick), .rx-done-tick(rx-done-tick), .dout(rx-data-out)); fifo #(.B(DBIT), .W(FIFO-W)) fifo-tx-unit (.clk(clk), .reset(reset), .rd(tx-done-tick), .wr(wr-uart), .w-data(w-data), .empty(tx-empty), .full(tx-full), .r-data(tx-fifo-out)); a s s i g n tx-f ifo-not-empty = -tx-empty; U endmodule Xilinx specific Figure 8.6 Block diagram of a UART verification circuit. In the picoBlaze source file (discussed in Chapter 15), Xilinx supplies a customized UART module with similar functionality. Unlike our implementation, the module is described using low-level Xilinx primitives. It can be considered as a gate-level description that utilizes Xilinx-specific components. Since the designer has the expert knowledge of Xilinx devices and takes advantage of its architecture, its implementation is more efficient than the generic RT-level device-independent description of this chapter. It is instructive to compare the code complexity and the circuit size of the two descriptions. 8.4.2 UART verification configuration Verification circuit We use a loop-back circuit and a PC to verify the UART's operation. The block diagram is shown in Figure 8.6. In the circuit, the serial port of the S3 board is connected to the serial port of a PC. When we send a character from the PC, the received data word is stored in the UART receiver's four-word FIFO buffer. When retrieved (via the r-data port), the data word is incremented by 1 and then sent back to the transmitter (via the w-data port). The debounced pushbutton switch produces a single one-clock-cycle tick when pressed and it is connected to the rd-uart and wr-uart signals. When the tick is generated, it removes one word from the receiver's FIFO and writes the incremented word to the transmitter's FIFO for transmission. For example, we can first type HAL in the PC and the three data words are stored in the FIFO buffer of the UART receiver. We can then push the button on the S3 board three times. The three successive characters, IBM, will be transmitted back and displayed. The UART's r-data port is also connected to the eight LEDs of the S3 board, and its t x - f u l l and rx-empty signals are connected to the two horizontal bars of the rightmost digit of the seven-segment display. The code is shown in Listing 8.5. Listing 8.5 UART verification circuit module u a r t - t e s t ( input wire clk, r e s e t , input wire rx, 5 input wire [2:0] btn, output wire t x , output wire [3:01 an, output wire [7:0] sseg, led 1; 10 // signal declaration wire tx-full, rx-empty , btn-tick; w i r e [7:01 rec-data , rec-data1 ; I5 // body // instantiate uart uart uart-unit ( . clk(clk1, .reset (reset), .rd-uart (btn-tick) , . wr-uart (btn-tick), .rx(rx), .w-data(rec-datai), .tx-full(tx-full), .rx-empty (rx-empty), .r-data(rec-data), .tx(tx)); // instantiate debounce circuit debounce btn-db-unit ( . elk( clk) , . reset (reset) , . sw (btn [Ol ) , 25 .db-level(), .db-tick(btn-tick)) ; // incrernented data loops back assign rec-data1 = rec-data + 1; / / LED d i s p l a y assign led = rec-data; 30 a s s i g n a n = 4 ' b l l i O ; a s s i g n sseg = {l'bl, -tx-full, 2'bll, -rx-empty, 3'blll); endmodule HyperTerminal of Windows On the PC side, Windows' HyperTerminal program can be used as a virtual terminal to interact with the S3 board. To be compatible with our customized UART, it has to be configured as 19,200 baud, 8 data bits, 1 stop bit, and no parity bit. The basic procedure is: 1. Select Start F Programs + Accessories + Communications + HyperTerminal. The HyperTerminal dialog appears. 2. Type a name for this connection, say fpga-192. Click OK. This connection can be saved and invoked later. 3. A Connect-to dialog appears. Press the Connecting Using field and select the desired serial port (e.g., COM1). Click OK. 4. The Port Setting dialog appears. Configure the port as follows: Bits per second: 19200 a Data bits: 8 Parity: None Stop bits: 1 a Flow control: None Click OK. + 5. Select File Properties F Setting. Click ASCII Setup and check the Echo typed characters locally box. Click OK twice. This will allow the typed characters to be shown on the screen. The HyperTerminal program is set up now and ready to communicate with the S3 board. We can type a few keys and observe the LEDs of the S3 board. Note that the received words are stored in the FIFO buffer and only the first received data word is displayed. After we press the pushbutton, the first data word will be removed from the FIFO and the incremented word will be looped back to the PC's serial port and displayed in the HyperTerminal window. The full and empty status of the respective FIFO buffers can be tested by consecutively receiving and transmitting more than four data words. ASCII code In HyperTerminal, characters are sent in ASCII code, which is 7 bits and consists of 128 code words, including regular alphabets, digits, punctuation symbols, and nonprintable control characters. The characters and their code words (in hexadecimal format) are shown in Table 8.1. The nonprintable characters are shown enclosed in parentheses, such as (del). Several nonprintable characters may introduce special action when received: (nul): null byte, which is the all-zero pattern (bel): generate a bell sound, if supported (bs): backspace (ht): horizontal tab (nl): new line (vt): vertical tab (np): new page (cr): carriage return (esc): escape (sp): space (del): delete, which is also the all-one pattern Since we use the PC's serial port to communicate with the S3 board in many experiments and projects, the following observations help us to manipulate and process the ASCII code: When the first hex digit in a code word is 016or 116,the corresponding character is a control character. When the first hex digit in a code word is 216 or 316, the corresponding character is a digit or punctuation. When the first hex digit in a code word is or 516, the corresponding character is generally an uppercase letter. When the first hex digit in a code word is 616 or 716,the corresponding character is generally a lowercase letter. If the first hex digit in a code word is 316,the lower hex digit represents the corresponding decimal digit. The upper- and lowercase letters differ in a single bit and can be converted to each other by adding or subtracting 2016or inverting the sixth bit. Note that the ASCII code uses only 7 bits, but a data word is normally composed of 8 bits (i.e., a byte). The PC uses an extended set in which the MSB is 1 and the characters are special graphics symbols. This code, however, is not part of the ASCII standard. 8.5 CUSTOMIZING A UART The UART discussed in previous sections is customized for a particular configuration. The design and code can easily be modified to accommodate other required features: Baud rate. The baud rate is controlled by the frequency of the sampling ticks of the baud rate generator. The frequency can be changed by revising the M parameter of the mod-m counter, which is represented as the DVSR constant in code. Number of data bits. The number of data bits can be changed by modifying the upper limit of the n-reg register, which is specified as the DBIT constant in code. Parity bit. A parity bit can be included by introducing a new state between the data and s t o p states in the ASMD chart in Figure 8.3. Code Char 00 (nul) 01 (soh) 02 (stx) 03 (etx) 04 (eot) 05 06 (ack) 07 (bel) 08 (bs) 09 (ht) Oa (nl) Ob (vt) Oc (np) Od (cr) Oe (so) Of (si) 10 (dle) 11 (dcl) 12 (dc2) 13 (dc3) 14 (dc4) 15 (nak) 16 (syn) 17 (etb) 18 (can) 19 (em) la (sub) lb (esc) lc (fs) Id (gs) l e (rs) If (us) Table 8.1 ASCII codes Code Char Code Char Code Char 60 61 a 62 b 63 c 64 d 65 e 66 f 67 g 68 h 69 i 6a j 6b k 6c 1 6d m 6e n 6f o 70 P 71 q 72 r 73 S 74 t 75 u 76 v 77 w 78 x 79 Y 7a z 7b { 7'2 I 7d 7e 1- 7f (del) Number of stop bits. The number of stop bits can be changed by modifying the upper limit of the s - r e g register in the s t o p state of the ASMD chart. The SB-TICK constant is used for this purpose. It can be 16,24, or 32, which is for 1, 1.5, or 2 stop bits, respectively. Error checking. Three types of errors can be detected in the UART receiving subsystem: - Parity error. If the parity bit is included, the receiver can check the correctness of the received parity bit. - Frame error. The receiver can check the received value in the s t o p state. If the value is not 1, a frame error occurs. - Buffer overrun error. This happens when the main system does not retrieve the received words in a timely manner. The UART receiver can check the value of the buffer's f lag-reg signal or FIFO's f u l l signal when the received word is ready to be stored (i.e., when the rx-done-tick signal is generated). Data overrun occurs if the f lag-reg or f u l l signal is still asserted. 8.6 BIBLIOGRAPHIC NOTES Although the RS-232 standard is very old, it still provides a simple and reliable low-speed communication link between two devices. The Wikipedia Web site has a good overview article and several useful links on the subject (search with the keyword RS232). Serial Port Complete by Jan Axelson provides information on interfacing hardware devices to a PC's serial port. 8.7 SUGGESTED EXPERIMENTS 8.7.1 Full-featured UART The alternative to the customized UART is to include all features in design and to dynamically configure the UART as needed. Consider a full-featured UART that uses additional input signals to specify the baud rate, type of parity bit, and the numbers of data bits and stop bits. The UART also includes an error signal. In addition to the I10 signals of the u a r t - t o p design in Listing 8.4, the following signals are required: b d - r a t e : 2-bit input signal specifying the baud rate, which can be 1200,2400,4800, or 9600 baud dnum: I-bit input signal specifying the number of data bits, which can be 7 or 8 snum: 1-bit input signal specifying the number of stop bits, which can be 1 or 2 p a r : 2-bit input signal specifying the desired parity scheme, which can be no parity, even parity, or odd parity e r r : 3-bit output signal in which the bits indicate the existence of the parity error, frame error, and data overrun error Derive this circuit as follows: 1. Modify the ASMD chart in Figure 8.3 to accommodate the required extensions. 2. Revise the UART receiver code according to the ASMD chart. 3. Revise the UART transmitter code to accommodate the required extensions. 4. Revise the top-level UART code and the verification circuit. Use the onboard switches for the additional input signals and three LEDs for the error signals. Synthesize the verification circuit. 5. Create different configurations in HyperTerrninal and verify operation of the UART circuit. 8.7.2 UART with an automatic baud rate detection circuit The most commonly used number of data bits of a serial connection is eight, which corresponds to a byte. When a regular ASCII code is used in communication (as we type in the HyperTerrninal window), only seven LSBs are used and the MSB is 0. If the UART is configured as 8 data bits, 1 stop bit, and no parity bit, the received word is in the form of 0-dddd-dddO-I,in which d is a data bit and can be 0 or 1. Assume that there is sufficient time between the first word and subsequent transmissions. We can determine the baud rate by measuring the time interval between the first 0 and last 0. Based on this observation, we can derive a UART with an automatic baud rate detection circuit. In this scheme, the transmitting system first sends an ASCII code for rate detection and then resumes normal operation afterward. The receiving subsystem uses the first word to determine a baud rate and then uses this rate for the baud rate generator for the remaining transmission. Assume that the UART configuration is 8 data bits, 1 stop bit, and no parity bit, and the baud rate can be 4800,9600, or 19,200 baud. The revised UART receiver should have two operation modes. It is initially in the "detection mode" and waits for the first word. After the word is received and the baud rate is determined, the receiver enters "normal mode" and the UART operates in a regular fashion. Derive the UART as follows: 1. Draw the ASMD chart for the automatic baud rate detector circuit. 2. Derive the VHDL code for the ASMD chart. Use three LEDs on the S3 board to indicate the baud rate of the incoming signal. 3. Modify the UART to include three different baud rates: 4800, 9600, and 19,200. This can be achieved by using a register for the divisor of the baud rate generator and loading the value according to the desired baud rate. 4. Create a top-level FSMD to keep track of the mode and to control and coordinate operation of the baud rate detection circuit and the regular UART receiver. Use a pushbutton switch on the S3 board to force the UART into the detection mode. 5. Revise the top-level UART code and the verification circuit. Synthesize the verification circuit. 6. Create different configurations in HyperTerrninal and verify operation of the UART. 8.7.3 UART with an automatic baud rate and parity detection circuit In addition to the baud rate, we assume that the parity scheme also needs to be determined automatically, which can be no parity, even parity, or odd parity. Expand the previous automatic baud rate detection circuit to detect the parity configuration and repeat Experiment 8.7.2. 8.7.4 UART-controlled stopwatch Consider the enhanced stopwatch in Experiment 4.7.6. Operation of the stopwatch is controlled by three switches on the S3 board. With the UART, we can use PC's HyperTerrninal to send commands to and retrieve time from the stopwatch: When a c or C (for "clear") ASCII code is received, the stopwatch aborts current counting, is cleared to zero, and sets the counting direction to "up." When a g or G (for "go") ASCII code is received, the stopwatch starts to count. When a p or P (for "pause") ASCII code is received, counting pauses. When a u or U (for "up-down") ASCII code is received, the stopwatch reverses the direction of counting. When a r or R (for "receive") ASCII code is received, the stopwatch transmits the current time to the PC. The time should be displayed as " DD .D ",where D is a decimal digit. All other codes will be ignored. Design the new stopwatch, synthesize the circuit, connect it to a PC, and use HyperTerminal to verify its operation. 8.7.5 UART-controlled rotating LED banner Consider the rotating LED banner circuit in Experiment 4.7.5. With the UART, we can use a PC's HyperTerminalto control its operation and dynamically modify the digits in the banner: When a g or G (for "go") ASCII code is received, the LED banner rotates. When a p or P (for "pause") ASCII code is received, the LED banner pauses. When a d or D (for "direction") ASCII code is received, the LED banner reverses the direction of rotation. When a decimal-digit (i.e., 0, 1, . .. , 9) ASCII code is received, the banner will be modified. The banner can be treated as a 10-word FIFO buffer. The new digit will be inserted at the beginning (i.e., the leftmost position) of the banner and the rightmost digit will be shifted out and discarded. All other codes will be ignored. Design the new rotating LED banner, synthesize the circuit, connect it to a PC, and use HyperTerminalto verify its operation. PS2 KEYBOARD 9.1 INTRODUCTION The PS2 port was introduced in IBM's Personal System/2 personnel computers. It is a widely supported interface for a keyboard and mouse to communicate with the host. The PS2 port contains two wires for communication purposes. One wire is for data, which is transmitted in a serial stream. The other wire is for the clock information, which specifies when the data is valid and can be retrieved. The information is transmitted as an 11-bit "packet" that contains a start bit, 8 data bits, an odd parity bit, and a stop bit. Whereas the basic format of the packet is identical for a keyboard and a mouse, the interpretation for the data bits is different. The FPGA prototyping board has a PS2 port and acts as a host. We discuss the keyboard interface in this chapter and cover the mouse interface in Chapter 10. The communication of the PS2 port is bidirectional and the host can send a command to the keyboard or mouse to set certain parameters. For our purposes, the bidirectional communication is hardly required for the PS2 keyboard, and thus our discussion is limited to one direction, from the keyboard to the prototyping board. Bidirectional design is examined in the mouse interface in Chapter 10. FPGA ProtoQping by Verilog Examples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. data (ps2d) clock (ps2c) ,/Fi:d bit > 8 , 8 8 , 8 < # , 8 8 , I I , I I 8 \ 8 Figure 9.1 Timing diagram of a PS2 port. 9.2 PS2 RECEIVING SUBSYSTEM 9.2.1 Physical interface of a PS2 port In addition to data and clock lines, the PS2 port includes connections for power (i.e., V,,) and ground. The power is supplied by the host. In the original PS2 port, Vcc is 5 V and the outputs of the data and clock lines are open-collector. However, most current keyboards and mice can work well with 3.3 V. For an older keyboard and mouse, the 5-V supply can be obtained by switching the 52 jumper on the S3 board. The FPGA should still function properly since its 110 pins can tolerate a 5-V input. 9.2.2 Device-to-host communication protocol A PS2 device and its host communicate via packets. The basic timing diagram of transmitting a packet from a PS2 device to a host is shown in Figure 9.1, in which the data and clock signals are labeled ps2d and ps2c, respectively. The data is transmitted in a serial stream, and its format is similar to that of a UART. Transmission begins with a start bit, followed by 8 data bits and an odd parity bit, and ends with a stop bit. Unlike a UART, the clock information is carried in a separate clock signal, ps2c. The falling edge of the ps2c signal indicates that the corresponding bit in the ps2d line is valid and can be retrieved. The clock period of the ps2c signal is between 60 and 100 ~ L(Si.e., 10 kHz to 16.7 kHz), and the ps2d signal is stable at least 5 ps before and after the falling edge of the ps2c signal. 9.2.3 Design and code The design of the PS2 port receiving subsystem is somewhat similar to that of a UART receiver. Instead of using the oversampling scheme, the falling edge of the ps2c signal is used as the reference point to retrieve data. The subsystem includes a falling-edge detection circuit, which generates a one-clock-cycle tick at the falling edge of the ps2c signal, and the receiver, which shifts in and assembles the serial bits. The edge detection circuit discussed in Section 5.3.1 can be used to detect the falling edge and generate an enable tick. However, because of the potential noise and slow transition, a simple filtering circuit is added to eliminate glitches. Its code is always @(posedge clk, posedge reset) f ilter-reg <= f ilter-next ; ... // I-bit s h i f t e r a s s i g n f ilter-next = {ps2c, f i l t e r - r e g [ 7 : 11 1 ; // " f i l t e r " a s s i g n f _ p s 2 c _ n e x t = (filter_reg==8' bllllllll) ? l'bl : (filter~reg==8'b00000000) ? 1'bO : f-ps2c-reg; The circuit is composed of an 8-bit shift register and returns a 1 or 0 when eight consecutive 1's or 0's are received. Any glitches shorter than eight clock cycles will be ignored (i.e., filtered out). The filtered output signal is then fed to the regular falling-edge detection circuit. The ASMD chart of the receiver is shown in Figure 9.2. The receiver is initially in the idle state. It includes an additional control signal, rx-en, which is used to enable or disable the receiving operation. The purpose of the signal is to coordinate the bidirectional operation. It can be set to 1 for the keyboard interface. After the first falling-edge tick and the rx-en signal are asserted, the FSMD shifts in the start bit and moves to the dps state. Since the received data is in fixed format, we shift in the remaining 10 bits in a single state rather than using separate data, parity, and s t o p states. The FSMD then moves to the load state, in which one extra clock cycle is provided to complete the shifting of the stop bit, and the psrx-done-tick signal is asserted for one clock cycle. The HDL code consists of the filtering circuit and an FSMD, which follows the ASMD chart. It is shown in Listing 9.1. Listing 9.1 PS2 port receiver module ps2-rx ( input wire clk, reset, input wire ps2d, ps2c, rx-en, 5 output reg rx-done-tick, output wire [7:0] dout ); // symbolic s t a t e declaration 10 l o c a l p a r a m [1:01 idle = 2 'b00, dps = 2'b01, load = 2'biO; IS // s i g n u l d e c l a r a t i o n r e g [I :01 state-reg , state-next ; reg [7:01 filter-reg; wire [7:01 f ilter-next ; reg f-ps2c_reg ; 20 w i r e f - p s 2 c _ n e x t ; reg [3:0] n-reg , n-next ; reg [10:0] b-reg, b-next; wire fall-edge ; // f i l t e r and f a l l i n g - e d g e t i c k generation for ps2c ................................................... Figure 9.2 ASMD chart of PS2 port receiver. a l w a y s @ ( p o s e d g e clk , p o s e d g e reset ) 30 i f (reset) begin filter-reg <= 0 ; f-ps2c-reg <= 0 ; end 35 else begin filter-reg <= filter-next ; f-ps2c-reg <= f-ps2c_next ; end 40 a s s i g n filter-next = (ps2c, f ilter-reg [7:11 1 ; a s s i g n f-ps2c-next = (filter-reg==8'bllll1111) ? l'bl : ( f i l t e r ~ r e g = = 8 ' b 0 0 0 0 0 0 0 0 ) ? l'bO : f-ps2c-reg; 43 a s s i g n fall-edge = f-ps2c_reg & "f-ps2c_next ; ................................................... / / FSMD ................................................... ru / / FSMD s t a t e & d a t a r e g i s t e r s a l w a y s Q ( p o s e d g e clk , p o s e d g e reset ) i f (reset) begin state-reg <= idle; n-reg <= 0 ; b-reg <= 0 ; end else begin state-reg <= state-next ; n-reg <= n-next; b-reg <= b-next; end / / FSMD n e x t - s t a t e l o g i c 63 always Q* begin state-next = state-reg; rx-done-tick = l'bO; n-next = n-reg; b-next = b-reg; c a s e (state-reg) idle : i f (fall-edge & rx-en) begin // s h i f t in s t a r t b i t b-next = (ps2d, b-reg [lo: 11 1 ; n-next = 4'b1001; state-next = dps; end dps: // 8 datu + I p a r i t y + I s t o p i f (fall-edge) begin b - n e x t = { p s 2 d , b - r e g [ I 0 : 11 1 ; if (n-reg==O) state-next = load; else n-next = n-reg - 1; end load: // I extra clock to complete the last s h i f t 90 begin state-next = idle; rx-done-tick = l ' b l ; end endcase 95 end // output assign dout = b _ r e g [ 8 : l l ; // data bits endmodule There is no error detection circuit in the description. A more robust design should check the correctness of the start, parity, and stop bits and include a watchdog timer to prevent the keyboard from being locked in an incorrect state. This is left as an experiment at the end of the chapter. 9.3 PS2 KEYBOARD SCAN CODE 9.3.1 Overview of the scan code A keyboard consists of a matrix of keys and an embedded microcontroller that monitors (i.e., scans) the activities of the keys and sends scan code accordingly. Three types of key activities are observed: a When a key is pressed, the make code of the key is transmitted. a When a key is held down continuously, a condition known as typematic, the make code is transmitted repeatedly at a specific rate. By default, a PS2 keyboard transmits the make code about every 100 ms after a key has been held down for 0.5 second. When a key is released, the break code of the key is transmitted. The make code of the main part of a PS2 keyboard is shown in Figure 9.3. It is normally 1 byte wide and represented by two hexadecimal numbers. For example, the make code of the A key is IC.This code can be conveyed by one packet when transmitted. The make codes of a handful of special-purpose keys, which are known as the extendedkeys, can have 2 to 4 bytes. A few of these keys are shown in Figure 9.3. For example, the make code of the upper arrow on the right is EO 75. Multiple packets are needed for the transmission. The break codes of the regular keys consist of FO followed by the make code of the key. For example, the break code of the A key is FO IC. The PS2 keyboard transmits a sequence of codes according to the key activities. For example, when we press and release the A key, the keyboard first transmits its make code and then the break code: [J~]~]~]~]E]~]8~]E] [T1~]~]~]~l~ [-]~]~]E]~]E]~]~]~ [F[Z]lEE] ][TI[TI[TIITI]T] [a] [TI [TI[ Space 29 ] [TI Figure 9.3 Scan code of the PS2 keyboard. (Courtesy of Xilinx, Inc. O Xilinx, Inc. 19942007. All rights reserved.) If we hold the key down for awhile before releasing it, the make code will be transmitted multiple times: Multiple keys can be pressed at the same time. For example, we can first press the s h i f t key (whose make code is 12) and then the A key, and release the A key and then release the s h i f t key. The transmitted code sequence follows the make and break codes of the two keys: The preceding sequence is how we normally obtain an uppercase A. Note that there is no special code to distinguish the lower- and uppercase keys. It is the responsibility of the host device to keep track of whether the shift key is pressed and to determine the case accordingly. 9.3.2 Scan code monitor circuit The scan code monitor circuit monitors the arrival of the received packets and displays the scan codes on a PC's HyperTerrninalwindow. The basic design approach is to first split the received scan code into two 4-bit parts and treat them as two hexadecimal digits, and then convert the two digits to ASCII code words and send the words to a PC via the UART. The received scan codes should be displayed similar to the previous example sequences. The program is shown in Listing 9.2. Listing 9.2 PS2 keyboard scan code monitor circuit module kb-monitor ( input wire clk, reset, input wire ps2d, ps2c, 5 output wire tx 1; // constant declaration localparam SP=8'h20; // s p a c e in ASCII // symbolic state l o c a l p a r a m C1: 01 idle = 2'b00, send1 = 2'b01, send0 = 2'b10, sendb = 2 ' b l l ; declaration // signal declaration r e g [ I :01 s t a t e - r e g , s t a t e - n e x t ; reg [7:0] w-data, ascii-code ; wire [7:0] scan-data; reg wr-uart; wire scan-done-tick; wire [3:01 hex-in; // instantiation ...................................................... // i n s t a n t i a l e ps2 r e c e i v e r ps2-rx ps2-rx-unit ( . cik (cik) , .reset (reset 1, .rx-en (1'b l ) , .ps2d (ps2d), .ps2c ( p s 2 c ) , .rx-done-tick(scan-done-tick), . d o u t ( s c a n - d a t a ) ) ; / / i n s t a n t i a t e UART uart uart-unit (. clk(cik), .reset (reset), .rd-uart (1'bo), .wr-uart (wr-uart) , .r x (1' b l ) , .w-data(w-data) . t x - f u i i ( ) , . r x - e m p t y 0 ,. r - d a t a O , . t x ( t x ) ) ; ...................................................... / / FSM t o s e n d 3 ASCII c h a r a c t e r s ...................................................... // s t a t e r e g i s t e r s always Q (posedge clk , posedge reset ) if (reset) s t a t e - r e g <= i d l e ; else s t a t e - r e g <= s t a t e - n e x t ; // next-state logic always Q* begin wr-uart = l'bO; w-data = SP; state-next = state-reg; case (state-reg) idle : if (scan-done-tick) // state-next = sendl; s e n d l : // send higher hex a scan char code received begin w-data = ascii-code ; wr-uart = 1 'bl; state-next = send0; end send0: // send lolver hex char begin w-data = ascii-code ; wr-uart = l'bl; state-next = sendb; end sendb: // send blank char begin w-data = SP; wr-uart = l'bl; state-next = idle; end 80 endcase end ...................................................... // scan code to ASCII display * ........................................................ // s p l i t the scan code into two 4-bit hex a s s i g n hex-in = (state-reg==sendl)? scan-data [7:4] : // hex d i g i t to ASClI code 90 a l w a y s @ * c a s e (hex-in) scan-data [3:01 ; 4'hO: ascii-code = 8'h30; 4'hl: ascii-code = 8'h31; 4'h2: ascii-code = 8'h32; 91 4'h3: ascii-code = 8'h33; 4'h4: ascii-code = 8'h34; 4'h5: ascii-code = 8'h35; 4'h6: ascii-code = 8jh36; 4'h7: ascii-code = 8'h37; 4'h8: ascii-code = 8'h38; 4'h9: ascii-code = 8'h39; 4'ha: ascii-code = 8'h41; 4'hb: ascii-code = 8'h42; 4'hc: ascii-code = 8'h43; 4'hd: ascii-code = 8'h44; 4'he: ascii-code = 8'h45; d e f a u l t : ascii-code = 8'h46; endcase IIO endmodule An FSM is used to control the overall operation. The UART operation is initiated when a new scan code is received (as indicated by the assertion of scan-done-tick).The FSM circulates through the sendl, send0, and sendb states, in which the ASCII codes of the upper hexadecimal digit, lower hexadecimal digit, and blank space are written to the UART. Figure 9.4 Block diagram of a last-releasedkey circuit. Recall that the UART has a FIFO of four words, and thus no overflow will occur. Note that the UART receiver is not used and the corresponding ports are mapped to constants or left blank. 9.4 PS2 KEYBOARD INTERFACE CIRCUIT As discussed in Section 9.3.1,a sequence ofpackets is transmitted even for simple keyboard activities. It will be quite involved if we want to cover all possible combinations. In this section, we assume that only one regular key is pressed and released at a time and design a circuit that returns the make code of this key. This design provides a simple way to send a character or digit to the prototyping board and should be satisfactory for our purposes. 9.4.1 Basic design and HDL code The keyboard circuit, as a UART, is a peripheral circuit of a large system and needs a mechanism to communicate with the main system. The flagging and buffering schemes discussed in Section 8.2.4can be applied for the keyboard circuit as well. We use a fourword FIFO buffer as the interface in this design. The top-level conceptual diagram is shown in Figure 9.4. It consists of the PS2 receiver, a FIFO buffer, and a control FSM. The basic idea is to use the FSM to keep track of the FO packet of the break code. After it is received, the next packet should be the make code of this key and is written into the FIFO buffer. Note that this scheme cannot be applied to the extended keys since their make codes involve multiple packets. The corresponding HDL code is shown in Listing 9.3. Listing 9.3 PS2 keyboard last-releasedkey circuit module kb-code # ( p a r a m e t e r W-SIZE = 2) / / 2-W-SIZE w o r d s in FIFO ( input wire clk , reset, 5 input wire ps2d, ps2c, rd-key-code , output wire [7:0] key-code , output wire kb-buf-empty 1; lo // c o n s t a n t d e c l a r a t i o n localparam BRK = 8'hfO; // break code // symbolic state declaration localparam wait-brk = l'bO, get-code = l'bl; // signal declaration r e g state-reg , state-next; w i r e [ 7 : 01 scan-out ; reg got-code-tick; wire scan-done-tick; // bodv ...................................................... // instantiation ........................................................ // i n s t a n t i a t e ps2 receiver ps2-rx ps2-rx-unit ( . clk(clk1, .reset(reset), . rx-en(l 'bl), .ps2d(ps2d), .ps2c(ps2c), .rx-done-tick(scan-done-tick), .dout(scan-out)); // i n s t a n t i a t e f i f o buffer fifo #(.B(8), .W(W-SIZE)) fife-key-unit (.clk(clk), .reset(reset), .rd(rd-key-code), .wr (got-code-tick) , . w-data(scan-out), . empty (kb-buf-empty), . full , .r-data(key-code)); ......................................................... / / FSM t o g e t t h e s c a n c o d e a f t e r FO r e c e i v e d ......................................................... // state registers a l w a y s Q ( p o s e d g e clk, p o s e d g e reset) i f (reset) state-reg <= wait-brk ; else state-reg <= state-next ; // next-state logic always Q* begin got-code-tick = l'bO; state-next = state-reg; c a s e (state-reg) wait-brk: / / w a i t f o r FO o f b r e a k c o d e i f (scan-done-tick==l 'b1 && scan-out==BRK) state-next = get-code ; get-code: // g e t t h e f o l l o w i n g scan code i f (scan-done-tick) begin got-code-tick =l'bl; state-next = wait-brk ; Figure 9.5 Block diagram of a keyboard verification circuit. 65 end endcase end endmodule The main part of the code is the FSM, which screens for the break code and coordinates the operation of two other modules. It checks the received packets in the wait-brk state continuously. When the FO packet is detected, it moves to the get-code state and waits for the next packet, which is the make code of the key. The FSM then asserts the code-done-tick signal for one clock cycle and returns to the wait-brk state. 9.4.2 Verification circuit We design a simple serial interface and decoding circuit to verify operation of the PS2 keyboard interface. The top-level block diagram is shown in Figure 9.5. The circuit converts a key's make code to the corresponding ASCII code and then sends the ASCII code to the UART. The corresponding character or digits can be displayed in the HyperTerminal window. The HDL code for the conversion circuit is shown in Listing 9.4. Listing 9.4 Keyboard make code to ASCII code module key2ascii ( input wire [7:0] output reg [7:0] 5 1; key-code , ascii-code always O* c a s e (key-c:ode) 8'h45: ascii-code 8'h16: ascii-code 8' hle : ascii-code 8'h26: ascii-code 8' h25 : ascii-code 8'h2e: ascii-code 8'h36: ascii-code 8'h3d: ascii-code 8'h3e: ascii-code = 8'h30; = 8'h31; = 8'h32; = 8'h33; = 8'h34; = 8'h35; = 8'h36; = 8'h37; = 8'h38; 8'h46: ascii-code = 8'h39; // 9 ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code ascii-code = 8'h60; ascii-code = 8'h2d; ascii-code = 8'h3d; ascii-code = 8'h5b; ascii-code = 8'h5d; ascii-code = 8'h5c; ascii-code = 8'h3b; ascii-code = 8'h27; ascii-code = 8'h2c; ascii-code = 8'h2e; ascii-code = 8'h2f; // ' // // = // [ // ] // \ // ; // ' // , // . // / 8'h29: ascii-code = 8'h20; // ( s p a c e ) 8'h5a: ascii-code = 8'hOd; // ( e n t e r , c r ) 8'h66: ascii-code = 8'h08; // ( b a c k s p a c e ) d e f a u l t : ascii-code = 8'h2a; // * endcase The complete code for the verification circuit follows the block diagram and is shown in Listing 9.5. Listing 9.5 Keyboard verification circuit module kb-test ( input wire clk, reset, input wire ps2d, ps2c, output wire tx 1; // signal declaration wire C7:OI key-code , ascii-code; lo wire kb-not-empty , kb-buf -empty; // bod)] // instantiate keyboard scan code c i r c u i t kb-code kb-code-unit 15 ( . clk(c1k) , .reset (reset), . ~ s 2 d ( p s 2 d ) , . ~ s 2 (cps2c), .rd-key-code(kb-not-empty), .key-code(key-code), .kb-buf-empty(kb-buf-empty)); // i n s t a n t i a t e UART 0 uart uart-unit (.clk(clk), .reset(reset), .rd-uart(l'bO), .wr-uart(kb-not-empty), .rx(13bl), .w-data(ascii-code), . t x - f u l l 0 ,. rx-empty 0 ,. r - d a t a o , .tx(tx)) ; zr / / i n s t a n t i a t e k e y - t o - a s c i i code c o n v e r s i o n c i r c u i t key2ascii k2a-unit (.key-code(key-code), .ascii~code(ascii~code)); assign kb-not-empty = -kb-buf -empty; 7U endmodule 9.5 BIBLIOGRAPHIC NOTES Three articles, "PSI2 MouseIKeyboard Protocol," "PSI2 Keyboard Interface," and "PSI2 Mouse Interface," by Adam Chapweske, provide detailed information on the PS2 keyboard and mouse interface. They can be found at the http://www.computer-engineering.org site. Rapid Prototyping of Digital Systems: Quartus@ II Edition by James 0. Hamblen et al. also contains a chapter on the PS2 port and the keyboard and mouse protocols. 9.6 SUGGESTED EXPERIMENTS 9.6.1 Alternative keyboard interface I The interface circuit in Section 9.4 returns the make code of the last released key and thus ignores the typematic condition. An alternative approach is to consider the typematic condition. The keyboard interface circuit should return a key's make code repeatedly when it is held down and ignore the final break code. For simplicity, we assume that the extended keys are not used. Design the new interface circuit, resynthesize the verification circuit, and verify operation of the new interface circuit. 9.6.2 Alternative keyboard interface II We can expand the interface circuit to distinguish whether the shift key is pressed so that both lower- and uppercase characters can be entered. The expanded circuit can be modified as follows: The keycode output should be extended from 8 bits to 9 bits. The extra bit indicates whether the shift key is held down. The FSM should add a special branch to process the make and break codes of the shift key and set the value of the corresponding bit accordingly. The width of the FIFO buffer should be extended to 9 bits. Design the expanded interface circuit, modify the k e y 2 a s c i i circuit to handle both lowerand uppercase characters, resynthesize the verification circuit, and verify operation of the expanded interface circuit. 9.6.3 PS2 receiving subsystem with watchdog timer There is no error-handling capability in the PS2 receiving subsystem in Section 9.2. The potential noise and glitches in the ps2c signal may cause the FSMD to be stuck in an incorrect state. One way to deal with this problem is to add a watchdog timer. The timer is initiated every time the f a l l - e d g e - t i c k signal is asserted in the g e t - b i t state. The time-out signal is asserted if no subsequently falling edge arrives in the next 20 ,us, and the FSMD returns to the i d l e state. Design the modified receiving subsystem, derive a testbench, and use simulation to verify its operation. 9.6.4 Keyboard-controlledstopwatch Consider the enhanced stopwatch in Experiment 4.7.6. Operation of the stopwatch is controlled by three switches on the prototyping board. We can use the keyboard to send commands to the stopwatch: When the C (for "clear") key is pressed, the stopwatch aborts the current counting, is cleared to zero, and sets the counting direction to "up." When the G (for "go") key is pressed, the stopwatch starts to count. When the P (for "pause") key is pressed, the counting pauses. When the U (for "up-down") key is pressed, the stopwatch reverses the direction of counting. All other keys will be ignored. Design the new stopwatch, synthesize the circuit, and verify its operation. 9.6.5 Keyboard-controlledrotating LED banner Consider the rotating LED banner circuit in Experiment 4.7.5. We can use a keyboard to control its operation and dynamically modify the digits in the banner: When the G (for "go") key is pressed, the LED banner rotates. When the P (for "pause") key is pressed, the LED banner pauses. When the D (for "direction") key is pressed, the LED banner reverses the direction of rotation. When a decimal digit (i.e., 0, 1, . . . , 9) key is pressed, the banner will be modified. The banner can be treated as a 10-word FIFO buffer. The new digit will be inserted at the beginning (i.e., the leftmost position) of the banner, and the rightmost digit will be shifted out and discarded. All other keys will be ignored. Design the new rotating LED banner, synthesize the circuit, and verify its operation. CHAPTER 10 PS2 MOUSE 10.1 INTRODUCTION A computer mouse is designed mainly to detect two-dimensional motion on a surface. Its internal circuit measures the relative distance of movement and checks the status of the buttons. For a mouse with a PS2 interface, this information is packed in three packets and sent to the host through the PS2 port. In the stream mode, a PS2 mouse sends the packets continuously in a predesignated sampling rate. Communication of the PS2 port is bidirectional and the host can send a command to the keyboard or mouse to set certain parameters. For our purposes, this hnctionality is hardly required for a keyboard, and thus the keyboard interface in Chapter 9 is limited to one direction, from the keyboard to the FPGA host. However, unlike the keyboard, a mouse is set to be in the nonstreaming mode after power-up and does not send any data. The host must first send a command to the mouse to initialize the mouse and enable the stream mode. Thus, bidirectional communication of the PS2 port is needed for the PS2 mouse interface, and we must design a transmitting subsystem (i.e., from FPGA board to mouse) for the PS2 interface. In this chapter, we provide a short overview of the PS2 mouse protocol, design a bidirectional PS interface, and derive a simple mouse interface. FPGA ProtoQping bj. VcrilogExamples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. Table 10.1 Mouse data packet format 10.2 PS2 MOUSE PROTOCOL 10.2.1 Basic operation A standard PS2 mouse reports the x-axis (righdleft) and y-axis (upldown) movement and the status of the left button, middle button, and right button. The amount of each movement is recorded in a mouse's internal counter. When the data is transmitted to the host, the counter is cleared to zero and restarts the counting. The content of the counter represents a 9-bit signed integer in which a positive number indicates the right or up movement, and a negative number indicates the left or down movement. The relationship between the physical distances is defined by the mouse's resolution parameter. The default value of resolution is four counts per millimeter. When a mouse moves continuously, the data is transmitted at a regular rate. The rate is defined by the mouse's sampling rate parameter. The default value of the sampling rate is 100 samples per second. If a mouse moves too fast, the amount of the movement during the sampling period may exceed the maximal range ofthe counter. The counter is set to the maximum magnitude in the appropriate direction. Two overflow bits are used to indicate the conditions. The mouse reports the movement and button activities in 3 bytes, which are embedded in three PS2 packets. The detailed format of the 3-byte data is shown in Table 10.1. It contains the following information: 28, . . . ,20: x-axis movement in 2's-complement format x, : x-axis movement overflow ys, .. . ,yo: y-axis movement in 2's-complement format y,: y-axis movement overflow 1 : left button status, which is 1 when the left button is pressed r: right button status, which is 1 when the right button is pressed m: optional middle button status, which is 1 when the middle button is pressed During transmission, the byte 1 packet is sent first and the byte 3 packet is sent last. 10.2.2 Basic initialization procedure The operation of a mouse is more complex than that of a keyboard. It has different operation modes. The most commonly used one is the stream mode, in which a mouse sends the movement data when it detects movement or button activity. Ifthe movement is continuous, the data is generated at the designated sample rate. During the operation, a host can send commands to a mouse to modify the default values of various parameters and set the operation mode, and a mouse may generate the status and send an acknowledgment. For our purposes, the default values are adequate, and the only task is to set the mouse to the stream mode. The basic interaction sequence between a PS2 mouse and the FPGA host consists of the following: ps2d (host) ps2d (mouse) ps2c (host) ps2c (mouse) ,- / / ----?---- idle /- start bit PS2 TRANSMllTlNG SUBSYSTEM 253 parity bit I ack bit 8 8 , 8 I ' , # , 8 8 I I I , , , , -----;---8--c-----c8 ----.I--8-.-;----.:, -----,-----t----<-.---*---8--;------8-- , ' I 8 8 , , 8 8 8 8 8 , I 8, 8 , : Figure 10.1 Host-to-device timing diagram of a PS2 port. I . At power-on, a mouse performs a power-on test internally. The mouse sends 1-byte data AA, which indicates that the test is passed, and then 1-byte data 00, which is the id of a standard PS2 mouse. 2. The FPGA host sends the command, F4, to enable the stream mode. The mouse will respond with FE to acknowledge acceptance of the command. 3. The mouse now enters the stream mode and sends normal data packets. If a mouse is plugged into the FPGA prototyping board in advance, it performs the poweron test when the power of the board is turned on and sends the AA 00 data immediately. The FPGA chip is not configured at this point and will not receive this data. Thus, we can usually ignore the power-on message in step 1. A minimal mouse interface circuit only needs to send the F4 command, check the FE acknowledge, and enter the normal operation mode to process the mouse's regular data packet. We can force the mouse to return to the initial state by sending the reset command: 1. The FPGA host sends the command, FF, to reset the mouse. The mouse will respond with FE to acknowledge acceptance of the command. 2. The mouse performs a power-on test internally and then sends AA 00. The stream mode will be disabled during the process. Newer mouses add more functionality, such as a scrolling wheel and additional buttons, and thus send more information. Additional bytes are appended to the original 3-byte data to accommodate these new features. 10.3 PS2 TRANSMITTING SUBSYSTEM 10.3.1 Host-to-PS2-devicecommunication protocol Host-to-PS2-device communication protocol involves bidirectional data exchange. The mouse's data and clock lines actually are open-collector circuits. For our design purposes, we treat them as tri-state lines. The basic timing diagram of transmitting a packet from a host to a PS2 device is shown in Figure 10.1, in which the data and clock signals are labeled ps2d and ps2c. For clarity, the diagram is split into two parts to show which activities are generated by the host (i.e., the FPGA chip) and which activities are generated by the device (i.e., mouse). The basic operation sequence is as follows: -- t, t, + + - tri-c ps2c-out tri-d - t ps2d-out U PS~ transmitting circuit > Figure 10.2 Tri-state buffers of the PS2 transmission subsystem. 1. The host forces the ps2c line to be 0 for at least 100 p s to inhibit any mouse activity. It can be considered that the host requests to send a packet. 2. The host forces the ps2d line to be 0 and disables the ps2c line (i.e., makes it high impedance). This step can be interpreted as the host sending a start bit. 3. The PS2 device now takes over the ps2c line and is responsible for future PS2 clock signal generation. After sensing the starting bit, the PS2 device generates a 1-to-0 transition. 4. Once detecting the transition, the host shifts out the least significant data bit over the ps2d line. It holds this value until the PS2 device generates a 1-to-0 transition in the ps2c line, which essentially acknowledges retrieval of the data bit. 5 . Repeat step 4 for the remaining 7 data bits and 1 parity bit. 6. After sending the parity bit, the host disables the ps2d line (i.e., makes it high im- pedance). The PS2 device now takes over the ps2d line and acknowledges completion of the transmission by asserting the ps2d line to 0. If desired, the host can check this value at the last 1-to-0 transition in the ps2c line to verify that the packet has been transmitted successfully. 10.3.2 Design and code Unlike the receiving subsystem, the ps2c and ps2d signals communicate in both directions. A tri-state buffer is needed for each signal. The tri-state interface is shown in Figure 10.2. The t r i - c and t r i - d signals are enable signals that control the tri-state buffers. When they are asserted, the corresponding ps2c-out and ps2d-out signals will be routed to the output ports. To design the transmitting subsystem, we can follow the sequence of the preceding protocol to create an ASMD chart, as shown in Figure 10.3. The FSMD is initially in the i d l e state. To start the transmission, the host asserts the wr-ps2 signal and places the data on the d i n bus. The FSMD loads din, along with the parity bit, par, to the s h i f t r e g register, loads the "1. . .I" to c r e g , and moves to the rts (for "request to send") state. In this state, the ps2c-out is set to 0 and the corresponding t r i - c is asserted to enable the corresponding tri-state buffer. The c r e g is used as a 13-bit counter to generate a 164-ps delay. The FSMD then moves to the s t a r t state, in which the PS2 clock line is disabled and the data line is set to 1. The PS2 device (i.e., mouse) now takes over and generates a default: ps2c-out = I ps2d-out = I tri-c = 0 tri-d = 0 I ! data 1 ,....................................... -- Figure 10.3 ASMD chart of the PS2 transmitting subsystem. clock signal over the ps2c line. After detecting the falling edge of the ps2c signal through the f all-edge signal, the FSMD goes to the d a t a state and shifts 8 data bits and 1 parity bit. The n register is used to keep track of the number of bits shifted. The FSMD then moves to the s t o p state, in which the data line is disabled. It returns to the i d l e state after sensing the last falling edge. The FSMD also includes a t x - i d l e signal to indicate whether a transmission is in progress. This signal can be used to coordinate operation between the receiving and transmitting subsystems. The code follows the ASMD chart and is shown in Listing 10.1. A filtering circuit similar to that of Section 9.2 is used to generate the f all-edge signal. Listing 10.1 PS2 port transmitter module ps2-tx ( input wire clk, reset, input wire wr-ps2, i i n p u t w i r e [7:01 din, inout wire ps2d, ps2c, output reg tx-idle, tx-done-tick 1; 10 // s.vrnbolic s t a t e d e c l a r a t i o n l o c a l p a r a m C2 :01 idle = 3'b000, rts = 3'b001, start = 3'b010, data = 3'b011, stop = 3'blOO; // signal declaration r e g [2 : 01 state-reg , state-next ; zo r e g [7:01 f ilter-reg; w i r e [7 :01 filter-next ; reg f-ps2c_reg; wire f-ps2c_next; r e g [3:01 n-reg, n-next ; r j r e g [8:01 b-reg , b-next ; r e g [12:01 c-reg, c-next; wire par, fall-edge ; reg ps2c_out, ps2d-out ; reg tri-c , tri-d; o;. // body ................................................... // f i l t e r and falling -edge t i c k generation for ps2c ................................................... a a l w a y s @ ( ~ ~ s e d cglek, p o s e d g e reset) i f (reset) begin filter-reg <= 0 ; f-ps2c-reg <= 0; 40 end else begin f i l t e r - r e g <= f i l t e r - n e x t ; f - p s 2 c _ r e g <= f - p s 2 c _ n e x t ; end a s s i g n f i l t e r - n e x t = C p s 2 c , f i l t e r - r e g [ 7 : 111 ; a s s i g n f _ p s 2 c _ n e x t = ( f i l t e r ~ r e g = = 8 ' b l l l l 1 1 1 1 )? l ' b l : (filter~reg==8'b00000000)? l'bO : SO f-ps2c-reg; assign fall-edge = f-ps2c-reg & "f-ps2c-next; ................................................... / / FSMD ................................................... / / FSMD s t a t e & d a t a r e g i s t e r s always Q (posedge clk , posedge reset 1 if (reset) begin s t a t e - r e g <= i d l e ; c - r e g <= 0 ; n - r e g <= 0 ; b - r e g <= 0 ; end else begin s t a t e - r e g <= s t a t e - n e x t ; c - r e g <= c - n e x t ; n - r e g <= n - n e x t ; b - r e g <= b - n e x t ; end // odd parity bit assign par = -(-din); 75 / / FSMD n e x t - s t a t e logic always Q* begin state-next = state-reg; c-next = c-reg; n-next = n-reg; b-next = b-reg; tx-done-tick = l'bO; ps2c-out = l ' b l ; ps2d-out = l ' b l ; t r i - c = 1'bO; tri-d = l'bO; tx-idle = l'bO; case (state-reg) idle : begin tx-idle = l'bl; if (wr-ps2) begin b-next = {par, din}; c-next = 1 3 ' h l f f f ; // 2-13-1 state-next = r t s ; end end r t s : // request to send begin p s 2 c - o u t = 1 ' bO ; tri-c = l'bl; c-next = c-reg - 1; if (c-reg==O) state-next = start; end s t a r t : // assert start bit begin ps2d-out = l'bO; tri-d = l'bl; if (f all-edge) begin n-next = 4'h8; state-next = data; end end d a t a : // 8 data + I parity begin ps2d-out = b-reg [Ol ; tri-d = l'bl; if (f all-edge) begin b - n e x t = { l ' bO , b - r e g [8 : 11 1 ; i f ( n - r e g == 0 ) state-next = stop; else n-next = n-reg - 1 ; end end s t o p : // assume f l o a t i n g high f o r ps2d if (fall-edge) begin State-next = idle; tx-done-tick = l ' b l ; end endcase end 140 // f r i - s t a t e b u f f e r s assign ps2c = ( t r i - c ) ? ps2c-out : l ' b z ; assign ps2d = ( t r i - d ) ? ps2d-out : l ' b z ; endmodule BIDIRECTIONAL PS2 INTERFACE 259 Figure 10.4 Top-level block diagram of a bidirectional PS2 interface. There is no error detection circuit in this code. A more robust design should check the correctness of the parity and acknowledgment bits and include a watchdog timer to prevent the mouse from being locked in an incorrect state. 10.4 BIDIRECTIONAL PS2 INTERFACE 10.4.1 Basic design and code We can combine the receiving and transmitting subsystems to form a bidirectional PS2 interface. The top-level diagram is shown in Figure 10.4. We use the tx-idle and rx-en signals to coordinate the transmitting and receiving operations. Priority is given to the transmitting operation. When the transmitting subsystem is in operation, the tx-idle signal is deasserted, which, in turn, disables the receiving subsystem. The receiving subsystem can process input only when the transmitting subsystem is idle. The corresponding HDL code is shown in Listing 10.2. Listing 10.2 Bidirectional PS2 interface module ps2-rxtx ( input wire clk , reset , input wire wr-ps2, 5 inout wire ps2d, ps2c, input wire [7:01 din, output wire rx-done-tick , tx-done-tick , output wire [7:0] dout 1; 10 // signal declaration wire tx-idle ; Figure 10.5 Block diagram of a mouse monitor circuit. // body ,c // i n s t a n t i a t e ps2 r e c e i v e r ps2-rx ps2-rx-unit (.clk(clk), .reset(reset), .rx-en(tx-idle), .ps2d (ps2d) , .ps2c (ps2c) , .rx-done-tick(rx-done-tick), .dout(dout)); ?o // i n s t a n t i a t e ps2 t r a n s m i t t e r ps2-tx ps2-tx-unit (.clk(clk), .reset(reset), .wr-ps2(wr-p~2), .din(din) , .ps2d(ps2d), .ps2c(ps2c), .tx-idle(tx-idle), .tx-done-tick(tx-done-tick)); 25 endmodule 10.4.2 Verification circuit We create a testing circuit to verify and monitor operation of the bidirectional interface. The block diagram is shown in Figure 10.5. A command is transmitted manually. We use the 8-bit switch to specify the data (i.e., the command from the host) and use a pushbutton to generate a one-clock-cycle tick to transmit the packet. The received packet data is first passed to the byte-to-ascii circuit, which converts the data into two ASCII characters plus a blank space. The characters are then transmitted via the UART and displayed in Windows HyperTerminal. The HDL code is shown in Listing 10.3. Listing 10.3 Bidirectional PS2 interface monitor circuit module ps2-monitor ( input wire clk, reset, i n p u t wire [7:01 sw, i n p u t wire [2:01 btn, inout wire ps2d, ps2c, output wire tx 1; lo // cor~stant declaration localparam SP=8'h20; // space in ASCII // synibolic state declaration l o c a l p a r a m [ I : 01 idle = 2'b00, send1 = 2'b01, send0 = 2'b10, sendb = 2 ' b l l ; 20 / / s i g n a l d e c l a r a t i o n r e g [ I : 01 s t a t e - r e g , s t a t e - n e x t ; wire [7:01 rx-data; reg [7:0] w-data, ascii-code; wire psrx-done-tick , wr-ps2 ; 25 reg wr-uart; wire [3:0] hex-in; // body ...................................................... 30 / / i n s t a n t i a t i o n ...................................................... // i n s t a n t i a t e ps2 t r a n s m i t t e r / r e c e i v e r ps2-rxtx ps2-rxtx-unit (. c i k ( c i k ) , . r e s e t ( r e s e t ) , .wr-ps2(wr-p~2), . . d i n ( s w ) , d o u t ( r x - d a t a ) , . p s 2 d ( p s 2 d ) . P S ~ C ( P ~9 ~ C ) . r x - d o n e - t i c k ( p s r x - d o n e - t i c k ) , . t x - d o n e - t i c k 0 ); / / i n s t a n t i a t e UART ( o n l y use t h e UART t r a n s m i t t e r ) uart uart-unit (. c l k ( c i k ) , . r e s e t ( r e s e t ) , .rd-uart (1'bo) .wr-uart (wr-uart) , .rx (1'b l ) , .w-data(w-data) 9 . t x - f ~ i l ( ) , .rx-empty 0 , . r - d a t a O , . t x ( t x ) ) ; // instantiate debounce circuit a debounce btn-db-unit (. c l k ( c l k ) , . r e s e t ( r e s e t ) , .sw(btn [O]), .db-level() , .db-tick (wr-ps2)) ; ...................................................... SO // FSM t o s e n d 3 ASCII c h a r a c t e r s ...................................................... // s t a t e r e g i s t e r s always Q(posedge clk , posedge reset if (reset) s t a t e - r e g <= i d l e ; else s t a t e - r e g <= s t a t e - n e x t ; // next-state logic 60 a l w a y s Q * begin wr-uart = l'bO; w-data = SP; state-next = state-reg; case (state-reg) idle : if (psrx-done-tick) // a scan code received state-next = sendl; sendl: // send h i g h e r hex char begin w-data = ascii-code ; wr-uart = l'bl; state-next = send0; end send0: // send l o w e r hex char begin w-data = ascii-code ; wr-uart = l'bl; state-next = sendb; end sendb: // send blank char begin w-data = SP; wr-uart = l'bl; state-next = idle; end endcase end ...................................................... // scan code to ASCII display ..................................................... // s p l i t the scan code into two 4-bit hex a s s i g n hex-in = (state-reg==sendl)? rx-data [7:4] : vs rx-data [3:01 ; // hex digit to ASCII code always a* c a s e (hex-in) 4'hO: ascii-code = 8'h30; 4'hl: ascii-code = 8'h31; 4'h2: ascii-code = 8'h32; 4'h3: ascii-code = 8'h33; 4'h4: ascii-code = 8'h34; 4'h5: ascii-code = 8'h35; 4'h6: ascii-code = 8'h36; 4'h7: ascii-code = 8'h37; 4'h8: ascii-code = 8'h38; 4'h9: ascii-code = 8'h39; 4'ha: ascii-code = 8'h41; 4'hb: ascii-code = 8'h42; 4'hc: ascii-code = 8'h43; 4'hd: ascii-code = 8'h44; 4'he: ascii-code = 8'h45; d e f a u l t : ascii-code = 8'h46; endcase endmodule If a mouse is connected to the PS2 circuit, we can first issue the FF command to reset the mouse and then issue the F4 command to enable the stream mode. Windows HyperTerminal will show the mouse's acknowledge packets and subsequent mouse movement packets. 10.5 PS2 MOUSE INTERFACE 10.5.1 Basic design The basic PS2 mouse interface creates another layer over the bidirectional PS2 circuit. Its two basic hnctions are to enable the stream mode and to reassemble the 3 data bytes. The output of the circuit consists of xm and ym, which are two 9-bit x- and y-axis movement signals; btm, which is the 3-bit button status signal; and m-done-tick, which is a oneclock-cycle status signal and is asserted when the assembled data is available. The HDL code is shown in Listing 10.4. It is implemented by an FSMD with seven states. The i n i t I, i n i t 2 , and i n i t 3 states are executed once after the r e s e t signal is asserted. In these states, the FSMD issues the F4 command, waits for completion of the transmission, and then waits for the acknowledgment packet. The mouse is in the stream mode now. The FSMD then obtains and assembles the next three packets in the packl, pack2, and pack3 states, and activates the m-done-tick signal in the done state. The FSMD circulates these four states afterward. Listing 10.4 Basic mouse interface circuit module mouse ( input wire clk, r e s e t , inout wire ps2d, ps2c, 5 o u t p u t w i r e [ 8 : 0 ] xm, ym, output wire [2:01 btnm, output reg m-done-tick 1; 10 // c o n s t a n t d e c l a r a t i o n localparam STRM=8'hf4; // stream command F4 // symbolic state declaration l o c a l p a r a m [2: 01 15 i n i t l = 3'b000, i n i t 2 = 3' b001, i n i t 3 = 3'b010, packl = 3 ' b011. pack2 = 3'b100, 20 pack3 = 3'b101, done = 3'b110; // signal declaration r e g [ 2 : 01 s t a t e - r e g , s t a t e - n e x t ; 25 wire [7:01 rx-data; reg wr-ps2; wire rx-done-tick , tx-done-tick ; reg [8:0] x-reg, y-reg, x-next, y-next; r e g [ 2 : 01 b t n - r e g , b t n - n e x t ; // body // instantiation ps2-rxtx ps2-unit 5 (.clk(clk), .reset(reset), .wr-ps2(wr-~s2), . d i n (STRM) , . d o u t ( r x - d a t a ) , . p s 2 d ( p s 2 d ) , . ~ s 2 (cp s 2 ~ 9) .rx-done-tick(rx-done-tick), .tx-done-tick(tx-done-tick)); 40 // body / / FSMD s t a t e and d a t a r e g i s t e r s always @ (posedge clk , posedge reset ) if (reset) begin s t a t e - r e g <= i n i t l ; x - r e g <= 0 ; y - r e g <= 0 ; b t n - r e g <= 0 ; end else begin s t a t e - r e g <= s t a t e - n e x t ; x - r e g <= x - n e x t ; y - r e g <= y - n e x t ; b t n - r e g <= b t n - n e x t ; end // FSMD n e x t - s t a t e l o g i c always Q* 60 begin state-next = state-reg; wr-ps2 = l'bO; m-done-tick = l'bO; x-next = x-reg; y-next = y-reg ; btn-next = btn-reg; case (state-reg) init1: begin wr-ps2 = 1' b l ; state-next = init2; end i n i t 2 : // wait for send t o complete if (tx-done-tick) state-next = init3; i n i t 3 : // wait for acknowledge packet if (rx-done-tick) state-next = packl; packl: // wait for 1st data packet if (rx-done-tick) begin state-next = pack2; y - n e x t [81 = r x - d a t a C51 ; x - n e x t [8] = r x - d a t a [41 ; b t n - n e x t = r x - d a t a [2 :01 ; end pack2: // wait for 2nd data packet if (rx-done-tick) begin state-next = pack3; x-next 17: 01 = r x - d a t a ; end packs: // wait for 3rd data packet if (rx-done-tick) begin state-next = done; y-next [ 7 : 01 = r x - d a t a ; end done : begin m-done-tick = l ' b l ; state-next = packl; end endcase 105 end // output a s s i g n xm = x - r e g ; a s s i g n ym = y - r e g ; assign btnm = b t n - r e g ; 110 endmodule This design provides only minimal functionalities. A more sophisticated circuit should have a robust method to initiate the stream mode and add an additional buffer, similar to that in Section 8.2.4, to interact better with the external system. 10.5.2 Testing circuit We use a simple testing circuit to demonstrate use of the PS2 interface. The circuit uses a mouse to control the eight discrete LEDs of the prototyping board. Only one of the eight LEDs is lit and the position ofthat LED follows the x-axis movement of the mouse. Pressing the left or right button places the lit LED to the leftmost or rightmost position. The HDL code is shown in Listing 10.5. It uses a 10-bit counter to keep track of the current x-axis position. The counter is updated when a new data item is available (i.e., when the m-done-t i c k signal is asserted). The counter is set to 0 or maximum when the left or right mouse button is pressed. Otherwise, it adds the amount of the signed-extended x-axis movement. A decoding circuit uses the three MSBs of the counter to activate one of the LEDs. Listing 10.5 Mouse-controlled LED circuit module mouse-led ( input wire clk, r e s e t , inout wire ps2d, ps2c, 5 o u t p u t r e g [7:0] led ); // signal declaration r e g [9:01 p-reg; l o w i r e C9:01 p-next ; w i r e [8:01 x m ; w i r e [2:0] btnm; wire m-done-tick; 15 // body // i n s t a n t i a t i o n mouse mouse-unit ( . clk(clk), . reset (reset), . ps2d(ps2d), . xm(xm), .y m 0 , .btnmcbtnm), .PS~C(P~~C) .m-done-tick(m-done-tick)); // counter a l w a y s @ ( p o s e d g e clk , p o s e d g e reset ) i f (reset) p-reg <= 0 ; else p-reg <= p-next; a s s i g n p-next = ("m-done-tick) ? p-reg : // no a c t i v i t y 30 (btnm C01) ? 10'bO : // l e f t b u t t o n (btnm [I]) ? lO'h3ff : // r i g h t b u t t o n p-reg + Cxm C81 , xml; // x movement always Q* c a s e (p-reg C9:71 3'bOOO: led = 8'b10000000; 3'bOOl: led = 8'b01000000; 3'bOlO: led = 8'b00100000; 3'b011: led = 8'b00010000; 3'blOO: led = 8'b00001000; 3'b101: led = 8'b00000100; 3'b110: led = 8'b00000010; d e f a u l t : led = 8'b00000001; endcase 45 endmodule 10.6 BIBLIOGRAPHIC NOTES The bibliographic information for this chapter is similar to that for Chapter 9. 10.7 SUGGESTED EXPERIMENTS The mouse is used mainly with a graphic video interface, which is discussed in Chapters 13 and 14. Many additional mouse-related experiments can be found in these chapters. SUGGESTED EXPERIMENTS 267 10.7.1 Keyboard control circuit A host can issue a command to set certain parameters for a PS2 keyboard as well. For example, we can control the three LEDs of the keyboard by sending ED OX. The X is a hexadecimal number with a format of "Osnc",where s, n, and c are I-bit values that control the Scroll, Num, and Caps Lock LEDs, respectively. We can incorporate this feature into the keyboard interface circuit of Section 9.4.1 and use a 3-bit switch to control the three keyboard LEDs. Design the expanded interface circuit, resynthesize the circuit, and verify its operation. 10.7.2 Enhanced mouse interface For the mouse interface discussed in Section 10.5, we can alter the design to manually enable or disable the steam mode. This can be done by using two pushbuttons of the FPGA prototyping board. One button issues the reset command, FF, which disables the stream mode during operation, and the other button issues the F4 command to enable the steam mode. Modify the original interface to incorporate this feature, and resynthesize the LED testing circuit to verify its operation. 10.7.3 Mouse-controlled seven-segment LED display We can use the mouse to enter four decimal digits on the four-digit seven-segment LED display. The circuit functions as follows: Only one of the four decimal points of the LED display is lit. The lit decimal point indicates the location of the selected digit. The location of the selected digit follows the x-axis movement of the mouse. The content of the select seven-segment LED display is a decimal digit (i.e., 0, .. . ,9) and changes with the y-axis movement of the mouse. Design and synthesize this circuit and verify its operation. This Page Intentionally Left Blank CHAPTER 11 EXTERNAL SRAM 11.1 INTRODUCTION Random access memory (RAM) is used for massive storage in a digital system since a RAM cell is much simpler than an FF cell. A commonly used type of RAM is the asynchronous static RAM (SRAM). Unlike a register, in which the data is sampled and stored at an edge of a clock signal, accessing data from an asynchronous SRAM is more complicated. A read or write operation requires that the data, address, and control signals be asserted in a specific order, and these signals must be stable for a certain amount of time during the operation. It is difficult for a synchronous system to access an SRAM directly. We usually use a memory controller as the interface, which takes commands from the main system synchronously and then generates properly timed signals to access the SRAM. The controller shields the main system from the detailed timing and makes the memory access appear like a synchronous operation. The performance of a memory controller is measured by the number of memory accesses that can be completed in a given period. While designing a simple memory controller is straightforward, achieving optimal performance involves many timing issues and is quite difficult. The S3 board has two 256K-by-16 asynchronous SRAM devices, which total 1M bytes. In this chapter, we demonstrate the construction of a memory controller for these devices. Sincethe timing characteristics of each RAM device are different, the controller is applicable only to this particular device. However, the same design principle can be used for similar FPGA Protoyping b>~VerilogExamples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. 270 EXTERNAL SRAM SRAM devices. The Xilinx Spartan-3 device also contains smaller embedded memory blocks. Use of this memory is discussed in Chapter 12. 11.2 SPECIFICATION OF THE IS61LV25616AL SRAM 11.2.1 Block diagram and 110 signals The S3 board has two IS61LV25616AL devices, which are 256K-by-16 SRAM manufactured by Integrated Silicon Solution, Inc. (ISSI). A simplified block diagram is shown in Figure 1l.l(a). This device has an 18-bit address bus, ad, a bidirectional 16-bit data bus, dio, and five control signals. The data bus is divided into upper and lower bytes, which can be accessed individually. The five control signals are: c e n (chip enable): disables or enables the chip wen (write enable): disables or enables the write operation o e n (output enable): disables or enables the output l b n (lower byte enable): disables or enables the lower byte of the data bus u b n (upper byte enable): disables or enables the upper byte of the data bus All these signals are active low and the n suffix is used to emphasize this property. The functional table is shown in Figure 1l.l(b). The c e n signal can be used to accommodate memory expansion, and the wen and o e n signals are used for write and read operations. The l b n and u b n signals are used to facilitate the byte-oriented configuration. In the remainder of the chapter, we illustrate the design and timing issues of a memory controller. For clarity, we use one SRAM device and access the SRAM in 16-bit word format. This means that the c e n , l b n , and u b n signals should always be activated (i.e., tied to 0). The simplified functional table is shown in Figure 11.1(c). 11.2.2 Timing parameters The timing characteristics of an asynchronous SRAM are quite complex and involve more than two dozen parameters. We concentrate on only a few key parameters that are relevant to our design. The simplified timing diagrams for two types of read operations are shown in Figure 1 1.2(a) and (b). The relevant timing parameters are: tRG: read cycle time, the minimal elapsed time between two read operations. It is about the same as tAAfor SRAM. tAA: address access time, the time required to obtain stable output data after an address change. t o H ~o:utput hold time, the time that the output data remains valid after the address changes. This should not be confused with the hold time of an edge-triggered FF, which is a constraint for the d input. tDOE: output enable access time, the time required to obtain valid data after o e n is activated. tHZOE: output enable to high-Z time, the time for the tri-state buffer to enter the high-impedance state after o e n is deactivated. tLZOE: output enable to low-Z time, the time for the tri-state buffer to leave the high-impedance state after o e n is activated. Note that even when the output is no longer in the high-impedance state, the data is still invalid. Values of these parameters for the IS6 1LV25616AL device are shown in Figure 11.2(c). SPECIFICATION OF THE IS61LV25616AL SRAM 271 / I 18 dio (upper) 4 / / dio (lower) 4 8, / 8 decoder1 multiplexer b 256K-by-16 cell array - tA oe-n control circuit (a) Block diagram Operation c e n w e n o e n l b n u b n d i o (lower) d i o (upper) disabled 1 Z Z 0 1 1 z z 0 1 1 z z read 0 1 0 0 1 data out Z 0 1 0 1 0 Z data out 0 1 0 0 0 data out data out write 00 0 0 0 0 0 1 1 0 0 0 data in Z data in Z data in data in (b) Functional table Operation w e n o e n d i o (16 bits) output disabled 1 1 read 16-bit word 1 0 write 16-bit word 0 Z data out data in (c) Simplified functional table Figure 11.1 Block diagram and functional table of the ISSI 256K-by-16 SRAM. 272 EXTERNAL SRAM parameter min max ~RC read cycle time 10 - tAA address access time - 10 ~OHA output hold time 2 - DOE output enable access time - 4 ~ H Z O E output enable to high-Z time - 4 ~LZOE output enable to low-Z time 0 - - -- - (c) Timlng parameters (In ns) Figure 11.2 Timing diagrams and parameters of a read operation. SPECIFICATIONOF THE IS61LV25616AL SRAM 273 - I -din+ - (a) Timing diagram of a write cycle parameter min max twc ~SA HA ~PWEI ~SD ~HD write cycle time 10 - address setup time 0 - address hold time 0 - w e n pulse width 8 - data setup time 6 - data hold time 0 - (b) Timing parameter (in ns) Figure 11.3 Timing diagram and parameters of a write operation. The simplified timing diagram for a wen-controlled write operation is shown in Figure 11.3(a). The relevant timing parameters are: twc: write cycle time, the minimal elapsed time between two write operations. tSA: address setup time, the minimal time that the address must be stable before w e n is activated. tHA: address hold time, the minimal time that the address must be stable after w e n is deactivated. tPWE1: w e n pulse width, the minimal time that w e n must be asserted. tso: data setup time, the minimal time that data must be stable before the latching edge (the edge in which w e n moves from 0 to 1). tHD: data hold time, the minimal time that data must be stable after the latching edge. The values of these parameters for the IS6 1LV25616AL device are shown in Figure 11.3(b). The complete timing information can be found in the data sheet of the IS61LV25616AL device. FPGA I_______________---------- I I I I . P addr data-m2f I I I dataJ2m-ur I I I main system memory controller I I I clk -p I I Figure 11.4 Role of an SRAM memory controller. 11.3 BASIC MEMORY CONTROLLER 11.3.1 Block diagram The role of a memory controller and its 110 signals are shown in Figure 11.4. The signals to the SRAM side are discussed in Section 11.2.1. The signals to the main system side are: mem: is asserted to 1 to initiate a memory operation. rw: specifies whether the operation is a read (1) or write (0) operation. addr: is the 18-bit address. data-f 2s: is the 16-bit data to be written to the SRAM (the -f2s suffix stands for FPGA to SRAM). data-s2f 1:is the 16-bit registered data retrieved from the SRAM (the -s2f suffix stands for SRAM to FPGA). data-s2f -ur: is the 16-bit unregistered data retrieved from SRAM. ready: is a status signal indicating whether the controller is ready to accept a new command. This signal is needed since a memory operation may take more than one clock cycle. The memory controller basically provides a "synchronous wrap" around the SRAM. When the main system wants to access the memory, it places the address and data (for a write operation) on the bus and activates the command (i.e., the mem and r w signals). At the rising edge of the clock, all signals are sampled by the memory controller and the desired operation is performed accordingly. For a read operation, the data becomes available after one or two clock cycles. The block diagram of a memory controller is shown in Figure 11.5. Its data path contains one address register, which stores the address, and two data registers, which store the data from each direction. Since the data bus, dio, is a bidirectional signal, a tri-state buffer is needed. The control path is an FSM, which follows the timing diagrams and specifications in Figures 11.2 and 11.3 to generate a proper control sequence. addr data-f2s data-s2f-ur data-s2f-r raddr -Cl q . en ad > + + rcs -d q en > rs21 din w-b dio 4-h dout + a) + - q d en < + - rnern wr - tri-n FSM we-n > oe-n I ready I Figure 11.5 Block diagram of a memory controller. 11.3.2 Timing requirement Although the timing diagrams appear to be complicated at first glance, the control sequences are fairly simple. Let us first consider a read cycle. The w e n should be deactivated during the entire operation. Its basic operation sequence is: 1. Place the address on the a d bus and activate the o e n signal. These two signals must be stable for the entire operation. 2. Wait for at least t A A .The data from the SRAM becomes available after this interval. 3. Retrieve the data from d i o and deactivate the o e n signal. We use the wen-controlled write cycle in our design, as shown in Figure 11.3(a). The basic operation sequence is: 1. Place the address on the a d bus and data on the d i o bus and activate the w e n signal. These signals must be stable for the entire operation. 2. Wait for at least t P W E 1 . 3. Deactivate the w e n signal. The data is latched to the SRAM at the 0-to-1 transition edge. 4. Remove the data from the d i o bus. Note that t H D(data hold time after write ends) is 0 ns for this SRAM, which implies that it is theoretically possible to remove the data and deactivate w e n simultaneously. However, because of the variations in propagation delays, this condition cannot be guaranteed in a 276 EXTERNAL SRAM real circuit. To achieve proper latching, we need to ensure that the wen signal is always deactivated first. 11.3.3 Register file versus SRAM We discuss the design of a register file in Section 4.2.3. Its basic storage elements are D FFs and thus it is completely synchronous. Although a memory controller wraps the SRAM in a synchronous interface, there are several differences: A register file usually has one write port and multiple read ports. The read and write ports of a register file can be accessed at the same time (i.e., the read and write operations can be done at the same time). Writing to a register takes only one clock cycle. Data from a register's read ports is always available and the read operation involves no clock or additional control signals. In summary, a register file is faster and more flexible. However, due to the circuit size of an FF, a register file is feasible only for small storage. 11.4 A SAFE DESIGN With the block diagram of Figure 1 1.5, the remaining task is to derive the controller. Our first scheme uses a "safe" design, which means that the design provides large timing margins and does not impose any stringent timing constraints. The control signals are generated directly from the FSM. The controller uses two clock cycles (i.e., 40 ns) to complete memory access and requires three clock cycles (i.e., 60 ns) for back-to-back operations. 11.4.1 ASMD chart The ASMD chart for this controller is shown in Figure 11.6. The FSM has five states and is initially in the i d l e state. It starts the memory operation when the mem signal is activated. The r w signal determines whether it is a read or write operation. For a read operation, the FSM moves to the r d l state. The memory address, addr, is sampled and stored in the a d d r r e g register at the transition. The o e n signal is activated in the r d l and rd2 states. At the end of the read cycle, the FSM returns to the i d l e state. The retrieved data is stored in the data-s2f r e g register at the transition, and the o e n signal is deactivated afterward. Note that the block diagram of Figure 11.5 has two read ports. The data-s2f -r signal is a registered output and becomes available ajer the FSM exits the r 2 state. The data remains unchanged until the end of the next read cycle. The data-s2f -ur signal is connected directly to the SRAM's d i o bus. Its data should become valid at the end of the rd2 state but will be removed after the FSM enters the i d l e state. In some applications, the main system samples and stores the memory readout in its own register, and the unregistered output allows this action to be completed one clock cycle earlier. For a write operation, the FSM moves to the w r l state. The memory address, addr, and data, data-f 2s, are sampled and stored in the a d d r r e g and data-f 2s-reg registers at the transition. The wen and t r i n signals are both activated in the w r l state. The latter enables the tri-state buffer to put the data over the SRAM's d i o bus. When the FSM moves to the wr2 state, wen is deactivated but t r i n remains asserted. This ensures that the data is properly latched to the SRAM when wen changes from 0 to 1. At the end of the write Default: oe-n = 1; we-n = 1; tri-n = 1; ready = 0 ................................................................ ......................... 4 , ......................... wl T 1 we-n = 0 / tri-n = 0 I oe-n = 0 / rs2ft dio / tri-n = 0 Figure 11.6 ASMD chart of a safe SRAM controller. cycle, the FSM returns to the i d l e state and t r i n is deactivated to remove data from the d i o bus. 11.4.2 Timing analysis To ensure correct operation of a memory controller, we must verify that the design meets various timing requirements. Recall that the FSM is controlled by a 50-MHz clock signal and thus stays in each state for 20 ns. During the read cycle, o e n is asserted for two states, totaling 40 ns, which provides a 30-ns margin over the 10-ns ~ A A .Although it appears that o e n can be deasserted in the rd2 state, this imposes a more stringent timing constraint. This issue is explained in Section 11S.3. The data is stored in the data-s2f register when the FSM moves from the rd2 state to the i d l e state. Although o e n is deasserted at the transition, the data remains valid for a small interval because of the FPGA's pad delay and the t H Z o Edelay of the SRAM chip. It can be sampled properly by the clock edge. During the write cycle, w e n is asserted in the w r l state, and the 20-ns interval exceeds the 8-ns t P W E rIequirement. The t r i n signal remains asserted in the wr2 state and thus ensures that the data is still stable during the 0-to-1 transition edge of the w e n signal. 278 EXTERNAL SRAM In terms of performance, both read and write operations take two clock cycles to complete. During the read operation, the unregistered data (i.e., data-s2f -ur) is available at the end of the second clock cycle (i.e., just before the rising edge of the second clock cycle) and the registered data (i.e., data-s2f -r)is available right after the rising edge of the second clock cycle. Although a memory operation can be done in two clocks, the main system cannot access memory at this rate. Both read and write operations must return to the i d l e state after completion. The main system must wait for another clock cycle to issue a new memory operation, and thus the back-to-back memory access takes three clock cycles. 11.4.3 HDL implementation The HDL code can be derived by following the block diagram in Figure 11.5 and the ASMD chart in Figure 11.6. The memory controller must generate fast, glitch-free control signals. One method is to modify the output logic to include look-ahead output buffers for the Moore output signals. This scheme adds a buffer (i.e., D FF) for each output signal to remove glitches and reduce clock-to-output delay. To compensate the one clock cycle delay introduced by the buffer, we "look ahead" at the state's future value (i.e., the s t a t e n e x t signal) and use it to replace the state's current value (i.e., the s t a t e r e g signal) in the FSM's output logic. The complete HDL code is shown in Listing 11.l. To facilitate future expansion, we label the S3 board's two SRAM chips as a and b and add an -a suffix to the SRAM's 110 signals in port declaration. Note that tri-state buffers are required for the bidirectional data signal dio-a. Listing 11.1 SRAM controller with three-cycleback-to-back operation module sram-ctrl ( input wire clk, r e s e t , // t o / f r o m main system i i n p u t w i r e mem, r w , input wire [17:0] addr, input wire [15:0] data-f2s, output reg ready, output wire [15:0] data-s2f -r , data-s2f -ur , 10 // to/from sram chip output wire [17:0] ad, output wire we-n, oe-n, // sram chip a inout wire [15:0] dio-a, IS output wire ce-a-n, ub-a-n, lb-a-n 1; // symbolic s t a t e declaration localparam [2:01 20 idle = 3'b000, rdl = 3'b001, rd2 = 3'b010, w r l = 3'b011, wr2 = 3'blOO; 25 // signal declaration reg [2:01 state-reg , state-next ; r e g C15: 01 d a t a - f 2 s _ r e g , d a t a - f 2 s - n e x t ; r e g [15: 01 d a t a - s 2 f - r e g , d a t a - s 2 f - n e x t ; 30 r e g [ I 7 :01 a d d r - r e g , a d d r - n e x t ; r e g we-buf , oe-buf , t r i - b u f ; reg we-reg , oe-reg , t r i - r e g ; // body ss / / FSMD s t a t e & d a t a r e g i s t e r s always Q(posedge clk , posedge reset if (reset) begin s t a t e - r e g <= i d l e ; a d d r - r e g <= 0 ; d a t a - f 2 s - r e g <= 0 ; d a t a - s 2 f - r e g <= 0 ; t r i - r e g <= l ' b l ; we-reg <= l ' b l ; o e - r e g <= 1 ' b l ; end else begin s t a t e - r e g <= s t a t e - n e x t ; a d d r - r e g <= addr-next ; d a t a - f 2 s - r e g <= d a t a - f 2s-next ; d a t a - s 2 f - r e g <= d a t a - s 2 f - n e x t ; t r i - r e g <= t r i - b u f ; we-reg <= we-buf; o e - r e g <= o e - b u f ; end // FSMD n e x t - s t a t e l o g i c always Q* 60 begin addr-next = addr-reg ; data-f 2s-next = data-f 2s-reg; data-s2f -next = data-s2f -reg; ready = l'bO; case (state-reg) idle : begin i f (-men) state-next = idle; else begin addr-next = addr; if (-rw) // write begin state-next = wrl; data-f 2s-next = data-f 2s ; end e l s e // read state-next = rdl; 80 end ready = l'bl; end wrl : state-next = wr2; wr2 : state-next = idle; rdl : state-next = rd2; rd2 : begin data-s2f -next = dio-a; state-next = idle; end default : state-next = idle; endcase end // look-ahead output logic 100 a l w a y s Q * begin tri-buf = 1 'bl; // s i g n a l s a r e a c t i v e low we-buf = l'bl; oe-buf = 1 'bl; c a s e (state-next idle : oe-buf = l'bl; wrl : begin tri-buf = l'bO; we-buf = l'bO; end wr2 : tri-buf = 1'bO; rdl : oe-buf = l'bO; rd2 : oe-buf = l'bO; endcase 120 end // t o main system a s s i g n data-s2f -r = data-s2f -reg; a s s i g n data-s2f-ur = dio-a; 125 // to sram a s s i g n we-n = we-reg; a s s i g n oe-n = oe-reg; a s s i g n ad = addr-reg; // i / o for sram chip a I30 a s s i g n ce-a-n = l'bO; a s s i g n ub-a-n = l'bO; a s s i g n lb-a-n = l l b O ; assign dio-a = (-tri-reg) 7 data-f2s-reg : 16'bz; 155 e n d m o d u l e To minimize the off-chip pad delay (discussed in Section 11.5.1), the corresponding FPGA's 110 pins should be configured properly. This can be done by adding additional information in the constraint file. A typical line is NET "ad<17>" LOC = "L3" I IOSTANDARD = LVCMOS33 I SLEW=FAST ; 11.4.4 Basic testing circuit We use two circuits to verify operation of the SRAM controller. The first one is a basic testing circuit that allows us manually to perform a single read or write operation. In addition to the SRAM chip 110 signals, the circuit has the following signals: sw. It is 8 bits wide and used as data or address input. led. It is 8 bits wide and used to display the retrieved data. btn [01 . When it is asserted, the current value of sw is loaded to a data register. The output of the register is used as the data input for the write operation. a btn 111. When it is asserted, the controller uses the value of sw as a memory address and performs a write operation. a btn C21. When it is asserted, the controller uses the value of sw as a memory address and performs a read operation. The readout is routed to the l e d signal. During a write operation, we first specify the data value and load it to the internal register and then specify the address and initiate the write operation. During a read operation, we specify the address and initiate the read operation. The retrieved data is displayed in eight discrete LEDs. The complete HDL code is shown in Listing 1 1.2. Listing 11.2 Basic SRAM testing circuit module ram-ctrl-test ( input wire clk, r e s e t , input wire [7:01 sw, 5 input wire [2:0] btn, output wire [7:0] l e d , output wire [17:0] ad, output wire we-n, oe-n, inout wire [15:0] dio-a, 10 output wire ce-a-n, ub-a-n, ); lb-a-n // signal declaration wire [17:0] addr; 15 wire [15:01 data-s2f; r e g [ 1 5 : 01 d a t a - f 2 s ; r e g mem, r w ; reg [7:01 data-reg; wire [2:01 db-btn; 20 // body // instantiation sram-ctrl ctrl-unit ( . clk(clk), . reset (reset), .mem(mem), . rw(rw) 9 25 .addr(addr), .data-f2s(data-f2s), .ready() 2 . data-s2f -r (data-s2f 1, . data-s2f -ur .ad(ad) 9 .we-n(we-n), . oe-n(oe-n), .dio-a(dio-a) 3 . ce-a-n (ce-a-n) , . ub-a-n (ub-a-n) , . lb-a-n(lb-a-n)) ; 30 debounce deb-unit0 ( . clk(clk), .reset(reset), . sw(btn [Ol), . d b - l e v e l 0 , . db-tick (db-btn LO])) ; debounce deb-unit1 35 ( . clk(clk), .reset(reset), . sw(btn [11), . d b - l e v e l 0 , . db-tick(db-btn [l])) ; debounce deb-unit2 ( . cik(cik), .reset(reset), . sw(btn [2]) 9 . db-level() , . db-tick(db-btn [21)) ; // data r e g i s t e r s a l w a y s Q ( p o s e d g e elk) i f (db-btn [Ol ) JS data-reg <= sw; // address a s s i g n addr = ClO'b0, sw); so // always Q* begin data-f2s = 0 ; i f (db-btn[11) / / w r i t e is begin mem = l'bl; rw = l'bO; data-f 2s = {8' b0, data-reg); end e l s e i f (db-btn 121) / / r e a d begin mem = l'bl; rw = l'bl; end else begin mem = l'bO; rw = l'bl; end 70 end // outpt~r a s s i g n led = data-s2f C7:OI ; endmodule 11.4.5 Comprehensive SRAM testing circuit The second circuit performs comprehensive testing. It verifies operation of the SRAM controller and checks the integrity of the SRAM chip as well. This circuit has three functions: Write testing data patterns to the entire SRAM at the maximal rate. Read the entire SRAM at the maximal rate, check the retrieved data against the original patterns, and record the number of erroneous readouts. Inject erroneous data. These functions can be initiated by three debounced pushbuttons. The ASMD chart is shown in Figure 11.7. It contains three branches, corresponding to three functions. The middle branch writes the test patterns to the SRAM. The wr-clkl, wr-clk2, and wr-clk3 states correspond to the i d l e , wrl, and wr2 states of the SRAM controller. The FSMD uses the 18-bit c register as a counter to loop through this branch 218 times. The content of the c register is used as an address and the reversed 16 LSBs are used as data during a write operation. The FSMD writes all memory locations while looping through this branch. The left branch reads data from the SRAM. The three states correspond to the i d l e , r d l , and rd2 states of the SRAM controller. The FSMD again loops through the branch 218 times. The retrieved data is compared with the original test patterns, and the e r r register is used to keep track of the number of mismatches. The right branch performs a single write operation. It uses the 8-bit switch to form a memory address and writes an erroneous pattern to that address. The i n j counter is used to keep track of the number of injected errors. The complete HDL code is shown in Listing 1 1.3. Listing 11.3 ComprehensiveSRAM testing circuit module sram-test ( input wire clk, reset, i n p u t w i r e [7:01 sw, : i n p u t w i r e [2:0] btn, o u t p u t w i r e [3:01 an, o u t p u t w i r e [7:01 led, sseg, output wire [17:0] ad, output wire we-n, oe-n, 10 i n o u t wire [15:01 dio-a, output wire ce-a-n, ub-a-n, lb-a-n 1; // symbolic s t a t e declaration 15 l o c a l p a r a m [2:01 test-init = 3 'b000, rd-clkl = 3'b001, rd-clk2 = 3'b010, rd-clk3 = 3'b011, 20 wr-err = 3'b100, wr-clkl = 3'b101, wr-clk2 = 3'b110, wr-clk3 = 3'blll; 25 // signal declaration reg [2:0] state-reg , state-next ; reg [17:01 addr; ........................................................ ready = 1 addre c ,............... 1 , ................... rd-clk2 ........, j addrtc j I data-f2s t -c[l5:0] j 8 81 ........................ ............... / wr-clk2 + j addr t (0..0, sw} j dataxf2s + 1..1 8 8 .............. I 1L ,.L......... i , ,. ............................ rd-clk3 j ctc+l 1 L..... ...,........... , ............... j wr-clk3 j ctc+l ............ L 4T 1 ............ ................ 1 Figure 11.7 ASMD chart o f a comprehensive SRAM testing circuit. w i r e [15:01 data-s2f ; r e g [15:0] data-f2s; M reg mem, rw; w i r e [2:0] db-btn; r e g [17:0] c-next , c-reg; r e g [7:01 inj-next , inj-reg; r e g [15:01 err-next , err-reg; 35 // body ................................................. // component i n s t a n t i a t i o n ................................................. 40 // i n s t a n t i a t i o n sram-ctrl ctrl-unit ( . elk (elk), . reset (reset , .mem (men) , . rw(rw) . addr (addr) , . data-f 2s (data-f 2s) 9 . ready 2 .data-s2f-r(), .data-s2f-ur(data-s2f) 9 .ad(ad) 3 .we-n(we-n), .oe-n(oe-n), .dio-a(dio-a), .ce-a-n(ce-a-n), .ub-a-n(ub-a-n), .lb-a-n(lb-a-n)); debounce deb-unit0 50 . ( . clk(clk), .reset(reset), .swcbtn [Ol) , . db-level 0 , db-tick (db-btn [O] 1) ; debounce deb-unit1 ( . clk(c1k) , .reset(reset), . sw(btn [l]) , 5s . db-level ( ) , . db-tick (db-btn [l] ) ) ; debounce deb-unit2 ( . clk(c1k) , .reset(reset), . sw(btn [21), . d b - l e v e l 0 , . db-tick(db-btn [21)) ; 60 disp-hex-mux disp-unit ( . clk(c1k) , .reset(l'b0) , . dp_in(4'bllll), .hex3 (err-reg [l5 : 121 ) , . hex2 (err-reg Ell :81) , .hex1 (err-reg [ 7 : 41 , . hex0 (err-reg [3:01) , . an(an1, . sseg(sseg)) ; ................................................. / / FSMD ................................................. 70 / / FSMD s t a t e & d a t a r e g i s t e r s a l w a y s @ ( p o s e d g e clk , p o s e d g e reset ) i f (reset) begin state-reg <= test-init; c-reg <= 0 ; inj-reg <= 0 ; err-reg <= 0 ; end else begin s t a t e - r e g <= s t a t e - n e x t ; c - r e g <= c - n e x t ; i n j - r e g <= i n j - n e x t ; e r r - r e g <= e r r - n e x t ; 85 end // FSMD n e x t - s t a t e l o g i c always @* begin c-next = c-reg; inj-next = inj-reg; err-next = err-reg; addr = 0; rw = l'bl; mem = I ' b O ; data-f2s = 0; case (state-reg) test-init : i f ( d b - b t n [OI ) begin state-next = rd-clkl ; c-next = 0; err-next = 0; end else if (db-btn[I]) begin state-next = wr-clkl; c-next = 0; inj-next = 0; end e l s e i f (db-btn [21) begin state-next = wr-err ; inj-next = inj-reg + 1; end e1se state-next = test-init; wr-err: // w r i t e I e r r o r ; done in next 2 clocks begin state-next = test-init; mem = l ' b l ; r w = l'bO; a d d r = C I O ' b 0 , sw); data-f2s = 16'hffff; end wr-clkl: // in i d l e s t a t e of srarn-ctrl begin state-next = wr-clk2; mem = l ' b l ; r w = I'bO; addr = c-reg; d a t a - f 2 s = - c - r e g [ I S : 01 ; end wr-clk2: // in wrl s t a t e of srarn-ctrl state-next = wr-clk3 ; wr-clk3: // in wr2 s t a t e of s r a m - c t r l begin c-next = c-reg + 1; i f (c-next ==O) state-next = test-init; else state-next = wr-clkl ; end rd-clkl: // in idle s t a t e of sram-ctrl begin state-next = rd-clk2 ; mem = l'bl; rw = l'bl; addr = c-reg; end rd-clk2: // in rdl s t a t e of s r a m - c t r l state-next = rd-clk3; rd-clk3: // in rd2 s t a t e of s r a m - c t r l begin // compare readout; must use unregistered output i f (-c-reg [l5:01 != data-s2f err-next = err-reg + 1; c-next = c-reg + 1; if (c-next ==O) state-next = test-init; else state-next = rd-clkl; end endcase end 16' // Output assign led = inj-reg; endmodule Note that the number of write-read mismatches is connected to the seven-segment LED display and shown as a four-digit hexadecimal number, and the number of injected errors is connected to the eight discrete LEDs. We can use this circuit as follows: Perform the read function. Since the SRAM is not written yet, it is in the initial "power-on" state. The seven-segment LED display should show a large number of mismatches. Perform the write function. Perform the read function. The number of mismatches should be zero if both the SRAM controller and the SRAM device work properly. Inject error data a few times (to different memory locations). Perform the read function again. The number of mismatches should be the same as the number of injected errors. 11.5 MORE AGGRESSIVE DESIGN Although the previous memory controller functions properly, it does not have optimal performance. While both the read and write cycles are 10 ns of the SRAM device, the back-to-back memory access of this controller takes 60 ns (i.e., three clock cycles). In this section, we study the timing issue in more detail, examine several more aggressive designs and their potential problems, and discuss some FPGA features that help to remedy the problems. 11.5.1 Timing issues Timing issues on asynchronous SRAM There are two subtle timing issues in designing a high-performance asynchronous SRAM controller. The first issue is deactivation of the w e n signal. The 0-to-1 transition of w e n functions somewhat like a clock edge of an FF, in which the data is latched and stored to the internal memory element. Note that the data hold time ( t H D )is zero for this SRAM. Although it appears that it is fine to deactivate w e n and remove data at the same time, this approach is not reliable because of the variations in propagation delays. We must ensure that w e n is deactivated before data is removed from the bus. The second issue is the potential conflict on the data bus, dio. Recall that the data bus is a bidirectional bus. The controller places data on the bus during a write operation, and the SRAM places data on the bus during a read operation. A condition known asfighting occurs if the controller and SRAM place data on the bus at the same time. This condition should be avoided to ensure reliable operation. Estimation ofpropagation delay Designing a good memory controller requires having a good understanding about the propagation delays of various signals. However, it is a difficult task. First, during synthesis, an RT-level description is optimized and mapped to logic cells and wire interconnects. The final implementation may not resemble the block diagram depicted by the initial description, and thus it is difficult to estimate the propagation delay from the initial description. Second, a memory operation involves of-chip data access. Additional propagation delay is introduced when a signal propagates through the FPGA's I10 pads. The delay, sometimes known aspaddelay, is usually much larger than the internal wiring delay and its exact value depends on a variety of factors, including the type of FPGA device, the location ofthe output register (in LE or IOB), the 110 standards, the slew rate, the driver strength, and external loading. It requires intimate knowledge ofthe FPGA device and the synthesis software to perform a good timing analysis and to estimate the propagation delays of various signals. 11.5.2 Alternative design I The first alternative design is targeted to reduce the back-to-back operation overhead. Instead of always returning to the i d l e state, the memory controller can check the mem signal at the end of current memory operation (i.e., in the r d 2 or wr2 state) and determine what to do next. It initiates a new memory operation immediately if there is a pending request. The revised ASMD chart for this controller is shown in Figure 11.8. In the r d 2 and wr2 states, the mem and r w signals are examined and the FSMD may move directly to the r d l or w r l state if another memory operation is required. Default:oe-n = I ; we-n = I;tri-n = I ; ready = 0 !o j raddr t addr I oe-n = 0 oe-n = 0 rrn t dio we-n = 0 1 tri-n = 0 . . ............. - ~ # ........................... tri-n = 0 F Figure 11.8 ASMD chart of SRAM controller design I. Timing analysis Most of the original timing analysis in Section 11.4.2 can still be applied to this design. However, skipping the i d l e state introduces subtle new complications when different types of back-to-back memory operations are performed. The issue is the potential fighting on the data bus. Let us consider a write operation performed immediately after a read operation. During the read operation, the signal flows from the SRAM to the FPGA. To facilitate this operation, the tri-state buffer of the SRAM should be "turned on7' (i.e., passing signal) and the tristate buffer of the FPGA should be "turned off' (i.e., high impedance). During the write operation, the signal flows from the FPGA to the SRAM, and the roles of the two tri-state buffers are reversed. Note that a small delay is required to turn on or off a tri-state buffer. In the SRAM chip, these delays are specified by tHZoE ( o e n to high-impedance time) and tLZOE( o e n to low-impedance time) in Figure 11.2. In the original SRAM controller, both tri-state buffers are turned off in the i d l e state. The state provides enough time for the data bus to settle to the high-impedance condition. The new design requires the two tristate buffers to reverse directions simultaneously during back-to-back operations. For example, when moving from the r d 2 state to the w r l state, the FSMD generates signals to turn off the SRAM's tri-state buffer and to turn on the FPGA's tri-state buffer. A problem may occur in this transition if the SRAM's tri-state buffer is turned off too slowly or the FPGA's tri-state buffer is turned on too quickly. In a small interval, both buffers may allow data to be placed on the bus and fighting occurs. Similarly, fighting may occur when a read operation is performed immediately after a write operation. Since the interval tends to be very small, the fighting should not cause severe damage to the devices but may introduce a large transient current which makes the design less reliable. We must do a detailed timing analysis to examine whether fighting occurs and may even need to fine-tune the timing to fix the problem. As discussed in Section 11.5.1, it is a difficult task. 11.5.3 Alternative design II Timing analysis in Section 11.4.2 shows that the initial design provides a large safety margin. In this controller, a memory operation takes two clock cycles, which amount to 40 ns. Since the read and write cycles of the SRAM are each 10 ns, we naturally wonder whether it is possible to reduce the operation time to a single 20-11s clock cycle. This can be done by eliminating the rd2 and wr2 states in the ASMD chart. The second alternative design uses this approach. The revised ASMD chart is shown in Figure 11.9. It takes one clock cycle to complete the memory access and requires two clock cycles to complete the back-to-back operations. Timing analysis Reducing a state from the original controller imposes much tighter timing constraints for both read and write operations. Let us first consider the read operation. During operation, the address signal first propagates through the FPGA's I10 pads to the SRAM's address bus, and the retrieved data then propagates back through the I10 pads to FPGA's internal logic. All of this must be completed within a 20-11s clock cycle. In addition to the 10-ns SRAM address access time (i.e., tAA),the cycle must accommodate two pad delays. The pad delay of a Spartan-3 device can range from 4 ns to more than 10 ns. Therefore, we need to "fine-tune" the synthesis to achieve this margin. Unlike the read operation, a write operation is "one-way" and only needs to propagate the address, data, and control signals to the SRAM chip. If we assume that the signals experience similar pad delays, the absolute value of the delay is a lesser issue. Instead, the MORE AGGRESSIVE DESIGN 291 Default: oe-n = I; we-n = 1; t r i g = I; ready = 0 L.......... ...................................................... 8 ......................... j rl 7 / oe-n = 0 i ISZI +- dio ......, 1 wl ............ v / we-n = 0 / tri-n = 0 Figure 11.9 ASMD chart of SRAM controller design 11. key is the order of signals being activated and deactivated. As discussed in Section 1 1.5.1, w e n must be deactivated before data to latch the data properly to the SRAM. In the original design, this is achieved by including the second state in the write operation, w r 2 , in which w e n is deactivated but the data is still available (i.e., t r i n is still active). In the revised controller, the w e n and t r i n signals are deactivated simultaneously at the end of the w r l state. Due to the variations in the internal logic and pad delays, normal synthesis cannot guarantee that w e n is deactivated before the data is removed from the external data bus. Again, for a reliable design, we need to fine-tune the synthesis to satisfy this goal. 11.5.4 Alternative design Ill We can combine the features from the two preceding revisions to derive the third alternative design. This new controller eliminates the second clock cycle in the read and write operations and allows back-to-back operation without first returning to the i d l e state. This is the most aggressive design. The revised ASMD chart is shown in Figure 11.10. It combines the modification~from the previous two ASMD charts. The revised design takes one clock cycle to complete the memory access and one clock cycle to complete back-to-back operations. Note that the w e n signal must be asserted for a fraction of the clock period and cannot be shown in the ASMD chart. We use the w e - t m p in the w r l state and later derive w e n from this signal. Timing analysis Since the new design combines the features of the two previous designs, all the timing issues discussed in the two preceding subsections must be considered Default: oe-n = I;we-n = I;tri-n = 1; ready = 0 idle ready = 1 T rdd, t addr .................................................. rsat dio F mem==l tri-n = 0 Figure 11.10 ASMD chart of SRAM controller design 111. for this design as well. One additional issue is generation of the w e n signal. During backto-back write operations, the ASMD stays on the w r l state. In the original design, the w e n signal is a Moore output. It will be asserted to 0 continuously in this case. The controller does not hnction properly since the data is latched to the SRAM at the 0-to- 1 transition of the w e n signal. To solve the problem, the w e n signal must be asserted in only a fraction of the clock period. One possible way to solve the problem is to assert the signal only at the first half of the clock, which is 10 ns and can satisfy the t w P E 1requirement in theory. Intuitively, we are tempted to do this by gating the w e - t m p signal with the clock signal, clk: a s s i g n we-n = w e - t m p I -elk; However, this is not a reliable solution because of the potential glitches and delay variation. A better alternative is discussed in the next subsection. 11.5.5 Advanced FPGA featuresXiLinx ' p e c i f ic The memory controller examples in this section illustrate the limitations of the FSM-based controller and synchronous design methodology. Basically, an FSM cannot generate a control sequence that is "finer" than the period of its clock signal. The operation of these alternative designs relies on factors that cannot be specified by an RT-level HDL description. Due to the variations in propagation delays, the synthesized circuits are not reliable and may or may not work. There are some ad hoc features to obtain better control. These features are usually device and software dependent. For example, the digital clock manager (DCM) circuit and input/output block (IOB) of the Spartan-3 device can help to remedy some of the previously discussed problems. Detailed discussion of DCM and IOB is beyond the scope ofthis book. In this subsection, we sketch a few ideas and illustrate how to apply these features to obtain a more reliable controller. DCM A Spartan-3 FPGA device contains up to eight digital clock managers (DCMs). As its name indicates, a DCM is a circuit that manipulates the system clock signal. It can multiply or divide the frequency or shift the phase of the incoming clock signal to generate new clock signals. One way to obtain a "finer" control sequence is to use a faster clock. Since implementation of a memory controller is fairly simple, the circuit itself can operate at a faster clock rate. For example, we can isolate the memory controller and drive it with a DCM-generated 200-MHz clock signal, whose period is only 5 ns. Consider the write operation of the ASMD chart in Figure 11.6. In the new controller, each state lasts only 5 ns. To satisfy the 10-ns w e n requirement, we need to expand the w r l state to two states and assert the w e n signal in these states. The complete write operation now requires four states. However, because of the faster clock rate, the four clock cycles amount to only 20 ns, which is much better than the original 60-11s design. A simple application of clock phase shift is discussed in the next subsection. IOB An input/output block (IOB) of a Spartan-3 FPGA device provides a programmable interface between an 110 pin and the device's internal logic. It contains several storage registers and tri-state buffers as well as analog driver circuits that can be configured to provide different slew rates and driver strength and to support a variety of 110 standards. To minimize the off-chip pad delay discussed in Section 11S.3, we can put the output registers of the memory controller to the FFs inside the IOBs and configure the driver with clk we-n clkl80 clk2 Figure 11.11 Generating a half-cycle signal with DDR. the proper slew rate and strength. This can be done by specifying the desired condition and configuration in the constraint file. An IOB also contains a double data rate (DDR) register, which has two clocks and two inputs. Conceptually, we can think that the two inputs are sampled independently by the two clocks and the sampled values are stored in the same register. The DDR register and DCM can be combined to generate a control signal whose width is a fraction of a clock signal, as the w e n signal discussed in Section 1 1S.4. The block diagram is shown in Figure 1 1.1I(a). The regular output register is replaced with a DDR register. The top portion of the DDR consists of the we-tmp signal and the original clock signals, c l k . The bottom input of the DDR is tied to 1 and the clock is connected to the out-of-phase clock signal, clk180, which is generated by a DCM. The 1 is always loaded at the rising edge of the clk180 signal, which corresponds to the falling edge ofthe c l k signal. It essentially deactivates the second half of the w e n signal. The timing diagram is shown in Figure 1 1.1I(b). This approach generates a clean half-cycle signal and is far more reliable than the clock gating scheme discussed in Section 1 1S.4. 11.6 BIBLIOGRAPHIC NOTES The data sheet published by ISSI provides detailed information for the IS61LV25616AL SRAM device. The Xilinx application note, XAPP462 Using Digital Clock Managers (DCMs) in Spartan-3 FPGAs, discusses the use of DCM, and the data sheet, DS099 Spartan3 FPGA Family: Complete Data Sheet, explains the architecture and configuration of the IOB and the DDR register. 11.7 SUGGESTED EXPERIMENTS 11.7.1 Memory with a 512K-by-16 configuration There are two 256K-by-16 SRAM chips, and their 110connections are shown in the manual of the S3 board. We can expand them to form a 512K-by-16 SRAM. 1. Derive a scheme to combine the two chips. 2. Follow the procedure in Section 11.4 to design a memory controller for the 512K- by-16 SRAM. Derive the HDL description. 3. Modify the testing circuit in Section 11.4.5 for the new controller and derive the HDL description. 4. Synthesize the testing circuit and verify operation of the controller and SRAM chips. 11.7.2 Memory with a 1M-by-8 configuration Repeat Experiment 11.7.1 but configure the two chips as a 1M-by-8 SRAM. The l b n and u b n signals can be used for this purpose. 11.7.3 Memory with an 8M-by-1 configuration A single bit ofthe 256K-by-16 SRAM can be written as follows: Read a 16-bit word. Modify the designated bit in the word. Write the 16-bit word back. Repeat Experiment 11.7.1 but configure the two chips as an 8M-by-1 SRAM. 11.7.4 Expanded memory testing circuit The memory testing circuit in Section 11.4.5 conducts exhaustive back-to-back read and back-to-back write tests. We can expand the circuit to include an exhaustive "read-afterwrite" test, in which the testing circuit issues write and read operations alternately for the entire memory space. To make the test more effective, the writing and reading addresses should be different. For example, we can make the read operation retrieve the data written 16 positions earlier (i.e., if the current writing address is c, the reading address will be c-16). Create a modified ASMD chart, derive an HDL description, synthesize the circuit, and verify its operation. 11.7.5 Memory controller and testing circuit for alternative design I Derive the HDL code for alternative design I in Section 11.5.2 and create an expanded testing circuit similar to the one in Experiment 11.7.4. Synthesize the testing circuit and examine whether any error occurs during operation. 11.7.6 Memory controller and testing circuit for alternative design II Repeat the process in Experiment 11.7.5 for alternative design I1discussed in Section 11.5.3. 11.7.7 Memory controller and testing circuit for alternative design Ill Repeat the process in Experiment 11.7.5for alternative design 111discussed in Section 11.5.4. 11.7.8 Memory controller with DCM Study the application note on DCM and follow the discussion in Section 11.5.5 to drive the safe memory controller discussed in Section 11.4 with a higher clock rate (150 MHz or even 200 MHz). Derive an ASMD chart and HDL code, and create a new testing circuit. Synthesize the circuit and verify operation of the memory controller and the SRAM. 11.7.9 High-performancememory controller Study the documentation of the DCM and the IOB and apply these features to reconstruct alternative design 111 discussed in Section 11S.4. Create a new testing circuit. Synthesize the circuit and verify operation of the memory controller and the SRAM. CHAPTER 12 XlLlNX SPARTAN-3 SPECIFIC MEMORY 12.1 INTRODUCTION A digital system frequently requires memory for storage. To facilitate this need, most FPGA devices contain dedicated embedded memory modules. While these modules cannot replace the massive external memory devices, they are useful for applications that require small or intermediate-sized memory. Although the basic internal structure ofmemory modules is similar, there are many subtle differences in their 110 interfaces. It is usually difficult for synthesis software to extract the desired features from the code and to infer a matching memory module from the underlying device library. In Xilinx ISE, we can use HDL instantiation,the Core Generator program, or the behavioral HDL inference templateto incorporate an embedded memory module into a design. The third one is semi-device independent and we use this method in this book. In this chapter, we briefly examine Spartan-3 memory modules and the first two methods and provide detailed descriptions of several key behavioral HDL templates. 12.2 EMBEDDED MEMORY OF SPARTAN-3 DEVICE 12.2.1 Overview There are two types of embedded memory in a Spartan-3 device: distributed RAM and block RAM. A distributed RAM is constructed from the logic cell's look-up table (LUT). The LUT can be configured as a 16-by-1 synchronous RAM, and multiple LUTs can be FPGA Prolotyping by VerilogExamples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. 298 XlLlNX SPARTAN-3 SPECIFIC MEMORY cascaded to form a wider and deeper memory module. The Spartan-3 XC3S200 device of the S3 board can provide up to 30K bits of distributed memory, which is small compared to a block RAM or external memory. Furthermore, since the distributed RAM uses the logic cells, it competes for resources with the normal logic. Thus, it is feasible only for applications that require relatively small storage. A block RAM is a special memory module embedded in an FPGA device and is separated from the regular logic cells. It can be thought of as a fast SRAM wrapped by a synchronous, configurable interface. Each block RAM consists of 16K (214) data bits plus optional 2K parity bits. It can be organized in different widths, from 16K by 1 (i.e., 214 by 2') to 512 by 32 (i.e., 2' by 25). The Spartan-3 XC3S200 device has 12 block RAMs, totaling 172K data bits. These block RAMs can be used for intermediate-sized applications, such as a FIFO, a large look-up table, or an intermediate-sized local memory. In comparison, the external SRAM chips of the S3 board have a capacity of 8M bits. Both the distributed RAM and block RAM are already "wrapped" with a synchronous interface, and thus no additional memory controller circuit is needed. They are very flexible and can be configured to perform single- and dual-port access and to support various types of buffering and clocking schemes. Detailed discussion is beyond the scope of this book. We only examine several commonly used configurations, including a synchronous single-port RAM, a synchronous dual-port RAM, and a ROM in Section 12.4. 12.2.2 Comparison The Spartan-3 device and the S3 board provide several options for storage elements. It is a good idea to keep in mind the relative capacities of these options: XC3S200's FFs (for registers): about 4.5K bits, embedded in logic cells and 110 buffers XC3S200's distributed RAM: 30K bits, constructed from the logic cells XC3S2OO's block RAM: 172K bits, configured as twelve 16K-bit modules External SRAM: 8M bits, configured as two 256K-by-16 SRAM chips This helps us to decide which option is most suitable for an application at hand. 12.3 METHOD TO INCORPORATE MEMORY MODULES Although memory modules have similar internal structure, there are many subtle differences in their interfaces, such as the numbers of read and write ports, clocking scheme, data and address buffering, enable and reset signals, and initial values. Although it is possible to describe the desired module behaviors in HDL code, the synthesis software may or may not recognize the designer's intention. Therefore, the HDL code cannot always infer the proper memory module and is normally not portable. In Xilinx ISE, there are three methods to incorporate an embedded memory module into a design: HDL instantiation The Core Generator program The behavioral HDL inference template The first two are specific for Xilinx devices and the third is a semi-device-independent behavioral description. Because of the clarity of the behavioral description, we use the third method in this book. We provide a brief overview of the three methods in this section. 12.3.1 Memory module via HDL component instantiation We have used HDL component instantiation in many earlier design examples to include predesigned modules or to create a hierarchy. Instantiating a Xilinx memory module is similar except that there is no HDL description for the architecture body. We must check the manual to find the exact module name and the associated parameters and 110 port definitions. This is a tedious process and is particularly error-prone for memory modules because of the large number of configurations and options. The instantiation code for many Xilinx components can be obtained directly from ISE by + selecting Edit LanguageTemplates. The following are segments of a 16K-by- 1 dual-port RAM: // RAMBI6-SI-SI : V i r t e x -11 / [ [ - P r o , / / S p a r t a n -3/3E 16k x I D u a l - P o r t RAM // Xi1in.x HDL L a n g u a g e T e m p l a t e v e r s i o n 8 . 1 i RAMB16-S1-S1 #( . INIT-A (1 'bO) , . INIT-B(l'bO), . SRVAL-A (1 ' bO) , . SRVAL-B (1 'bO) , .WRITE-MODE-A(~WRITE-FIRST~~), .WRITE-MODE-B ("WRITE-FIRST") , .SIM-COLLISION-CHECK("ALL"), . INIT-00 (256 ' h0 . . . 0) , . INIT-3F (256 ' h0 . . . 0) ) RAMB16-S1-Sl-inst ( . DOA (DOA) , // Port A I-bit Data Output .DOB (DOB) , // Port B I-bit Data Output . ADDRA (ADDRA) , // Port A 14- b i t A d d r e s s l n p u t . ADDRB (ADDRB) , // P o r t B 14- b i t A d d r e s s I n p u t .CLKA (CLKA) , // Port A Clock .CLKB (CLKB) , // Port B Clock .DIA (DIA) , // Port A I- b i t Data Input .DIB (DIB) , .ENA (ENA) , . ENB (ENB) , // Port B I-bit Data Input / / P o r t A RAM E n a b l e I n p u t / / P o r t B RAM E n a b l e I n p u t .SSRA (SSRA) , // Port A Synchronous Set/Reset .SSRB (SSRB) , .WEA (WEA) , // Port B Synchronous Set/Reset // Port A Write Enable Input .WEB (WEB) // Port B Write Enable Input 1; Input Input Although the code is readily available, we must study the manual carefully to find the right component and proper configuration parameters. 12.3.2 Memory module via Core Generator To simplify the instantiation process, Xilinx provides a utility program, known as Core Generator (Coregen), to generate Xilinx-specific components. This utility can be invoked from the ISE environment by selecting Project + New Source. After the New Source Wizard dialog appears, we select IP (Coregen & Architecture Wizard) to invoke the Coregen 300 XlLlNX SPARTAN-3 SPECIFIC MEMORY program. The program guides the users through a series of questions and then generates several files. The file with the .xco extension is a text file that contains the information necessary to construct the desired memory component. The file with the .v extension contains the "wrapper" code for simulation purpose. This file cannot be used to instantiate the desired component and is ignored during the synthesis process. Although using the Coregen program is more convenient than direct HDL instantiation, it is not within the HDL framework and can lead to a compatibility problem when a design is not done in the Xilinx ISE environment. 12.3.3 Memory module via HDL inference Although it is not possible to develop a device-independent HDL description, the synthesis program of ISE, known as XST, provides a collection of behavioral HDL templates to infer memory modules from Xilinx FPGA devices. These templates are done by behavioral descriptions and contain no device-specific component instantiation. They are easy to understand and can be simulated without an additional HDL library. However, while the description does not explicitly refer to any Xilinx component, the code may not be recognized by other third-party synthesis software, and the desired memory module cannot always be inferred. Thus, these templates can best be described as "semi-portable" and "semi-deviceindependent" behavioral descriptions. Templates for commonly used memory modules are discussed in Section 12.4. On the downside, the template approach is based on the ability of the XST software to recognize the template and infer the proper memory module accordingly. The software may change during upgrade or misinterpret some code. It is a good idea to check the XST synthesis report to ensure that the desired memory module is inferred correctly. 12.4 HDL TEMPLATES FOR MEMORY INFERENCE To use behavioral HDL description to infer the Xilinx memory module, the XST's templates should be followed closely. To avoid misinterpretation, we should refrain from creating our own "innovative" code. The codes in the following subsections are all based on templates of the XST v8.l i Manual. They are the same as the original templates except that the Verilog2001 style of port declaration is used and parameters are added for the width of address bits and the width of data bits. It is a good practice to confine the memory description in a separate HDL module so that the module can easily be identified and replaced when needed. In this section, we discuss the behavioral HDL templates for six configurations, including two for single-port RAMs, two for dual-port RAMs, and two for ROMs. 12.4.1 Single-port RAM The embedded memory of a Spartan-3 device is already wrapped with a synchronous interface similar to that in Section 11.3. Its write operation is always synchronous. At the rising edge of the clock, the address, input data, and relevant control signals, such as w e (i.e., write enable), are sampled. If we is asserted, a write operation is performed (i.e., the input data is stored into the memory location designated by the address signal). The read operation can be asynchronous or synchronous. For asynchronous read, the address signal is used directly to access the RAM array. After the address signal changes, the data becomes available after a short delay. For synchronous read, the address signal is sampled at the rising edge ofthe clock and stored in a register. The registered address is then used to access the RAM array. Because of the register, the availability of data is delayed and is synchronized by the clock signal. Due to the internal structure, an asynchronous read operation can be realized only by the distributed RAM. Single-port RAM with asynchronous read The template for the single-port RAM with asynchronous read is shown in Listing 12.1. It is modified after the rams-04 module of the XST Manual. Listing 12.1 Template for a single-port RAM with asynchronous read / / S i n g l e - p o r t RAM w i t h a s y n c h r o n o u s r e a d / / M o d i f i e d from XST 8 . 1 i v - r a m s - 0 4 module xilinx-one-port-ram-async 5 #( parameter ADDR-WIDTH = 8 , DATA-WIDTH = 1 ) ( 10 input wire clk, input wire we, i n p u t w i r e [ADDR-WIDTH -1 :01 addr , i n p u t w i r e [DATA-WIDTH - 1 :01 d i n , o u t p u t w i r e [DATA-WIDTH -1 :01 dout IS ); // signal declaration r e g [DATA-WIDTH -1 :O] ram [2**ADDR-WIDTH -1 : 01 ; 20 // body always Q(posedge clk) i f (we) // write operation ram [addrl <= d i n ; // read operation 25 assign dout = ram[addrl ; endmodule The code is very similar to the register file discussed in Section 4.2.3 except that the read and write operations use the same address. It contains a two-dimensional array data type for storage and uses dynamic indexing to access the element in the array. The code shows that the write operation is controlled by the clock signal and the read operation depends only on the address. Since an asynchronous read can be realized only by the distributed RAM, this configuration is recommended only for applications that require small storage. Single-port RAM with synchronous read The template for the single-port RAM with synchronous read is shown in Listing 12.2. It is modified after the rams-07 module of the XST Manual. Listing 12.2 Template for a single-port RAM with synchronous read // S i n g l e - p o r t RAM w i t h s y n c h r o n o u s r e a d // M o d i f i e d from XST 8 . 1 i v - r a m s - 0 7 302 XlLlNX SPARTAN-3 SPECIFIC MEMORY module x i l i n x ~ o n e ~ p o r t ~ r a m ~ s y n c 5 #( parameter ADDR-WIDTH = 12, DATA-WIDTH = 8 1 ( 10 input wire clk , input wire we, input wire [ADDR-WIDTH -1:Ol addr , input wire [DATA-WIDTH -1:OI din, o u t p u t w i r e [DATA-WIDTH-1: 01 dout 15 ); // signal declaration r e g [DATA-WIDTH -1: O] ram [ 2 * * A D D R _ W I D T H-1 :01 ; r e g [ADDR-WIDTH -1: 01 addr-reg ; 20 // body always @ (posedge clk) begin i f (we) // w r i t e operation 5 ram [addr] <= din; addr-reg <= a d d r ; end // read operation assign dout = ram [addr-reg1 ; 11 endmodule Note that the addr signal is now sampled and stored to the a d d r r e g register at the rising edge ofthe clock, and the memory array (the ram signal) is accessed via the a d d r r e g signal. The data is available only after the a d d r r e g is updated and thus implicitly synchronized to the c l k signal. Synthesis report During synthesis, a proper RAM module should be inferred from the code template. We can check the synthesis report to confirm the inference of the RAM module. For example, consider the instantiation of a 4K-by-8 RAM (212-by-23) with synchronous read: The inference of RAM should be indicated in the HDL S y n t h e s i s section of the synthesis report: ....................................................................................... * HDL Synthesis * ........................................................... ... Found 4096x8-bit s i n g l e - p o r t block RAM f o r s i g n a l . 1 mode I aspect ratio I clock I write enable I address I data in I data out I ram-style --------------- write-first 4096-word x 8-bit connected to signal connected to signal connected to signal connected to signal connected to signal Auto Summary : inferred 1 RAM(s) I I rise I high I I I I I -------- The number of block RAMS used should be reported in the Final Report section of the synthesis report: Device utilization summary: Selected Device : 3s200ft256-5 Number of BRAMs: ... 2 out of 12 16% As we expected, a 4K-by-8 single-port block RAM is inferred and two block RAMS are used to realize the circuit. 12.4.2 Dual-port RAM A dual-port RAM includes a second port for memory access. Ideally, the second port should be able to conduct read or write operation independently and have its own set of address, data input and output, and control signals. To be compatible with older versions of XST, we consider a configuration with the second port that can conduct a read operation only. In this book, the main application of the dual-port configuration is for video memory, which requires one write port and one read port. Thus, this configuration does not impose a serious limitation for our purposes. As in a single-port RAM, the read operation of a dual-port RAM can be asynchronous or synchronous. Dual-port RAM with asynchronous read The template for the dual-port RAM with asynchronous read is shown in Listing 12.3. It is modified after the rams-09 module of the XST Manual. Listing 12.3 Template for adual-portRAM with asynchronous read // D u a l - p o r t RAM w i t h a s y n c h r o n o u s r e a d // M o d i f i e d from XST 8 . 1 i v - r a m s - 0 9 module x i l i n x ~ d u a l ~ p o r t ~ r a m ~ a s y n c 5 #( parameter ADDR-WIDTH = 6 , DATA-WIDTH = 8 ) ( 304 XlLlNX SPARTAN-3 SPECIFIC MEMORY 10 input wire c l k , input wire we, i n p u t w i r e [ADDR-WIDTH -1: 01 addr-a , addr-b , i n p u t w i r e [DATA-WIDTH -1: 01 din-a , o u t p u t w i r e [DATA-WIDTH -1 :01 dout-a , dout-b I5 ); // signal declaration r e g [DATA-WIDTH -1: 01 ram [ 2 * * A D D R _ W I D T H-1 : 01 ; zu / / b o d y always @(posedge clk) if (we) // write operation ram [addr-a] <= din-a; // two read operations 15 assign dout-a = ram [addr-a] ; assign dout-b = ram [addr-b] ; endmodule The write operation is similar to that of the single-port RAM, but the code includes a second output port, dout-b, which retrieves data from the second address, addr-b. As in a single-port RAM with asynchronous read, the dual-port version can be realized only by distributed RAM, and thus its size is limited. Note that if we ignore the dout-a port, it is the same as the single-read-port register file of Listing 4.6. Dual-port RAM with synchronous read The template for the dual-port RAM with synchronous read is shown in Listing 12.4. It is modified after the rams-11 module of the XST Manual. Listing 12.4 Template for a dual-port RAM with synchronous read / / D u a l - p o r t RAM w i t h s y n c h r o n o u s r e a d // M o d i f i e d from XST 8 . 1 i v - r a m s - 1 1 module xilinx-dual-port-ram-sync 5 #( parameter ADDR-WIDTH = 6 , DATA-WIDTH = 8 1 ( 10 input wire clk, input wire we, input wire [ADDR-WIDTH-1 :O] addr-a, addr-b , i n p u t w i r e [DATA-WIDTH -1 :01 din-a , o u t p u t w i r e [DATA-WIDTH -1 :01 dout-a , dout-b I5 ); // signal declaration r e g [DATA-WIDTH - 1 :01 ram [ 2 * * A D D R _ W I D T H-1 :O] ; reg [ADDR-WIDTH-1:OI addr-a-reg, addr-b-reg; 20 // body always @(posedge clk) begin i f (we) // n,rile operation 25 ram [addr-a] <= din-a; addr-a-reg <= addr-a ; addr-b-reg <= addr-b ; end // two read o p e r a t i o n s 30 a s s i g n dout-a = ram [addr-a-reg] ; a s s i g n dout-b = ram [addr-b-reg] ; endmodule The code is similar to Listing 12.3 except that the two addresses are first stored in two registers and the registered outputs are used to access memory. 12.4.3 ROM Despite its name, a ROM (read-only memory) is a combinational circuit and has no internal state. Its output depends only on its input (i.e., address). There is no real embedded ROM in a Spartan-3 device, but it can be emulated by a combinational circuit or a single-port RAM with the write operation disabled. The content of the ROM can be expressed as a case statement in the HDL code and the values are loaded to the RAM when the device is programmed. Since the ROM is based in a RAM, the read operation can be asynchronous or synchronous. ROM with asynchronousread A real ROM is a combinational circuit and thus should not have a buffer or a clock signal. To be consistent with the terms used in this section, we call it a ROM with asynchronoz~sread. This type of ROM can be described by a single case statement and the template is shown by an example in Listing 12.5. The code simply renames the input and output ports of the hex-to-seven-segment LED decoder in Listing 3.14. The address of the ROM functions as the selection expression of the case statement and the corresponding content is assigned to the data signal. Listing 12.5 Template for a ROM with asynchronous read module rom-template ( i n p u t w i r e [3:01 output reg [7:0] 5 ); addr, data // bodv always Q* case (addr) 4'hO: data = 7'b0000001; 4'hl: data = 7'b1001111; 4'h2: data = 7'b0010010; 4'h3: data = 7'b0000110; 4'h4: data = 7'b1001100; 4'h5: data = 7'b0100100; 4'h6: data = 7'b0100000; 4'h7: data = 7'b0001111; 4'h8: data = 7'b0000000; 4'h9: data = 7'b0000100; 20 4'ha: data = 7'b0001000; 4'hb: data = 7'b1100000; 4'hc: data = 7'b0110001; 4'hd: data = 7'b1000010; 4'he: data = 7'b0110000; 25 4'hf: data = 7'b0111000; endcase endmodule Since there is no address or data buffer in this circuit, the ROM cannot be realized by a block RAM. It is actually synthesized as a combinational circuit with the logic cells and thus this type of ROM is feasible only for a small table. ROM with synchronous read For a large table, it is better to utilize a block RAM to realize the ROM. Since the read operation of a block RAM is controlled and synchronized by a clock signal, the ROM requires a clock signal as well. The template for the ROM with synchronous read is shown in Listing 12.6. It is modified after the rams-2lc module of the XST Manual, and the hex-to-seven-segment LED decoder is used for demonstration. Listing 12.6 Template for a ROM with synchronous read module xilinx-rom-sync-template ( input wire clk, i n p u t w i r e [3:01 addr, i o u t p u t r e g C7:OI data ); // signal declaration r e g [3:0] addr-reg; 10 / / bod,v a l w a y s Q ( p o s e d g e clk) addr-reg <= addr; I? always Q* c a s e (addr-reg) 4'hO: data = 7'b0000001; 4'hl: data = 7'b1001111; 4'h2: data = 7'b0010010; 4'h3: data = 7'b0000110; 4'h4: data = 7'b1001100; 4'h5: data = 7'b0100100; 4'h6: data = 7'b0100000; 4'h7: data = 7'b0001111; 4'h8: data = 7'b0000000; 4'h9: data = 7'bOOOOlOO; 4'ha: data = 7'bOOOlOOO; 4'hb: data = 7'b1100000; 4'hc: data = 7'b0110001; 4'hd: data = 7'b1000010; 4'he: data = 7'b0110000; 4'hf: data = 7'b0111000; endcase The code is similar to that of the single-port RAM with synchronous read but with an additional case statement. Note that operation of this ROM depends on the clock signal, and its timing is different from that of a normal ROM. Artificial inclusion of the clock signal is necessary to infer a block RAM for the ROM implementation. During synthesis, the software automatically determines whether to use regular logic cells or block RAMS to realize this circuit. 12.5 BIBLIOGRAPHIC NOTES Two Xilinx application notes, XAPP464 Using Look-Up Tables as Distributed RAM in Spartan-3 Generation FPGAs and XAPP463 Using Block RAM in Spartan3 Generation FPGAs, provide detailed information on the distributed RAM and block RAM. Chapter 2 of the XST User Guide v8.li, titled HDL Coding Techniques,includes about two dozen HDL code templates to infer various memory configurations. The comprehensive ISE tutorial, ISE In-Depth Tutorial, includes a section on the Core Generator program. Although the program is simple, we need to know the module's basic fbnctionalities and its relevant parameters to create a proper instance. 12.6 SUGGESTED EXPERIMENTS 12.6.1 Block-RAM-based FIFO In Section 4.5.3, we design a FIFO buffer that uses a register file for storage. To increase its capacity, we can replace the register file with a block RAM-based dual-port RAM module. Derive the HDL code for the new design. Synthesize the verification circuit discussed in Section 4.5.3 with the new FIFO buffer and verify its operation. Note that due to the synchronous read, the behavior of the new FIFO is not completely identical to that of the original FIFO. 12.6.2 Block-RAM-based stack We discuss the hnction of a stack in Experiment 4.7.7. To increase its capacity, we can replace the register file with a block RAM-based dual-port RAM module. Repeat the experiment. 12.6.3 ROM-based sign-magnitude adder We can implement any n-input, m-output hnction with a 2n-by-m ROM. Consider the sign-magnitude adder discussed in Section 3.9.2 and assume that a and b are 4-bit input signals. Design this circuit as follows: 1. Write a program in a conventional programming language, such as C or Java, to generate a case statement that incorporates the 28-by-4 truth table of this circuit. 2. Follow the ROM template in Listing 12.5 to derive the HDL code. 308 XlLlNX SPARTAN9 SPECIFIC MEMORY 3. Synthesize the circuit and verify its operation. 4. Check the synthesis report and compare the sizes (in terms of the number of logic cells) of the original implementation and the ROM-based implementation. 5. Expand a and b to 8-bit input signals and repeat steps 1 to 4. 12.6.4 ROM-based s i n ( x ) function One way to implement a sinusoidal function, sin(x),is to use a look-up table. Assume that the desired implementation requires 10-bit input resolution [i.e., there are 1024 (2") points between the input range of 0 and 21. and 8-bit output resolution [i.e., there are 256 (28)points between the output range of -1 and +I]. Let the input and output be the 10-bit .c signal and the 8-bit y signal. The relationship between x and y is - = sin ( 2 . 5 ) 27 Because of the symmetry of the sin function, we only need to construct a 28-by-7 table for the first quadrant (i.e., between 0 and $) and use simple pre- and postprocessing circuits to obtain the values in other quadrants. Design this circuit as follows: 1. Write a program in a conventional programming language to generate a case statement that incorporates the 28-by-7 look-up table for the first quadrant. 2. Follow the ROM template in Listing 12.6 to derive the HDL code for the look-up table. 3. Derive a testbench to generate the sinusoidal output for three complete periods. This can be done by using a 10-bit counter to generate the 10-bit ROM address for 3 * 2' clock cycles. In ModelSim, we can display the y signal in Analog format to emulate the effect of a digital-to-analog converter. 12.6.5 ROM-based s i n ( x ) and c o s ( x )functions In many communication modulation schemes, the sin(x)and cos(x)functions are needed at the same time. Assume that the format of the input and output is similar to that in Experiment 12.6.4. The new circuit has two outputs, y, and y,: " = sin (2.s) 27 $ = COS ( 2 . 5 ) Although we can follow the previous procedure and create a new ROM for the cos(x) function, a better alternative is to share the same ROM for both sin(x)and cos(x)functions. This is based on the observations that cos(x) is only a phase shift of sin(x) and that the FPGA's block RAM can provide dual-port access. Note that this circuit requires essentially a "dual-port ROM." No HDL behaviorial template is given for this type of memory. We need to experiment with HDL codes and to check the synthesis report to ensure that only one block RAM is inferred. It may be necessary to use the Core Generator program or direct HDL component instantiation to achieve this goal. Construct this special ROM and derive the HDL code for the pre- and postprocessing circuits. Use a testbench similar to that in Experiment 12.6.4 to verify the circuit's operation. CHAPTER 13 VGA CONTROLLER I: GRAPHIC 13.1 INTRODUCTION VGA (video graphics array) is a video display standard introduced in the late 1980s in IBM PCs and is widely supported by PC graphics hardware and monitors. We discuss the design of a basic eight-color 640-by-480 resolution interface for CRT (cathode ray tube) monitors in this book. CRT synchronization and basic graphic processing are examined in this chapter, and text generation is discussed in Chapter 14. 13.1.1 Basic operation of a CRT The conceptual sketch of a monochrome CRT monitor is shown in Figure 13.1. The electron gun (cathode) generates a focused electron beam, which traverses a vacuum tube and eventually hits the phosphorescent screen. Light is emitted at the instant that electrons hit a phosphor dot on the screen. The intensity of the electron beam and the brightness of the dot are determined by the voltage level of the external video input signal, labeled mono in Figure 13.1. The mono signal is an analog signal whose voltage level is between 0 and 0.7 V. A vertical deflection coil and a horizontal deflection coil outside the tube produce magnetic fields to control how the electron beam travels and to determine where on the screen the electrons hit. In today's monitors, the electron beam traverses (i.e., scans) the screen systematically in a fixed pattern, from left to right and from top to bottom, as shown in Figure 13.2. FPGA Prototyping by Verilog Examples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. Figure 13.1 Conceptual diagram of a CRT monitor. horizontal retrace --\ I\ horizontal scan Figure 13.2 CRT scanning pattern. Table 13.1 Three-bit VGA color combinations Red (R) Green (G) Blue (B) Resulting color black blue green cyan red magenta yellow white The monitor's internal oscillators and amplifiers generate sawtooth waveforms to control the two deflection coils. For example, the electron beam moves from the left edge to the right edge as the voltage applied to the horizontal deflection coil gradually increases. After reaching the right edge, the beam returns rapidly to the left edge (i.e., retraces) when the voltage changes to 0. The relationship between the sawtooth waveform and the scan is shown in Figure 13.4. Two external synchronization signals, hsync and vsync, control generation of the sawtooth waveforms. These signals are digital signals. The relationship between the hsync signal and the horizontal sawtooth is also shown in Figure 13.4. Note that the "1" and "0" periods of the hsync signal correspond to the rising and falling ramps of the sawtooth waveform. The basic operation of a color CRT is similar except that it has three electron beams, which are projected to the red, green, and blue phosphor dots on the screen. The three dots are combined to form a pixel. We can adjust the voltage levels of the three video input signals to obtain the desired pixel color. 13.1.2 VGA port of the S3 board The VGA port has five active signals, including the horizontal and vertical synchronization signals, hsync and vsync,and three video signals for the red, green, and blue beams. It is physically connected to a 15-pin D-subminiature connector. A video signal is an analog signal and the video controller uses a digital-to-analog converter to convert the digital output to the desired analog level. If a video signal is represented by an N-bit word, it can be converted to 2 N analog levels. The three video signals can generate 23N different colors. This is also known as 3N-bit color since a color is defined by 3 N bits. In the S3 board, a I -bit word is used for each video signal. and this leads to only eight (i.e., 23)possible colors. The possible color combinations are shown in Table 13.1. If we use the same 1-bit signal to drive the video signals, they become either "000" or " 1 11" and the monitor functions as a black-and-white monochrome monitor. 13.1.3 Video controller A video controller generates the synchronization signals and outputs data pixels serially. A simplified block diagram of a VGA controller is shown in Figure 13.3. It contains a synchronization circuit, labeled vga-sync,and a pixel generation circuit. external j i datalcontrol ; r g b 7 - - pixel generation - > pixel-x - pixel-y video-on - circuit , I hsync vsync 1 clk-; vga-sync > VGA monitor ' VGA controller Figure 13.3 Simplified block diagram of a VGA controller. The vga-sync circuit generates timing and synchronization signals. The hsync and vsync signals are connected to the VGA port to control the horizontal and vertical scans of the monitor. The two signals are decoded from the internal counters, whose outputs are the p i x e l x and pixel-y signals. The p i x e l x and pixel-y signals indicate the relative positions of the scans and essentially specify the location of the current pixel. The vga-sync circuit also generates the video-on signal to indicate whetherto enable or disable the display. The design of this circuit is discussed in Section 13.2. The pixel generation circuit generates the three video signals, which are collectively referred to asthe rgb signal. A color value is obtained according to the current coordinates of the pixel (the pixel-x and pixel-y signals) and the external control and data signals. This circuit is more involved and is discussed in the second half of this chapter and Chapter 14. 13.2 VGA SYNCHRONIZATION The video synchronization circuit generates the hsync signal, which specifies the required time to traverse (scan) a row, and the vsync signal, which specifies the required time to traverse (scan) the entire screen. Subsequent discussions are based on a 640-by-480 VGA screen with a 25-MHzpixel rate, which means that 25M pixels are processed in a second. Note that this resolution is also know as the VGA mode. The screen of a CRT monitor usually includes a small black border, as shown at the top of Figure 13.4. The middle rectangle is the visible portion. Note that the coordinate of the vertical axis increases downward. The coordinates of the top-left and bottom-right comers are (0,O) and (639,479), respectively. 13.2.1 Horizontal synchronization A detailed timing diagram of one horizontal scan is shown in Figure 13.4. A period of the hsync signal contains 800 pixels and can be divided into four regions: Figure 13.4 Timing diagram of a horizontal scan. v-video-on line count vsync 480 horizontal scan lines r+ 8 8 8 8 8 88 8 8 8 8 /8 8 01 I I , , // / 4791 489: 491; 5241 8 ,8 display (480) bottom border (10) front porch retrace (2) one vertical scan (525 Figure 13.5 Timing diagram of a vertical scan. top border (33) back porch , Display: region where the pixels are actually displayed on the screen. The length of this region is 640 pixels. Retrace: region in which the electron beams return to the left edge. The video signal should be disabled (i.e., black), and the length of this region is 96 pixels. Right border: region that forms the right border of the display region. It is also know as the front porch (i.e., porch before retrace). The video signal should be disabled, and the length of this region is 16 pixels. Left border: region that forms the left border of the display region. It is also know as the backporch (i.e., porch after retrace). The video signal should be disabled, and the length of this region is 48 pixels. Note that the lengths of the right and left borders may vary for different brands of monitors. The hsync signal can be obtained by a special mod-800 counter and a decoding circuit. The counts are marked on the top of the hsync signal in Figure 13.4. We intentionally start the counting from the beginning of the display region. This allows us to use the counter output as the horizontal (x-axis) coordinate. This output constitutes the p i x e l x signal. The hsync signal goes low when the counter's output is between 656 and 751. Note that the CRT monitor should be black in the right and left borders and during retrace. We use the h-video-on signal to indicate whether the current horizontal coordinate is in the displayable region. It is asserted only when the pixel count is smaller than 640. 13.2.2 Vertical synchronization During the vertical scan, the electron beams move gradually from top to bottom and then return to the top. This corresponds to the time required to refresh the entire screen. The format of the vsync signal is similar to that of the hsync signal, as shown in Figure 13.5. The time unit of the movement is represented in terms of horizontal scan lines. A period of the vsync signal is 525 lines and can be divided into four regions: Display: region where the horizontal lines are actually displayed on the screen. The length of this region is 480 lines. Retrace: region that the electron beams return to the top of the screen. The video signal should be disabled, and the length of this region is 2 lines. Bottom border: region that forms the bottom border of the display region. It is also know as thefrontporch (i.e., porch before retrace). The video signal should be disabled, and the length of this region is 10 lines. Top border: region that forms the top border of the display region. It is also know as the backporch (i.e., porch afier retrace). The video signal should be disabled, and the length of this region is 33 lines. As in the horizontal scan, the lengths of the top and bottom borders may vary for different brands of monitors. The vsync signal can be obtained by a special mod-525 counter and a decoding circuit. Again, we intentionally start counting from the beginning ofthe display region. This allows us to use the counter output as the vertical (y-axis) coordinate. This output constitutes the pixel-y signal. The vsync signal goes low when the line count is 490 or 491. As in the horizontal scan, we use the v-video-on signal to indicate whether the current vertical coordinate is in the displayable region. It is asserted only when the line count is smaller than 480. 13.2.3 Timing calculation of VGA synchronization signals As mentioned earlier, we assume that the pixel rate is 25 MHz. It is determined by three parameters: p: the number of pixels in a horizontal scan line. For 640-by-480 resolution, it is 1: the number of lines in a screen (i.e., a vertical scan). For 640-by-480 resolution, it is 1= 525 lines - screen s: the number of screens per second. For flickering-free operation, we can set it to screens ~=60- second The s parameter specifies how fast the screen should be refreshed. For a human eye, the refresh rate must be at least 30 screens per second to make the motion appear to be continuous. To reduce flickering, the monitor usually has a much higher rate, such as the 60 screens per second specification above. The pixel rate can be calculated by the three Darameters: pixel rate = p * 1* s = 2 5 M - pix- els second The pixel rate for other resolutions and refresh rates can be calculated in a similar fashion. Clearly, the rate increases as the resolution and refresh rate grow. 13.2.4 HDL implementation The function of the vga-sync circuit is discussed in Section 13.1.3. If the frequency of the system clock is 25 MHz, the circuit can be implemented by two special counters: a mod-800 counter to keep track of the horizontal scan and a mod-525 counter to keep track of the vertical scan. Since our designs generally use the 50-MHz oscillator of the prototyping board, the system clock rate is twice the pixel rate. Instead of creating a separate 25-MHz clock domain and violating the synchronous design methodology, we can generate a 25-MHz enable tick to enable or pause the counting. The tick is also routed to the p-tick port as an output signal to coordinate operation of the pixel generation circuit. The HDL code is shown in Listing 13.1. It consists of a mod-2 counter to generate the 25-MHz enable tick and two counters for the horizontal and vertical scans. We use two status signals, h-end and v-end,to indicate completion of the horizontal and vertical scans. The values of various regions of the horizontal and vertical scans are defined as constants. They can easily be modified if a different resolution or refresh rate is used. To remove potential glitches, output buffers are inserted for the hsync and vsync signals. This leads to a one-clock-cycle delay. We should add a similar buffer for the rgb signal in the pixel generation circuit to compensate for the delay. Listing 13.1 VGA synchronization circuit module vga-sync ( input wire clk, reset, output wire hsync , vsync , video-on, p-tick, o u t p u t w i r e [9:0] pixel-x, pixel-y ); // constant declaration // VGA 640-by-480 sync p a r a m e t e r s lo localparam HD = 640; // h o r i z o n t a l d i s p l a y area l o c a l p a r a m HF = 48 ; // h . f r o n t ( l e f t ) b o r d e r localparam HB = 16 ; // h . back ( r i g h t ) border localparam HR = 96 ; // h . retrace localparam VD = 480; // v e r t i c a l display area 15 l o c a l p a r a m VF = 10; / / v . f r o n t ( t o p ) b o r d e r l o c a l p a r a m VB = 33; / / v . b a c k ( b o t t o m ) b o r d e r localparam VR = 2; // v . retrace // mod-2 counter m reg mod2-reg; wire mod2-next ; // sync counters r e g [9:01 h-count-reg, h-count-next; r e g [9:01 v-count-reg , v-count-next ; 25 // outpzit buffer reg v-sync-reg , h-sync-reg ; wire v-sync-next , h-sync-next ; // status signal wire h-end , v-end , pixel-t ick; 30 // body // registers a l w a y s Q ( p o s e d g e clk , p o s e d g e reset) i f (reset) 35 begin m o d 2 - r e g <= l'bO; v-count-reg <= 0 ; h-count-reg <= 0 ; v-sync-reg <= l'bO; h-sync-reg <= l'bO; end else begin mod2-reg <= mod2-next ; v-count-reg <= v-count-next; h-count-reg <= h-count-next; v-sync-reg <= v-sync-next ; h-sync-reg <= h-sync-next ; end / / mod-2 c i r c u i t t o g e n e r a t e 25 MHz e n a b l e t i c k assign mod2-next = "mod2-reg; assign pixel-tick = mod2-reg; 55 // status signals // end of horizontal counter (799) assign h-end = (h-count-reg==(HD+HF+HB+HR-1)) ; // end of v e r t i c a l counter (524) assign v-end = (v-count-reg==(VD+VF+VB+VR-1)) ; hU // n e x t - s t a t e l o g i c o f mod-800 h o r i z o n t a l sync c o u n t e r a l w a y s Q* i f ( p i x e l - t i c k ) / / 25 MHz p u l s e i f (h-end) h-count-next = 0; else h-count-next = h-count-reg + 1; else h-count-next = h-count-reg; 70 // n e x t - s t a t e l o g i c o f mod-525 v e r t i c a l sync c o u n t e r a l w a y s Q* i f (pixel-tick t h-end) i f (v-end) v-count-next = 0; else v-count-next = v-count-reg + 1; else v-count-next = v-count-reg; no // h o r i z o n t a l and v e r t i c a l s y n c , buffered to avoid g l i t c h // h - s v n c - n e x t a s s e r t e d b e t w e e n 656 and 751 a s s i g n h-sync-next = (h-count-reg>=(HD+HB) && h-count-reg<=(HD+HB+HR-1)); 85 // v h - s y n c - n e x t a s s e r t e d b e t w e e n 490 and 491 a s s i g n v-sync-next = (v-count-reg>=(VD+VB) && v-count-reg<=(VD+VB+VR-1)); // video o n / o f f 90 a s s i g n video-on = (h-count-reg BAR-V)) b a r - y - n e x t = b a r - y - r e g - BAR-V; / / move up end The design of the ball is more involved. We have to replace the four boundary constants with four signals and create two registers, b a l l x x e g and ball-y-reg, to store the current x- and y-axis coordinates ofthe left and top boundaries. The ball usually moves at a constant velocity (i.e., at a constant speed and in the same direction). It may change direction when hitting the wall, the paddle, or the bottom or top of the screen. We decompose the velocity into an x-component and a y-component, whose values can be either a positive constant value, BALL-VP, or a negative constant value, BALL-VLN. The current values of the two components are stored in the x-delta-reg and y-delta-reg registers. The code segment for updating b a l l x r e g and ball-y-reg is // new b a l l p o s i t i o n assign ball-x-next = (refr-tick) ? ball-x-reg+x-delta-reg : ball-x-reg ; assign ball-y-next = (refr-tick) ? ball-y-reg+y-delta-reg : ball-y-reg ; and the code segment for updating x-delta-reg and y-delta-reg is // new b a l l v e l o c i t y always Q* begin x-delta-next = x-delta-reg; y-delta-next = y-delta-reg; if (ball-y-t < 1) // reach top y - d e l t a - n e x t = BALL-V-P ; e l s e i f ( b a l l - y - b > (MAX-Y-1)) // r e a c h b o t t o m y - d e l t a - n e x t = BALL-V-N; e l s e i f ( b a l l - x - 1 <= WALL-X-R) // r e a c h w a l l x - d e l t a - n e x t = BALL-V-P ; // bounce back e l s e i f ((BAR-X-L < = b a l l - x - r ) && ( b a l l - x - r <=BAR-X-R) && ( b a r - y - t < = b a l l - y - b ) && ( b a l l - y - t < = b a r - y - b ) ) // reach x of r i g h t bar and h i t , ball bounce back x - d e l t a - n e x t = BALL-V-N; end Note that if the paddle bar misses the ball, the ball continues moving to the right and eventually wraps around. The complete code is shown in Listing 13.5. Listing 13.5 Pixel-generation circuit for the animated pong game module pong-graph-animate ( input wire clk, r e s e t , input wire video-on , I input wire [l:O] b t n , input wire [9:01 pix-x , pix-y , VGA CONTROLLER I: GRAPHIC output reg [2:0] graph-rgb >; // constant and signal declaration / / x , y c o o r d i n a t e s (0,O) t o ( 6 3 9 , 4 7 9 ) localparam MAX-X = 640; localparam MAX-Y = 480; wire refr-tick; ,, // vertical stripe as a wall ,, // wall left , right boundary l o c a l p a r a m WALL-X-L = 3 2 ; l o c a l p a r a m WALL-X-R = 3 5 ; // right v e r t i c a l bar // // bar left , right boundary l o c a l p a r a m BAR-X-L = 6 0 0 ; l o c a l p a r a m BAR-X-R = 6 0 3 ; // bar t o p , bottom boundary wire [9:0] bar-y-t , bar-y-b; l o c a l p a r a m BAR-Y-SIZE = 7 2 ; // r e g i s t e r to track top boundary ( x position is f i x e d ) reg [9:0] bar-y-reg, bar-y-next; // bar moving v e l o c i t y when a button is pressed localparam BAR-V = 4 ; // // square ball ,, l o c a l p a r a m BALL-SIZE = 8 ; // ball left , right boundary wire [9: 01 b a l l - x - 1 , b a l l - x - r ; // ball t o p , bottom boundary wire [9: 01 b a l l - y - t , b a l l - y - b ; // reg to track left , top position r e g [ 9 : 01 b a l l - x - r e g , b a l l - y - r e g ; w i r e [9 : 01 b a l l - x - n e x t , b a l l - y - n e x t ; // reg to track ball speed r e g [9 :01 x - d e l t a - r e g , x - d e l t a - n e x t ; reg [9:01 y-delta-reg, y-delta-next; // ball v e l o c i t y can be pos or neg) l o c a l p a r a m BALL-V-P = 2 ; l o c a l p a r a m BALL-V-N = - 2 ; // round ball ,, w i r e [2: 01 rom-addr , r o m - c o l ; reg [7:01 rom-data; wire rom-bit ; // object output signals wire wall-on , bar-on , sq-ball-on , rd-ball-on; w i r e [2 : 01 w a l l - r g b , b a r - r g b , b a l l - r g b ; ,, // r o u n d b a l l image ROM always Q* case (rom-addr) 3'hO: rom-data = 8'b00111100; // **** 3 ' h l : rom-data = 8'b01111110; // ****** 3'h2: rom-data = 8 ' b l l l l l l l l ; // ******** 3'h3: rom-data = 8 ' b l l l l l l l l ; // ******** 3'h4: rom-data = 8 ' b l l l l l l l l ; // ******** 3'h5: rom-data = 8 ' b l l l l l l l l ; // ******** 3'h6: rom-data = 8'b01111110; // ****** 3'h7: rom-data = 8'b00111100; // **** endcase // registers a l w a y s Q( p o s e d g e c l k , p o s e d g e r e s e t if (reset) begin b a r - y - r e g <= 0 ; b a l l - x - r e g <= 0 ; b a l l - y - r e g <= 0 ; x - d e l t a - r e g <= l O ' h 0 0 4 ; y - d e l t a - r e g <= l O ' h 0 0 4 ; end else begin b a r - y - r e g <= b a r - y - n e x t ; b a l l - x - r e g <= b a l l - x - n e x t ; b a l l - y - r e g <= b a l l - y - n e x t ; x - d e l t a - r e g <= x - d e l t a - n e x t ; y - d e l t a - r e g <= y - d e l t a - n e x t ; end // r e f r - t i c k : I-clock t i c k a s s e r t e d at s t a r t of v-sync // i . e . . when the s c r e e n is r e f r e s h e d (60 H z ) a s s i g n r e f r - t i c k = ( p i x - y = = 4 8 1 ) && ( p i x - x = = O ) ; 1, // ( w a l l ) l e f t v e r t i c a l s t r i p // pixel within wall a s s i g n w a l l - o n = (WALL-X-L < = p i x - x ) && ( p i x - x <=WALL-X-R) ; // wall rgb output assign wall-rgb = 3'bOOl; // blue ,, // right v e r t i c a l bar // // boundary VGA CONTROLLER I: GRAPHIC assign bar-y-t = bar-y-reg; a s s i g n b a r - y - b = b a r - y - t + BAR-Y-SIZE - 1 ; // pixel within bar a s s i g n bar-on = (BAR-X-L<=pix-x) && (pix-x<=BAR-X-R) && ( b a r - y - t < = p i x - y ) && ( p i x - y <=bar-y-b) ; // bar rgb output assign bar-rgb = 3'bOlO; // green // new bar y - p o s i t i o n always O* begin bar-y-next = b a r - y - r e g ; // no move if (refr-tick) i f ( b t n El1 & ( b a r - y - b < (MAX-Y-1-BAR-V))) b a r - y - n e x t = b a r - y - r e g + BAR-V; // move down e l s e i f ( b t n [ O ] & ( b a r - y - t > BAR-V)) b a r - y - n e x t = b a r - y - r e g - BAR-V; // move up end // square ball // boundary assign ball-x-1 = ball-x-reg; assign ball-y-t = ball-y-reg; a s s i g n b a l l - x - r = b a l l - x - 1 + BALL-SIZE - 1 ; a s s i g n b a l l - y - b = b a l l - y - t + BALL-SIZE - 1 ; // pixel within ball assign sq-ball-on = ( b a l l - x - 1 < = p i x - x ) && ( p i x - x < = b a l l - x - r ) && ( b a l l - y - t < = p i x - y ) && ( p i x - y < = b a l l - y - b ) ; / / map c u r r e n t p i x e l l o c a t i o n t o ROM a d d r / c o l assign rom-addr = pix-y [2:01 - ball-y-t [2:0] ; assign rom-col = pix-x [2:0] - ball-x-1 [2:0] ; assign rom-bit = rom-data [rom-col] ; // pixel within ball assign rd-ball-on = sq-ball-on & rom-bit; // ball rgb output assign ball-rgb = 3'blOO; // red // new b a l l p o s i t i o n assign ball-x-next = (refr-tick) ? ball-x-reg+x-delta-reg : ball-x-reg ; assign ball-y-next = (refr-tick) ? ball-y-reg+y-delta-reg : ball-y-reg ; // new b a l l v e l o c i t y always O* begin y-delta-next = y-delta-reg; if (ball-y-t < 1) // reach top y - d e l t a - n e x t = BALL-V-P; e l s e i f ( b a l l - y - b > (MAX-Y-1)) // r e a c h b o t t o m y - d e l t a - n e x t = BALL-V-N; e l s e i f ( b a l l - x - 1 <= WALL-X-R) // r e a c h w a l l x-delta-next = BALL-V-P; // bounce back e l s e i f ( (BAR-X-L <=ball-x-r ) && (ball-x-r <=BAR-X-R) && (bar-y-t <=ball-y-b) && (ball-y-t <=bar-y-b)) // reach x of right bar and h i t , ball bounce back x-delta-next = BALL-V-N; end // // rgb multiplexing c i r c u i t ,, 175 always O* i f ("video-on) graph-rgb = 3'bOOO; // blank else i f (wall-on) graph-rgb = wall-rgb ; e l s e i f (bar-on) graph-rgb = bar-rgb ; e l s e i f (rd-ball-on) graph-rgb = ball-rgb ; 185 else graph-rgb = 3'b110; // y e l l o w background endmodule As in the still screen, we can combine the synchronization circuit and create the top-level description. The HDL code is shown in Listing 13.6. Listing 13.6 Complete circuit for the animated pong game screen module pong-top-an ( input wire clk, reset, i n p u t w i r e [1:01 btn, i o u t p u t w i r e hsync , vsync, o u t p u t w i r e [2:01 rgb 1; // signal d e c l a r a t i o n III w i r e [9:01 pixel-x, pixel-y; w i r e video-on , pixel-tick; r e g [2:0] rgb-reg; w i r e [2 : 01 rgb-next ; I5 // body // i n s t a n t i a t e vga svnc c i r c u i t vga-sync vsync-unit ( . clk(clk), .reset(reset), . hsync (hsync), . v s ~ n c ( v s ~ n c9 ) .video-on(video-on), .p-tick(pixel-tick), 20 .pixel-x(pixe1-x), .pixel_y(pixel-y)); // instantiate graphic generator pong-graph-animate pong-graph-an-unit ( . clk (clk) , .reset (reset 1, . btn (btn) , 25 .video-on(video-on), .pix-x(pixe1-x), // rgb buffer always Q(posedge clk) 30 if (pixel-tick) rgb-reg <= rgb-next ; // output assign rgb = rgb-reg; 25 endmodule Note that there is no other control mechanism is this code. The ball simply moves and bounces continuously. A top-level control circuit is discussed in Chapter 14. 13.5 GRAPHIC GENERATION WITH A BIT-MAPPED SCHEME The bit-mapped scheme maps each pixel to a word in video memory. There are about 3 10k pixels in a 640-by-480 screen. This translates to 3 10k and 930k bits for monochrome and color displays, respectively. The actual size of the video memory can be much larger since the memory address must be properly aligned for fast access. For example, to map the pixel's current coordinates to a memory location, we can concatenate the pixel's xcoordinate, which is 10 bits (i.e., [log,(640)1), and the pixel's y-coordinate, which is 9 bits (i.e., [log,(480)1). This approach requires no additional circuit to translate the pixel's coordinates to a memory address but introduces some unused "holes" in memory. The memory size is increased from 310k words to 512K (i.e., 21°+') words. For the S3 board, memory is available from the external SRAM chips and FPGA's embedded block RAMs, as discussed in Chapters 11 and 12. Recall that the total capacity of the Spartan 3S200 device's block RAM is only about 192K bits. It is not large enough for a full-screen bit-mapped display. We must use the external SRAM, which is 8M bits, for this purpose. In this section, we use a small 128-by-128 (27-by-27) area of the screen to illustrate the design of the bit-mapped scheme. The screen has 16K (214) pixels in this area and requires a 16K-by-3 video memory for color display. This can be implemented by three embedded block RAMs. The small area is at the top-left comer of the screen and displays the trace of a bouncing one-pixel dot, as shown in Figure 13.9. The circuit uses a 3-bit switch to specify the color of the trace and a pushbutton switch to randomly select the origin of the trace. When the pushbutton switch is pressed, the dot starts to move, like the bouncing ball in Section 13.4.3. The trace forms a rectangle after the dot hits the four sides of the small area. A new trace is generated each time the pushbutton switch is pressed. 13.5.1 Dual-port RAM implementation A conceptual block diagram of this circuit is shown in Figure 13.10. The video memory is a synchronous 16K-by-3 (i.e., 214-by-3) dual-port RAM. The dual-port module discussed in Listing 12.4 can be used for this purpose. The seven LSBs of the pixel's y-coordinate form the seven MSBs of the memory address, and the seven LSBs of the pixel's x-coordinate form the seven LSBs of the memory address. The d o t x y circuit keeps track of the current location of the dot and generates its current y- and x-coordinates, which are concatenated as the write address. The 3-bit external switch input, sw,is the rgb value, which is connected GRAPHIC GENERATIONWITH A BIT-MAPPEDSCHEME 333 127 x-axis y-axis Figure 13.9 Dot trace shown in a 128-by-128 bit map. pixel-y pixel-x btn Figure 13.10 Conceptual block diagram of a dot trace circuit. 334 VGA CONTROLLER I: GRAPHIC to the memory's din-a port. The seven LSBs of pixel-y and the seven LSBs of p i x e l x form the read address. The data is retrieved continuously and the corresponding readout is routed to the rgb multiplexing circuit. The complete code of the dot trace pixel generation circuit is shown in Listing 13.7. We use two registers, d o t x x e g and dot-yreg, to keep track of the dot's current x- and y-coordinates and use two registers, v x r e g and v-yreg, to keep track of the current horizontal and vertical velocities. Computation of the dot's coordinates and velocities is similar to that of the bouncing ball in Section 13.4.3. In addition to regular updates, the d o t x m e x t and dot-ynext signals obtain the values of the seven LSBs of p i x x and pix-y when the pushbutton switch is pressed. Since these signals change much faster than a human's perception, the new origin appears to be random. Listing 13.7 Pixel-generationcircuit for a 128-by-128bit map module bitmap-gen ( input wire clk, reset, input wire video-on, 5 input [1:0] btn, input [2:01 sw, i n p u t wire C9:Ol pix-x, pix-y , output reg [2:01 bit-rgb 1; 10 // constant and signal d e c l a r a t i o n wire refr-tick , load-tick ; ,, // video sram IS // wire we; w i r e C13: 01 addr-r , addr-w; wire [2:0] din, dout ; //- 20 // d o t l o c a t i o n and v e l o c i t y localparam MAX-X = 128; localparam MAX-Y = 128; // dot v e l o c i t y can be pos or neg 25 l o c a l p a r a m DOT-V-P = 1; localparam DOT-V-N = -1; // reg to keep track of dot Iocation reg [6:0] dot-x-reg , dot-y-reg; w i r e C6: 01 dot-x-next , dot-y-next ; 30 // r e g t o k e e p t r a c k o f d o t v e l o c i t y r e g C6: 01 v-x-reg , v-y-reg ; w i r e [6:01 v-x-next , v-y-next ; ,r // object output signals 3s // wire bitmap-on ; w i r e [2 :01 bitmap-rgb ; GRAPHIC GENERATION WITH A BIT-MAPPED SCHEME 335 40 / / i n s t a n t i a t e d e b o u n c e c i r c u i t f o r a b u t t o n debounce deb-unit ( . clk(c1k) , .reset(reset), . sw(btn LO]) , . d b - l e v e l 0 , . db-tick(1oad-tick)) ; / / i n s t a n t i a t e d u a l - p o r t v i d e o RAM ( 2 - 1 2 - b y - 7 ) 5 xilinx-dual-port-ram-sync # ( . ADDR-WIDTH (14) , . DATA-WIDTH ( 3 ) ) video-ram ( . clk(clk), . we(we) , . addr-a(addr-w), . addr-b(addr-r), . din-a (din) , . dout-a , . dout-b (dout)) ; // video ram i n t e r f a c e ill a s s i g n addr-w = {dot-y-reg , dot-x-reg); a s s i g n addr-r = {pix-y [6:O] , pix-x [6:011; a s s i g n we = l'bl; a s s i g n din = sw; a s s i g n bitmap-rgb = dout ; 5 // r e g i s t e r s a l w a y s Q ( p o s e d g e clk , p o s e d g e reset) if (reset) begin dot-x-reg <= 0; dot-y-reg <= 0; v-x-reg <= DOT-V-P; v-y-reg <= DOT-V-P; end else begin dot-X-reg <= dot-x-next ; dot-y-reg <= dot-y-next; V-x-reg <= v-x-next ; v-y-reg <= v-y-next; end // r e f r - t i c k : I-clock t i c k asserted at s t a r t of v-sync a s s i g n refr-tick = (pix-y==481) && (pix-x==O); 75 // p i x e l w i t h i n b i t map a r e a a s s i g n bitmap-on =(pix-x <=127) & (pix-y <=I271 ; // dot position // "randomly" load dot l o c a t i o n when btn[O] pressed a s s i g n dot-x-next = (load-tick) ? pix-x[6:01 : (refr-tick) ? dot-x-reg + v-x-reg : dot-x-reg ; a s s i g n dot-y-next = (load-tick) ? pix-y [6:01 : (refr-tick) ? dot-y-reg + v-y-reg : dot-y-reg ; 85 // dot x v e l o c i t y a s s i g n v-x-next = (dot-x-reg==l) ? DOT-V-P : // reach l e f t (dot-x-reg==(MAX-X -2)) ? DOT-V-N : / / r e a c h r i g h t v-x-reg ; 90 / / d o t y v e l o c i t v a s s i g n v-y-next = (dot-y-reg==l) ? DOT-V-P : // reach top (dot-y-reg==(MAX-Y - 2 ) ) ? DOT-V-N : // r e a c h b o t t o m v-y-reg; 95 // // rgb multiplexing circuit ,, always Q* i f (-video-on) bit-rgb = 3'bOOO; // blank else i f (bitmap-on) bit-rgb = bitmap-rgb; else 10s bit-rgb = 3'bllO; // y e l l o w background endmodule The HDL code for the top-levelsystem is shown in Listing 13.8. Listing 13.8 Completecircuit for a bit-mappedscreen module dot-top ( input wire clk, reset, i n p u t w i r e [1:01 btn, 5 i n p u t w i r e [2:01 sw, output wire hsync, vsync, o u t p u t w i r e [2:0] rgb 1; 10 // signal declaration w i r e [ 9 : 01 pixel-x , pixel-y ; wire video-on , pixel-tick; r e g [2:01 rgb-reg; w i r e [2 :01 rgb-next ; I5 // body / / i n s t a n t i a t e VGA s y n c c i r c u i t vga-sync vsync-unit ( . clk(clk1, .reset(reset), .hsync(hsync), .vsync(vs~nc), .video-on(video-on), .p-tick(pixe1-tick), .pixel-x(pixe1-x), .pixel-y(pixe1-y)); // instantiate graphic generator bitmap-gen bitmap-unit zs ( . clk(clk), . reset (reset), . btn(btn), . sw(sw) .video-on(video-on), .pix-x(pixel-x), .pix-y(pixe1-y), .bit-rgb(rgb-next)); // rgb buffer M a l w a y s @ ( p o s e d g e clk) i f (pixel-tick) rgb-reg <= rgb-next ; // output a s s i g n rgb = rgb-reg; is endmodule BIBLIOGRAPHIC NOTES 337 13.5.2 Single-port RAM implementation Although a dual-port memory is ideal, it is not always available. Using regular single-port memory, such as the S3 board's external SRAM, for the video memory requires careful coordination between the write and read operations to avoid interruption in data retrieval. For demonstration purposes, we configure the embedded block RAM as a single-port synchronous SRAM and redesign the previous dot trace circuit. In the dot trace circuit, the dot's coordinates are updated once every screen scan. Thus, the video memory can be written at this rate as well. We can do this during the vertical retrace since the video is off in this period and writing video memory does not interfere with screen data retrieval. Note that the r e f r - t i c k signal is asserted when p i x e l - y is 481. The video is off in this location, and writing video memory will not interfere with the screen data retrieval. We use this signal as the write enable signal, we, for the single-port RAM. The single-port RAM module discussed in Listing 12.2 can be used for this purpose. The memory portion of Listing 13.7 now becomes / / i n s t a n t i a t e d u a l - p o r t v i d e o RAM ( 2 - 1 2 - b y - 7 ) xilinx-one-port-ram-sync # ( . ADDR-WIDTH (14), . DATA-WIDTH ( 3 ) ) video-ram (.clk(clk), .we(we), .addr(addr), .din (din) , .dout (dout ) ) ; // v i d e o ram i n t e r f a c e a s s i g n addr-w = (dot-y-reg , dot-x-reg); a s s i g n addr-r = (pix-y C6:Ol , pix-x [6:01); assign addr = (refr-tick) ? addr-w : addr-r; a s s i g n we = refr-tick; assign din = sw; assign bitmap-rgb = dout; The dot trace circuit updates one pixel in a screen scan. The required memory bandwidth for writing is 60*3 bits per second, which is rather low. Thus, the previous design is fairly straightforward. The design of memory interface becomes much more difficult when a large memory bandwidth is required (i.e., when a large portion of the screen is updated at a rapid rate). 13.6 BIBLIOGRAPHIC NOTES Rapid PrototL;oing of Digital Svstems by James 0.Hamblen et al. contains timing information for monitors with different resolutions and refresh rates. 13.7 SUGGESTED EXPERIMENTS 13.7.1 VGA test pattern generator A VGA test pattern generator produces two simple patterns to verify operation of a VGA monitor. The first pattern divides the screen evenly into eight vertical stripes, each displaying a unique color. The second pattern is similar but the screen is divided into eight horizontal stripes. A 1-bit switch is used to select the pattern. Design a pixel-generating circuit for this pattern generator and then combine it with the synchronization circuit in a top-level module. Synthesize and verify operation ofthe circuit. 13.7.2 SVGA mode synchronization circuit The specification for the super VGA (SVGA) mode with 72-Hz refresh rate is resolution: 800-by-600 pixels pixel rate: 50 MHz horizontal display region: 800 pixels horizontal right border: 64 pixels horizontal left border: 56 pixels horizontal retrace: 120 pixels vertical display region: 600 lines vertical bottom border: 23 lines vertical top border: 37 lines vertical retrace: 6 lines We wish to create a dual-mode synchronization circuit that can support both VGA and SVGA modes. The mode can be selected by a switch. Construct the circuit as follows: 1. Modify the horizontal and vertical synchronization counters of Listing 13.1 to accommodate both modes. 2. Design a pixel-generating circuit that draws a 100-pixel grid on the screen (i.e., draw a vertical line every 100 pixels and draw a horizontal line every 100 pixels). 3. Derive a top-level module. Synthesize and verify operation of the two modes. 13.7.3 Visible screen adjustment circuit Due to the internal timing error of a monitor, the visible portion of the screen may not always be centered. We can adjust the location of the visible portion by slightly modifying the widths surrounding black border areas. In a horizontal scan line, there are 64 pixels for the right and left border regions. To move the visible portion horizontally, we can add a certain number of pixels to one border region and subtract the same number from the opposite border region. We can adjust the visible portion vertically in a similar fashion. Design a screen adjustment circuit as follows: 1. Expand the VGA synchronization circuit to include this feature. Use a switch to select the vertical or horizontal mode, and use two pushbuttons to move the visible screen to IeftJup and rightldown. 2. Modify the testing circuit in Section 13.2.5 to incorporate the new synchronization circuit. 3. Synthesize and verify operation of the circuit. 13.7.4 Ball-in-a-box circuit The ball-in-a-box circuit displays a bouncing ball inside a square box. The square box is centered on the screen and its size is 256-by-256 pixels. The ball is an 8-by-8 round ball. When the ball hits the wall, the ball bounces back and the wall flashes (i.e., changes color briefly). The ball can travel at four different speeds, which are selected by two slide SUGGESTED EXPERIMENTS 339 Figure 13.11 Screen of the breakout game. switches, and its direction changes randomly when a pushbutton switch is pressed. Derive the HDL code and then synthesize and verify operation of the circuit. 13.7.5 Two-balls-in-a-box circuit We can expand the circuit in Experiment 13.7.4 to include two balls inside the box. When two balls collide, the new directions of the two balls should follow the laws of physics. Derive the HDL code and then synthesize and verify operation of the circuit. 13.7.6 Two-player pong game The two-player pong game replaces the left wall with another paddle, which is controlled by the second player. To better accommodate two players, we can use the keyboard interface of Section 9.4 as the input device. Four keys can be defined to control vertical movements of the two paddles. Derive the HDL code and then synthesize and verify operation of the circuit. 13.7.7 Breakout game The breakout game is somewhat like the pong game. In this game, the left wall is replaced by several layers of "bricks." When the ball hits a brick, the ball bounces back and the brick disappears. The basic screen is shown in Figure 13.11. As in the code of Listing 13.5, we assume that the game runs continuously. Derive the HDL code and then synthesize and verify operation of the circuit. 13.7.8 Full-screen dot trace We can implement the full-screen dot trace circuit of Section 13.5 using the external SRAM chip as follows: 1. Modify the SRAM controller in Chapter 1 1to configure the SRAM chip as a 2''-by-8 memory. 2. Follow the discussion in Section 13.5.2 to incorporate the new memory module in the circuit. Note that accessing the external memory requires two clock cycles. 3. Synthesize and verify operation of the circuit. 13.7.9 Mouse pointer circuit The mouse interface is discussed in Section 10.5. The mouse pointer circuit uses a mouse to control the movement of a small 16-by-16 square on the screen. It functions as follows: The square moves according to the movement of the mouse. a The pointer wraps around when it reaches a border. The pointer changes color when the left button of the mouse is pressed. It circulates through the eight colors defined in Table 13.1. Synthesize and verify operation of the circuit. 13.7.10 Small-screen mouse scribble circuit Mouse scribble circuit keeps track of the trace of the mouse movement in a 128-by-128 screen, somewhat similar to the dot trace circuit discussed in Section 13.5. Its specification is as follows: a The 3-bit switch determines the color of the trace. a Clicking the left button of the mouse turns on and off the trace alternately. Clicking the right button of the mouse clears the screen. Synthesize and verify operation of the circuit. 13.7.11 Full-screen mouse scribble circuit Repeat Experiment 13.7.10, but use the full screen. An external SRAM module similar to that in Experiment 13.7.8 is needed for this circuit. CHAPTER 14 VGA CONTROLLER II: TEXT 14.1 INTRODUCTION A tile-mapped pixel generation scheme is discussed in Section 13.3. A tile can be considered as a "super pixel." Whereas a pixel is defined by a 3-bit word in a bit-mapped scheme, a tile is mapped to a predesigned pattern. One method of constructing a text display is to treat the characters as tiles and design the pixel generation circuit with the tile-mapped scheme. We discuss this method in this chapter and apply it to add scores and rules to the pong game. 14.2 TEXT GENERATION 14.2.1 Character as a tile When applying a tile-mapped scheme, we treat each character as a tile. In a bit-mapped scheme, the value of a pixel represents a 3-bit color. On the other hand, the value of a tile represents the code of a specific pattern. For the text display, we use the 7-bit ASCII code for the character tiles. The patterns of the tiles constitute the font of the character set. A variety of fonts are available. We choose an 8-by-16 (i.e., 8-column-by-16-row) font similar to the one used in early IBM PCs. In this font, each character is represented as an 8-by-16 pixel pattern. The pattern for the letter "A" is shown in Figure 14.l(a). The character patterns are stored in a ROM and each pattern requires 24* 8 bits. The pattern memory is known as font ROM. The original font set consists of 256 patterns, FPGA Prototyping by VerilogExamples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. I character address row 72"-by-8 ROM (a) Pixel pattern (b) ROM content Figure 14.1 Font pattern for the letter A. including digits, upper- and lowercase letters, punctuation symbols, and many specialpurpose graphic symbols. We implement only the first half [i.e., 128 (2')] of the patterns and exclude most graphic symbols. To accommodate this set, 2' * 24 * 8 ROM bits are needed. It is usually configured as a 211-by-8 ROM. 7 ) g ) When we use these 8-by-16 characters (i.e., tiles) in a 640-by-480 resolution screen, 80 (i.e., tiles can be fitted into a horizontal line and 30 (i.e., tiles can be fitted into a vertical line. In other words, the screen can be treated as an 80-by-25 tile screen. We can put characters on the screen using these scaled coordinates. 14.2.2 Font ROM Our font set implements the 128 characters of the ASCII code, listed in Table 8.1. The 128 (2') character patterns can be accommodated by a 2"-by-8 font ROM. In this ROM, the seven MSBs of the 1I -bit address are used to identify the character, and the four LSBs of the address are used to identify the row within a character pattern. The address and ROM content for the letter "A" are shown in Figure 14.l(b). In the ASCII table, the first column (ASCII codes OOls to IFls) consists of nonprintable control characters. The font ROM uses these codes to implement special graphic symbols. For example, the 0616 code will generate a spade pattern, 4, on the screen. Note that the 0016 code is reserved for a blank tile. The 2''-by-8 font ROM can fit neatly into a single block RAM of the Spartan-3 device. We use the ROM template of Listing 12.6 to ensure that a block RAM will be inferred during synthesis. Part of the HDL code is shown in Listing 14.1. The complete code has 2'' rows in constant definition and the file can be downloaded from the companion Web site. TEXT GENERATION 343 Listing 14.1 Partial code of the font ROM module f ont-rom ( input wire c l k , input wire [10:0] addr, 5 output reg [7:0] data 1; // signal declaration r e g 110: 01 a d d r - r e g ; 10 // body always Q(posedge clk) a d d r - r e g <= a d d r ; 15 always Q* case (addr-reg) / / c o d e xOO bIank 11' h 0 0 0 : d a t a = 8 ' b 0 0 0 0 0 0 0 0 ; / / ll'h001: data = 8'b00000000; // ll'h002: data = 8~b00000000;// 11' h003: data = 8'b00000000; // 11'h004: data = 8~b00000000;// 11'h005: data = 8~b00000000;// ll'h006: data = 8'b00000000; // 11'h007: data = 8Jb00000000; // 11'h008: d a t a = 8Jb00000000; // 11'h009: data = 8'b00000000; // 11' h00a: data = 8'b00000000; // ll'h00b: data = 8~b00000000;// 30 l l ' h 0 0 c : d a t a = 8'b00000000; // 11'hood: d a t a = 8 b00000000; // ll'h00e: data = 8'b00000000; // 11' h00f : d a t a = 8'b00000000; // //code x01 smiley face 35 11'h010: d a t a = 8'b00000000; // i l ' h 0 1 1 : d a t a = 8'b00000000; // ll'h012: data = 8'b01111110; // ****** l l ' h 0 1 3 : d a t a = 8'b10000001; // * * ll'h014: data = 8'b10100101; // * * * * 40 ll'h015: data = 8'b10000001; // * * ll'h016: data = 8Jb10000001; // * * ll'h017: data = 8'b10111101; // * **** * ll'h018: data = 8'b10011001; // * ** * ll'h019: data = 8'b10000001; // * * * 11' h O 1 a : d a t a = 8 ' b 1 0 0 0 0 0 0 1 ; / / * Il'hOlb: data = 8'b01111110; // ****** I1 'hOlc: data = 8'b00000000; // I l ' h O l d : d a t a = 8~b00000000; // Il'hOle: data = 8'b00000000; // 11' hOlf : d a t a = 8 ' b 0 0 0 0 0 0 0 0 ; / / 344 VGA CONTROLLER It: TEXT Figure 14.2 Two-stage text generation circuit. ll'h7f0: data ll'h7fl: data ll'h7f2: data 1 1 'h7f3: data 11Jh7f4: data llJh7f5: data llJh7f6: data ll'h7f7: data ll'h7f8: data ll'h7f9: data ll'h7fa: data Il'h7fb: data Il'h7fc: data Il'h7fd: data ll'h7fe: data 11 ' h7f f : data endcase = 8'b00000000; // = 8'b00000000; // = 8'b00000000; / / = 8'b00000000; // = 8'b00010000; // = 8'b00111000; // = 8'b01101100; // = 8'b11000110; // = 8'b11000110; // = 8'b11000110; // = 8'b11111110; / / = 8'b00000000; / / = 8'b00000000; // = 8'b00000000; // = 8'b00000000; // = 8'b00000000 ; // * *** ** ** ** ** ** ** ** ** ******* 711 endmodule Note that the block RAM-based ROM implementation introduces a one-clock-cycle delay, as discussed in Section 12.4.3. 14.2.3 Basic text generation circuit The pixel generation circuit generates pixel values according to the current pixel coordinates (provided by the pixel-x and pixel-y signals) and the external data and control signals. Pixel generation based on a tile-mapped scheme involves two stages. The first stage uses the upper bits of the p i x e l x and pixel-y signals to generate a tile's code, and the second stage uses this code and lower bits to generate the pixel's value. The text generation circuit follows this method, and the basic diagram is shown in Figure 14.2. The screen is treated as a grid of 80-by-30 tiles, each containing an 8-by-16 font pattern. In the first stage, the p i x e l x [9 :31 and pixel-y [8 :41 signals provide the x- and y-coordinates of the current tile location. The character generation circuit uses these coordinates, combined with other external data, to generate the value of this tile (labeled c h a r - a d d r ) , which corresponds to a character's ASCII code. In the second stage, the ASCII TEXT GENERATION 345 code becomes the seven MSBs of the address of the font ROM and specifies the location of the current pattern. It is concatenated with the four LSBs of the screen's y-coordinate (i.e., pixel-y [3 :01,labeled row-addr) to form the complete address (labeled rom-addr) ofthe font ROM. The output of the font ROM (labeled f ont-word) corresponds to an 8-bit row in the pattern. The three LSBs of the screen's x-coordinate (i.e., p i x e l x [2: 01, labeled bit-addr) specify the desired pixel location, and an 8-to-1 multiplexer routes the pixel to the output. 14.2.4 Font display circuit We use a simple font display circuit to verify operation of the font ROM and display all font patterns on the screen. The 128 patterns are arranged in four rows, which correspond to the four columns of the ASCII table in Table 8.1. We can obtain each pattern by using the proper x- and y-coordinates to generate the desired ASCII code, which is labeled the char-addr signal. The code segment is a s s i g n c h a r - a d d r = (pixel-y [5:4] , pixel-x [7:31); The p i x e l x [7 :31 signal forms the five LSBs of the ASCII code, and thus 32 p5)con- secutive font patterns will be displayed in a row. The pixel-y [5:41 signal forms the two MSBs of the ASCII code, and thus four consecutive rows will be displayed. Since the upper bits of the p i x e l x and pixel-y signals are left unspecified, the 32-by-4 region will be displayed repetitively on the screen. An additional code segment is included to turn on the display for the top-left portion of the screen only. The complete code is shown in Listing 14.2. Listing 14.2 Pixel generation of a font display circuit module font-test-gen ( input wire clk, input wire video-on, 5 i n p u t w i r e [9:01 pixel-x , pixel-y , output reg [2:0] rgb-text 1; // signal declaration lo wire [10:0] rom-addr; w i r e [6:01 char-addr ; wire [3:01 row-addr; wire [2:0] bit-addr; w i r e [7:01 f o n t - w o r d ; 15 w i r e font-bit , text-bit-on; // body / / i n s t a n t i a t e f o n t ROM font-rom font-unit 20 (.clk(clk), .addr(rom-addr), .data(font-word)); / / f o n t ROM i n t e r f a c e a s s i g n char-addr = {pixel-y [5:4] , pixel-x [7:311; a s s i g n row-addr = pixel-y [3:0] ; a s s i g n rom-addr = (char-addr , row-addr); 25 a s s i g n bit-addr = pixel-x [2:0] ; assign font-bit = font-word [-bit-addrl ; // "on" region limited to top-left corner a s s i g n text-bit-on = (pixel-x [9:81==O && pixel-y [9:61 ==0) ? font-bit : l'bO; 3u / / r g b m u l t i p l e x i n g c i r c u i t always @* if (-video-on) rgb-text = 3 'b000; // blank else if (text-bit-on) rgb-text = 3'bOlO; // green else rgb-text = 3'bOOO; // black 40 e n d m o d u l e The key part of the code is the font ROM interface. For clarity, we define the following signals for the font ROM, as shown in Figure 14.2: char-addr: 7 bits, the ASCII code of the character row-addr: 4 bits, the row number in a particular font pattern rom-addr: 11 bits, the address of the font ROM; the concatenation of char-addr and row-addr b i t - a d d r : 3 bits, the column number in a particular font pattern f ont-word: 8 bits, a row of pixels of the font pattern specified by rom-addr f o n t - b i t : 1 bit, one pixel of f ont-word specified by b i t - a d d r The connection of these signals follows the diagram in Figure 14.2. The routing of the f o n t - b i t signal is done by a multiplexer, coded as an array with a dynamic index: assign font-bit = font-word [-bit-addr] ; Note that a row (i.e., a word) in the font ROM is defined in descending order (i.e., [7 :01 ). Since the screen's x-coordinate is defined in ascending fashion, in which the number increases from left to right, the order of the retrieved bits must be reversed. This is achieved by the " operator in the expression. We need to combine the synchronization circuit and create the top-level description. The HDL code is shown in Listing 14.3. Listing 14.3 Top-level description of a font display circuit module font-test-top ( input wire clk, reset, output wire hsync, vsync , 5 output wire [2:0] rgb ); // signal declaration w i r e [9:01 pixel-x , pixel-y ; lo wire video-on , pixel-tick; reg [2:01 rgb-reg; w i r e [ 2 :01 r g b - n e x t ; // body 1s // i n s t a n t i a t e vga s y n c c i r c u i t TEXT GENERATION 347 vga-sync vsync-unit (. clk(clk), . reset (reset), .hsync (hsync) , .vsync (vsync), .video-on(video-on), .p-tick(pixe1-tick), .pixel-x(pixe1-x), .pixel-y(pixe1-y)); 20 // font generation c i r c u i t font-test-gen font-gen-unit (.clk(clk), .video-on(video-on), .pixel-x(pixe1-x), .pixel-y(pixe1-y), .rgb-text(rgb-next)); // rgb buffer 15 always @(posedge c l k ) if ( p i x e l - t i c k ) rgb-reg <= rgb-next ; // output assign rgb = rgb-reg; 10 endmodule There is subtle timing issue in this circuit. Because of the block RAM implementation, the font ROM's output suffers a one-clock-cycle delay. However, since the p i x e l - t i c k signal is asserted every two clock cycles, the p i x e l x signal remains unchanged within this interval and the corresponding bit (i.e., f ont-bit) can be retrieved properly. The rgb multiplexing circuit can use this data, and the desired value is stored to the r g b ~ e rgegister in a timely manner. 14.2.5 Font scaling In the tile-mapped scheme, we can scale a tile pattern to larger sizes by "enlarging" the screen pixels. For example, we can scale the 8-by-16 font to a 16-by-32 font by enlarging the original pixel four times (i.e., expanding one pixel to four pixels). To perform the scaling, we just need to shift pixel coordinates to the right 1 bit and discard the LSBs of the p i x e l x and pixel-y signals. This can best be explained by an example. Let us repeat the previous font displaying circuit with enlarged 16-by-32 fonts. The screen can now be treated as a grid of 40-by-1 5 tiles. The new font addresses become assign r o w - a d d r = pixel-y [4: 11 ; assign b i t - a d d r = p i x e l - x [3:11 ; assign c h a r - a d d r = {pixel-y [6:5] , p i x e l - x [8:41); The first two statements imply that the same f o n t - b i t value will be obtained when p i x e l 2 [Ol and pixel-y C01 are "OO", "01","1O", and " 1 1",and this effectively enlarges the original pixel to four pixels. The text-bit-on condition also needs to be modified to accommodate a larger region: assign t e x t - b i t - o n = ( p i x e l - x [ 9 1 = = O && p i x e l - y [9:71 = = 0 ) ? font-bit : l'bO; We can apply this scheme to scale up the font even further. Note that the enlarged fonts may appear jagged because they simply magnify the original pattern and introduce no new detail. Figure 14.3 Text generation circuit with tile memory. 14.3 FULL-SCREEN TEXT DISPLAY A full-screen text display, as the name indicates, uses the entire screen to display text characters. The character generation circuit now contains a tile memory that stores the ASCII code of each tile. The design of the tile memory is similar to the video memory of the bit-mapped circuit in Section 13.5. For easy memory access, we can concatenate the xand y-coordinates of a tile to form the address. This translates to 12 bits for the 80-by-30 (i.e., 27-by-25)tile screen. Since each tile contains a 7-bit ASCII code, a 212-by-7 memory module is required. A synchronous dual-port RAM can be used for this purpose. A circuit with tile memory is shown in Figure 14.3. Because accessing tile memory requires another clock cycle, retrieving a font pattern is now increased to two clock cycles. This prolonged delay introduces a subtle timing problem. Because the p i x e l x signal is updated every two clock cycles, its value has incremented when the f ont-word value becomes available. Thus, when the bit is retrieved by the statements a s s i g n b i t - a d d r = p i x - x 2 - r e g [2:0] ; assign font-bit = f ont-word C-bit-addrl ; the incremented bit-addr is used and an incorrect font bit will be selected and routed to the output. One way to overcome the problem is to pass the p i x e l x signal through two buffers and use this delayed signal in place of the p i x e l x signal. We use a simple circuit to demonstrate the design of the full-screen tile-mapped scheme. The circuit reads an ASCII code from a 7-bit switch and places it in the marked location of the 80-by-30 tile screen. The conceptual diagram is shown in Figure 14.3. A cursor is included to mark the current location of entry, where the color is reversed. The c u r s o r block keeps track of the current location of the cursor. The circuit uses three pushbutton switches for control. Two buttons move the cursor right and down, respectively. The third button is for the write operation. When it is pressed, the current value of the 7-bit switch is written to the tile memory. The HDL code is shown in Listing 14.4. FULL-SCREENTEXT DISPLAY 349 Listing 14.4 Pixelgenerationofa full-screentext display module text-screen-gen ( i n p u t w i r e clk , reset , input wire video-on, 5 i n p u t w i r e [2:0] btn, i n p u t w i r e [6:01 s w , i n p u t w i r e [9 :01 pixel-x , pixel-y , o u t p u t r e g [2:01 text-rgb 1; 10 // signal declaration // f o n t ROM w i r e [lo:01 rom-addr ; w i r e [6:01 char-addr ; I5 w i r e [3:0] row-addr; w i r e [2:01 bit-addr ; w i r e [7:0] font-word; w i r e fout-bit ; // t i l e RAM 20 w i r e we; w i r e [I1 :01 addr-r , addr-w ; w i r e [6:01 din, dout; / / 80-by-30 t i l e map l o c a l p a r a m MAX-X = 80; 25 l o c a l p a r a m MAX-Y = 30; // cursor r e g [6:01 cur-x-reg ; w i r e [6:01 cur-x-next ; r e g [4:01 cur-y-reg ; 30 w i r e [4:01 cur-y-next ; w i r e move-x-tick , move-y-tick , cursor-on; // delayed pixel count r e g 19:01 pix-xi-reg , pix-y 1-reg ; r e g [9:01 pix-x2_reg, pix-y2-reg; 35 / / o b j e c t o u t p u t s i g n a l s w i r e [2 :01 fout-rgb , fout-rev-rgb ; // body // instantiate debounce c i r c u i t for two buttons 40 debounce deb-unit0 ( . clk(clk), .reset (reset), . sw(btn[Ol), .db-level(), .db-tick(move-x-tick)); debounce deb-unit1 ( . cik(clk), .reset(reset), . sw(btn [I]), . db-level() , . db-tick (move-y-tick)) ; / / i n s t a n t i a t e f o n t ROM font-rom font-unit (.clk(clk), .addr(rom-addr), .data(font-word)); / / i n s t a n t i a t e d u a l - p o r t v i d e o RAM ( 2 - 1 2 - b y - 7 ) 50 xilinx-dual-port-ram-sync # ( . ADDR-WIDTH (12) , . DATA-WIDTH (7) ) video-ram ( . clk(clk), . we(we), . addr-a(addr-w), . addr-b(addr-r), 15 // registers a l w a y s @ ( p o s e d g e clk) begin cur-x-reg <= cur-x-next ; cur-y-reg <= cur-y-next ; pix-xl-reg <= pixel-x ; pix-x2-reg <= pix-xl-reg; pix-yl-reg <= pixel-y; pix-y2-reg <= pix-yl-reg ; end 65 // t i l e RAMwrite a s s i g n addr-w = {cur-y-reg , cur-x-reg); a s s i g n we = btn C21 ; a s s i g n din = sw; / / t i l e RAM r e a d 70 / / u s e n o n d e l a y e d c o o r d i n a t e s t o f o r m t i l e RAM a d d r e s s a s s i g n addr-r = {pixel-y [8:41 , ~ i x e l - xC9:31); a s s i g n char-addr = dout; // f o n t ROM a s s i g n row-addr = pixel-y [3:0] ; 75 a s s i g n rom-addr = {char-addr , row-addr); // use delayed coordinate to select a bit a s s i g n bit-addr = pix-x2-reg C2:01 ; a s s i g n font-bit = font-word [-bit-addr] ; // new c u r s o r p o s i t i o n RO a s s i g n cur-x-next = (move-x-tick && (cur-x-reg==MAX-X-1)) ? 0 : / / wrap (move-x-tick) ? cur-x-reg + 1 : cur-x-reg; a s s i g n cur-y-next = XI (move-y-tick && (cur-x-reg==MAX-Y-1)) ? 0 : // wrap (move-y-tick) ? cur-y-reg + 1 : cur-y-reg; // object signals // green over black and reversed video for cursor so a s s i g n font-rgb = (font-bit) ? 3'b010 : 3'bOOO; a s s i g n font-rev-rgb = (font-bit) ? 3'bOOO : 3'bOlO; // use delayed coordinates for comparison a s s i g n cursor-on = (pix-y2-reg [8:4]==cur-y-reg) && (pix-x2-reg C9 :31 ==cur-x-reg) ; si / / r g b m u l t i p l e x i n g c i r c u i t always Q* i f ("video-on) text-rgb = 3'bOOO; // blank else i f (cursor-on) text-rgb = font-rev-rgb; else text-rgb = font-rgb ; endmodule The font ROM interface signals are similar to those in Listing 14.2 except that the char-addr is obtained from the read port of the tile memory. To facilitate the font ROM access delay, we create two delayed signals, pixx2-reg and pix-y21eg, from the current x- and y-coordinates, p i x e l x and pixel-y. Note that the undelayed signals, p i x e l x and pixel-y, are used to form the address to access the font ROM, but the delayed signal, pixx2_reg, is used to obtain the font bit. The instantiation and interface of the dual-port tile RAM are similar to those of the video RAM in Listing 13.7. The cursor-on signal is used to identify the current cursor location. The colors of the font pattern are reversed in this location. Because the font bits are delayed by two clocks, we use the delayed coordinates, pixx21eg and pix-y2reg, for comparison. The delayed font bits also introduce one pixel delay for the final rgb signal. This implies that the overall visible portion of the VGA monitor is shifted to the right by one pixel. To correct the problem, we should revise the vga-sync circuit and use the delayed p i x x 2 r e g and pix-y2-reg signals to generate the hsync and vsync signals. Since the shift has little effect on the overall video quality, we do not make this modification. The top-level code combines the text pixel generation circuit and the synchronization circuit and is shown in Listing 14.5. Listing 14.5 Top-level system of a full-screen text display module text-screen-top ( input wire clk, reset, input wire [2:0] btn, 5 input wire [6:01 sw, output wire hsync, vsync, output wire [2:0] rgb 1; I,, // signal declaration w i r e [ 9 : 01 pixel-x , pixel-y ; wire video-on , pixel-tick; reg [2:01 rgb-reg; w i r e [2 :01 rgb-next ; 15 // body // i n s t a n t i a t e vga sjjnc c i r c u i t vga-sync vsync-unit ( . clk(clk), .reset (reset), .hsync (hsync) , .vsync(vsync), .video-on(video-on), .p-tick(pixe1-tick), 20 .pixel-x(pixe1-x), .pixel-y(pixe1-y)); // font generation c i r c u i t text-screen-gen text-gen-unit (.clk(clk), .reset(reset), .video-on(video-on), .btn(btn1, .sw(sw), .pixel-x(pixel-x), 5 .pixel-y(pixe1-y), .text-rgb(rgb-next)); // rgb buffer always @( posedge clk) i f (pixel-tick) rgb-reg <= rgb-next ; 70 // output assign rgb = rgb-reg; endmodule - btn hsync vsync video-on - pixel-x ---. pixel-y > vga-sync t c pixel-x t r - pixel-y hit + ' miss --, btn - graph-still graph-rgb graph-on -btn graph-still -+ hit state-reg -+ miss ----- dinc - > d-clr - m100counter control FSM - ball timer-up > timer-start - > timer pong4raph . dig0 dig1 ball text-rgb text-on pongtext hsync vsync Figure 14.4 Top-level b l o c k diagram o f the complete p o n g game 14.4 THE COMPLETE PONG GAME We create a free-running graphic circuit for the pong game in Section 13.4.3. In this section, we add a text interface to display scores and messages, and design a top-level control FSM that integrates the graphic and text subsystems and coordinates the overall circuit operation. The rules and operations of the complete game are: When the game starts, it displays the text of the rule. After a player presses a button, the game starts. The player scores a point each time hitting the ball with the paddle. When the player misses the ball, the game pauses and a new ball is provided. Three balls are provided in each session. The score and the number of remaining balls are displayed on the top of the screen. Afier three misses, the game is ended and displays the end-of-game message. In the following subsections, we first discuss the text subsystem, graphic subsystem, and auxiliary counters, and then derive a top-level FSM to coordinate and control the overall operation. The conceptual diagram is shown in Figure 14.4. 14.4.1 Text subsystem The text subsystem of the pong game consists of four text messages: THE COMPLETE PONG GAME 353 Figure 14.5 Text of the pong game. Display the score as "Scores : DD" and the number of remaining balls asMBal:l D" in the 16-by-32 font on top of the screen. Display the rule message "Rules: Use two b u t t o n s t o move paddle up o r down. " in the regular font at the beginning of the game. Display the "PONG" logo in the 64-by-128 font on the background. Display the end-of-game message "Game Over" in the 32-by-64 font at the end of the game. A sketch of the first three messages is shown in Figure 14.5. The end-of-game message is overlapped with the rule message and not included. Since these messages use different font sizes and are displayed at different occasions, they cannot be treated as a single screen. We treat each text message as an individual object and generate the on status signal and the font ROM address. For example, the logo message segment is assign l o g o - o n = (pix-y [ 9 : 71 ==2) && (3<=pix-x [ 9 : 61 ) && assign row-addr-1 = pix-y [6:31 ; assign bit-addr-1 = pix-x [5:3] ; always Q* case (pix-x [8:61 ) 3'03: char-addr-1 = 7'h50; 3'04: char-addr-1 = 7'h4f; 3'05: char-addr-1 = 7'h4e; default: char-addr-1 = 7'h47; endcase ( p i x - x 19: 61 < = 6 ) ; // P // 0 // N // G The logo-on signal indicates that the current scan is in the logo region and the corresponding text should be "turned on." The other statements specify the message content and the font ROM connections to generate the scaled 32-by-64 characters. The other three segments are similar. A separate multiplexing circuit examines various on signals and routes one set of addresses to the font ROM. The text subsystem receives the score and the number of remaining balls via the b a l l , dig0, and d i g 1 ports. It outputs the r g b information via the r g b - t e x t port and outputs the on status information via the 4-bit t e x t - o n port, which is the concatenation of four individual on signals. The complete code is shown in Listing 14.6. 354 VGA CONTROLLER II: TEXT Listing 14.6 Text subsystem for the pong game module pong-text ( input wire clk, i n p u t w i r e [1:01 ball, 5 i n p u t w i r e [3:0] dig0, digl, i n p u t w i r e [9:01 pix-x, pix-y, o u t p u t w i r e [3:01 text-on, o u t p u t r e g [2:01 text-rgb 1; 10 // signal declaration w i r e 110:01 rom-addr ; r e g [6 : 01 char-addr , char-addr-s , char-addr-1 , char-addr-r, char-addr-o; I5 r e g [3:0] row-addr; w i r e C3:01 row-addr-s , row-addr-1 , row-addr-r , row-addr-o ; r e g [2:01 bit-addr; w i r e [2:0] bit-addr-s, bit-addr-1,bit-addr-r, bit-addr-o; w i r e [7:01 font-word; 20 w i r e font-bit , score-on, logo-on, rule-on, over-on; w i r e C7:01 rule-rom-addr ; / / i n s t a n t i a t e f o n t ROM font-rom font-unit (.clk(clk), .addr(rom-addr). .data(font-word)); // score region // - display two-digit s c o r e , ball on top l e f t 30 // - scale to 16-by-32 font // - l i n e 1 , 16 chars: "Score:DD Bal1:D" ,, a s s i g n score-on = (pix-y [ 9 : 51 ==0) && (pix-x [9:41 <16) ; a s s i g n row-addr-s = pix-y [4:11 ; 35 a s s i g n bit-addr-s = pix-x [3:11 ; always Q* c a s e (pix-x [7:41) 4'hO: char-addr-s = 7'h53; // S 4'hl: char-addr-s = 7'h63; // c 4'h2: char-addr-s = 7'h6f; // o 4'h3: char-addr-s = 7'h72; // r 4'h4: char-addr-s = 7jh65; // e 4'h5: char-addr-s = 7'h3a; // : 4'h6: char-addr-s = {3'b011, digl); // d i g i t 10 4'h7: char-addr-s = C3' b011, dig0); // d i g i t 1 4'h8: char-addr-s = 7'hOO; // 4'h9: char-addr-s = 7'hOO; // 4'ha: char-addr-s = 7'h42; // B 4'hb: char-addr-s = 7'h61; // a 4'hc: char-addr-s = 7'h6c; / / 1 4'hd: char-addr-s = 7'h6c; // 1 4'he: char-addr-s = 7'h3a; // : THE COMPLETE PONG GAME 355 4'hf : char-addr-s = {5'b01100, ball); endcase // logo region: // - d i s p l a y l o g o "PONG" a t t o p c e n t e r // - used as background // - scale to 64-by-128 font a s s i g n logo-on = (pix-y[9:71==2) && (3<=pix-x [9:61) && (pix-x [9:61 <=6) ; a s s i g n row-addr-1 = pix-y [6:31 ; a s s i g n bit-addr-1 = pix-x [5:31 ; 65 a l w a y s Q * c a s e (pix-x [8:61 ) 3'03: char-addr-1 = 7'h50; // P 3'04: char-addr-1 = 7jh4f; // 0 3'05: char-addr-1 = 7lh4e; / / N 70 d e f a u l t : char-addr-1 = 7'h47; // G endcase // rule region // - display rule (4-by-16 ti1es)on center 75 // - rule t e x t : // Rule : // Use two buttons // to move paddle // up and down a s s i g n rule-on = (pix-x [9:71 ==2) && (pix-y [9:61==2) ; a s s i g n row-addr-r = pix-y [3:01 ; a s s i g n bit-addr-r = pix-x [2:01 ; a s s i g n rule-rom-addr = {pix-y [5:4] , pix-x [6:31); 85 always Q* c a s e (rule-rom-addr) // row 1 6'hOO: char-addr-r = 7'h52; // R 6'hOl: char-addr-r = 7'h55; // U 6'h02: char-addr-r = 7'h4c; // L 6'h03: char-addr-r = 7'h45; // E 6'h04: char-addr-r = 7'h3a; // : 6'h05: char-addr-r = 7'hOO; // 6'h06: char-addr-r = 7'hOO; // 6'h07: char-addr-r = 7'hOO; / / 6'h08: char-addr-r = 7'hOO; // 6'h09: char-addr-r = 7jh00; // 6'hOa: char-addr-r = 7'hOO; // 6'hOb: char-addr-r = 7'hOO; // 6'hOc: char-addr-r = 7'hOO; // 6'hOd: char-addr-r = 7'hOO; // 6'hOe: char-addr-r = 7'hOO; // 6'hOf: char-addr-r = 7'hOO; // // row 2 6'hlO: char-addr-r = 7'h55; // U 6'hll: char-addr-r = 7'h73; // s 6'h12: char-addr-r = 7'h65; // e 6'h13: char-addr-r = 7'hOO; // 6'h14: char-addr-r = 7'h74; // t 6'h15: char-addr-r = 7'h77; // w 6'h16: char-addr-r = 7'h6f ; / / o 6'h17: char-addr-r = 7'hOO; / / 6'h18: char-addr-r = 7'h62; / / b 6'h19: char-addr-r = 7'h75; // u 6'hla: char-addr-r = 7'h74; / / t 6'hlb: char-addr-r = 7'h74; / / t 6'hlc: char-addr-r = 7'h6f ; // o 6'hld: char-addr-r = 7'h6e; // n 6'hle: char-addr-r = 7'h73; // s 6'hlf: char-addr-r = 7'hOO; // // row 3 6'h20: char-addr-r = 7'h74; // t 6'h21: char-addr-r = 7'h6f; // o 6'h22: char-addr-r = 7'hOO; // 6'h23: char-addr-r = 7'h6d; // m 6'h24: char-addr-r = 7'h6f ; // o 6'h25: char-addr-r = 7'h76; // v 6'h26: char-addr-r = 7'h65; // e 6'h27: char-addr-r = 7'hOO; // 6'h28: char-addr-r = 7'h70; // p 6'h29: char-addr-r = 7'h61; // a 6'h2a: char-addr-r = 7'h64; / / d 6'h2b: char-addr-r = 7'h64; // d 6'h2c: char-addr-r = 7'h6c; / / I 6'h2d: char-addr-r = 7'h65; / / e 6' h2e : char-addr-r = 7'hOO; / / 6'h2f: char-addr-r = 7'hOO; / / // row 4 6'h30: char-addr-r = 7'h75; // u 6'h31: char-addr-r = 7'h70; // p 6'h32: char-addr-r = 7'hOO; // 6'h33: char-addr-r = 7'h61; // a 6'h34: char-addr-r = 7'h6e; // n 6'h35: char-addr-r = 7'h64; // d 6'h36: char-addr-r = 7'hOO; // 6'h37: char-addr-r = 7'h64; // d 6'h38: char-addr-r = 7'h6f ; // o 6'h39: char-addr-r = 7'h77; / / w 6'h3a: char-addr-r = 7jh6e; // n 6'h3b: char-addr-r = 7'h2e; // . 6'h3c: char-addr-r = 7'hOO; // 6'h3d: char-addr-r = 7'hOO; // 6'h3e: char-addr-r = 7'hOO; // 6'h3f: char-addr-r = 7 'h00; / / endcase ,, // game over region // - d i s p l a v "Game Over" a t c e n t e r THE COMPLETE PONG GAME 357 // - scale to 32-by-64 fonts 160 // a s s i g n over-on = (pix-y [9:6]==3) && (5<=pix-x [9:51 ) && (pix-x [9:51 <=I31 ; a s s i g n row-addr-o = pix-y [5:21 ; a s s i g n bit-addr-o = pix-x [4:2] ; 16s always Q* c a s e (pix-x [a:51 ) 4'h5: char-addr-o = 7'h47; / / G 4'h6: char-addr-o = 7'h61; / / a 4'h7: char-addr-o = 7'h6d; / / m 4'h8: char-addr-o = 7'h65; // e 4'h9: char-addr-o = 7'hOO; // 4'ha: char-addr-o = 7'h4f; // 0 4'hb: char-addr-o = 7'h76; // v 4'hc: char-addr-o = 7'h65; // e d e f a u l t : char-addr-o = 7'h72; // r endcase ,, // mux f o r f o n t ROM a d d r e s s e s and r g b // ISU always Q* begin text-rgb = 3'b110; i f (score-on) begin // background, yellow char-addr = char-addr-s; row-addr = row-addr-s; bit-addr = bit-addr-s; i f (font-bit) text-rgb = 3'bOOl; end e l s e i f (rule-on) begin char-addr = char-addr-r; row-addr = row-addr-r; bit-addr = bit-addr-r ; i f (font-bit) text-rgb = 3jb001; end e l s e i f (logo-on) begin char-addr = char-addr-1; row-addr = row-addr-1; bit-addr = bit-addr-1; i f (font-bit) text-rgb = 3'b011; end e l s e // game o v e r begin char-addr = char-addr-o ; row-addr = row-addr-o; bit-addr = bit-addr-o; i f (font-bit) text-rgb = 3'bOOl; end 215 end a s s i g n text-on = (score-on, logo-on, rule-on, over-on}; // // f o n t rom i n t e r f a c e assign rom-addr = (char-addr, row-addr}; assign font-bit = font-word [-bit-addr] ; endmodule The structure of each segment is similar. Because the messages are short, they are coded with the regular ROM template. Since no clock signal is used, a distributed RAM or combinational logic should be inferred. Generation of the two-digit score depends on the two 4-bit external signals, digO and d i g l . Note that the ASCII codes for the digits 0, 1, . . . , 9, are 3Ol6, 3 l I 6 ,. . . , 3gI6. We can generate the char-addr signal simply by concatenating "011" in front of digO and d i g l . 14.4.2 Modified graphic subsystem To accommodate the new top-level controller, the graphic circuit in Section 13.4.3 requires several modifications: Add a g r a - s t i l l (for "still graphics") control signal. When it is asserted, the vertical bar is placed in the middle and the ball is placed at the center of the screen without movement. Add the h i t and miss status signals. The h i t signal is asserted for one clock cycle when the paddle hits the ball. The m i s s signal is asserted when the paddle misses the ball and the ball reaches the right border. Add a graph-on signal to indicate the on status of the graph subsystem. The modified portion of the code is shown in Listing 14.7. Listing 14.7 Modified portion of a graph subsystem for the pong game // new b a l l p o s i t i o n assign ball-x-next = (gra-still) ? MAX-X/2 : (refr-tick) ? ball-x-reg+x-delta-reg : 5 ball-x-reg ; assign ball-y-next = (gra-still) ? MAX-Y/2 : (refr-tick) ? ball-y-reg+y-delta-reg : ball-y-reg ; // new b a l l v e l o c i t y 10 a l w a y s Q * begin hit = 1'bO; miss = l'bO; x-delta-next = x-delta-reg; y-delta-next = y-delta-reg; if (gra-still) // i n i t i a l v e l o c i t y THE COMPLETE PONG GAME 359 begin x-delta-next = BALL-V-N ; y-delta-next = BALL-V-P; 20 end e l s e i f (ball-y-t < 1) // r e a c h t o p y-delta-next = BALL-V-P; e l s e i f (ball-y-b > (MAX-Y-1)) // r e a c h b o t t o m y-delta-next = BALL-V-N; 3 e l s e i f (ball-x-1 <= WALL-X-R) // r e a c h w a l l x-delta-next = BALL-V-P; // bounce back e l s e i f ((BAR-X-L <=ball-x-r) && (ball-x-r <=BAR-X-R) && (bar-y-t <=ball-y-b) && (ball-y-t <=bar-y-b)) begin 30 // reach x of right bar and hit , ball bounce back x-delta-next = BALL-V-N; hit = l'bl; end e l s e i f (ball-x-r>MAX-X) // reach r i g h t border is miss = l J b l ; // a miss end a s s i g n graph-on = wall-on I bar-on I rd-ball-on; ... 14.4.3 Auxiliary counters The top-level design requires two small utility modules, m100-counter and timer,to facilitate the counting. The m100-counter module is a two-digit decade counter that counts from 00 to 99 and is used to keep track of the scores of the game. Two control signals, d-incand d-clr,increment and clear the counter, respectively. The code is shown in Listing 14.8. Listing 14.8 Two-digit decade counter module m100-counter ( input wire clk, reset, input wire d-inc, d-clr, 5 o u t p u t w i r e [3:01 dig0, dig1 1; // signal declaration r e g [3:01 dig0-reg , digl-reg , dig0-next , digl-next ; 10 // r e g i s t e r s a l w a y s Q ( p o s e d g e clk , p o s e d g e reset ) i f (reset) begin I5 digl-reg <= 0; dig0-reg <= 0; end else begin d i g l - r e g <= d i g l - n e x t ; d i g 0 - r e g <= dig0-next ; end // next-state logic 2: always Q* begin dig0-next = dig0-reg ; digl-next = digl-reg; i f (d-clr) begin dig0-next = 0; digl-next = 0; end else i f (d-inc) i f (dig0-reg==9) begin dig0-next = 0; i f (digl-reg==9) digl-next = 0; else digl-next = digl-reg + 1; end e l s e // digO not 9 dig0-next = dig0-reg + 1; 45 end // output assign digO = dig0-reg; assign dig1 = digl-reg; The timer module uses the 60-Hz tick, timer-tick, to generate a 2-second interval. Its purpose is to pause the video for a small interval between transitions of the screens. It starts counting when the timer-start signal is asserted and activates the timer-up signal when the 2-second interval is up. The code is shown in Listing 14.9. Listing 14.9 Two-second timer module timer ( input wire clk, reset, input wire timer-start , timer-tick, I output wire timer-up ); // signal declaration reg [6:0] timer-reg, timer-next; 10 // r e g i s t e r s always Q(posedge clk, posedge reset) i f (reset) timer-reg <= 7 ' b l l l l l l l ; else timer-reg <= timer-next ; // next-state logic always Q* 20 i f (timer-start) timer-next = 7'blllllll; e l s e i f ((timer-tick) && (timer-reg ! = 0)) timer-next = timer-reg - 1; else 25 timer-next = timer-reg; // output assign timer-up = (timer-reg==O); endmodule 14.4.4 Top-level system The top-level system of the pong game consists of the previously designed modules, including a video synchronization circuit, graphic subsystem, text subsystem, and utility counters, as well as a control FSM and an rgb multiplexing circuit. The block diagram is shown in Figure 14.4. The control FSM monitors overall system operation and coordinates the activities of the text and graphic subsystems. Its ASMD chart is shown in Figure 14.6. The FSM has four states and operates as follows: Initially, the FSM is in the newgame state. The game starts when a button is pressed and the FSM moves to the play state. In the play state, the FSM checks the h i t and m i s s signals continuously. When the h i t signal is activated, the d-inc signal is asserted for one clock cycle to increment the score counter. When the m i s s signal is asserted, the FSM activates the 2-second timer, decrements the number of the balls by 1, and examines the number ofremaining balls. Ifit is zero, the game is ended and the FSM moves to the over state. Otherwise, the FSM moves to the newball state. The FSM waits in the newball state until the 2-second interval is up (i.e., when the timer-up signal is asserted) and a button is pressed. It then moves to the p l a y state to continue the game. The FSM stays in the over state until the 2-second interval is up. It then moves to the newgame state for a new game. The rgb multiplexing circuit routes the t e x t x g b or g r a p h ~ g bsignals to output according to the text-on and graphic-on signals. The key segment is always Q* i f (-video-on) rgb-next = "000"; // blank the e d g e / r e t r a c e else // d i s p l a y s c o r e , r u l e , o r game o v e r i f ( text_on[3] I1 ((state-reg==newgame) && t e x t - o n [I] ) I I ((state-reg==over) && text-onC01) ) rgb-next = text-rgb; e l s e i f (graph-on) // display graph default : gra-still = I .................................. .................................. Figure 14.6 ASMD chart of the pong controller. rgb-next = graph-rgb ; e l s e i f (text-on[21) / / d i s p l a y l o g o rgb-next = text-rgb ; else rgb-next = 3'b110; // y e l l o w background // output a s s i g n rgb = rgb-reg; The text-onC31 signal is for the scores, which is always displayed. The text-onC11 signal is for the rule, which is displayed only when the FSM is in the newgame state. Similarly, the end-of-game message, whose status is indicated by the text-on [01 signal, is displayed only when the FSM is in the over state. The logo, whose status is indicated by the t e x t - o n [21 signal, is used as part of the background and is displayed only when no other on signal is asserted. The complete code is shown in Listing 14.10. Listing 14.10 Top-level system for the pong game module pong-top ( input wire clk, reset, i n p u t w i r e [1:01 btn, 5 o u t p u t w i r e hsync , vsync , o u t p u t w i r e [2:0] rgb 1; // symbolic s t a t e declaration la l o c a l p a r a m [1:01 newgame = 2 ' b00, play = 2'b01, newball = 2'b10, over = 2'bll; I5 // signal declaration r e g [1:0] state-reg, state-next; w i r e [9 :0] pixel-x , pixel-y ; wire video-on, pixel-tick, graph-on, hit, miss; 20 w i r e [3:0] text-on; w i r e [2:01 graph-rgb , text-rgb ; r e g [2:01 rgb-reg , rgb-next ; w i r e [3:0] dig0, digl; r e g gra-still , d-inc , d-clr , timer-start ; 2s wire timer-tick , timer-up; r e g [I :01 ball-reg , ball-next ; // instantiation ......................................................... // instantiate video synchronization unit vga-sync vsync-unit ( . clk(clk), .reset(reset), . hsync(hsync), . vsync(vs~nc), .video-on(video-on), .p-tick(pixe1-tick), 35 .pixel-x(pixe1-x), .pixel-y(pixe1-y)); // i n s t a n t i a t e text module pong-text text-unit (. clk(clk1, .pix-x(pixe1-x), .pix-y(pixe1-y), .digO(digO), .digl(digl), .ball(ball-reg), .text-on(text-on), .text-rgb(text-rgb)); // i n s t a n t i a t e graph module pong-graph graph-unit (.clk(clk), .reset(reset), .btn(btn), ~r .pix-x (pixel-x) , .pix-y (pixel-y) , .gra-still(gra-still), .hit(hit), .miss(miss), . graph-on (graph-on) , .graph-rgb (graph-rgb) ) ; // i n s t a n t i a t e 2 sec timer // 60 Hz t i c k to a s s i g n t i m e r - t i c k = ( p i x e l - x = = O ) && ( p i x e l - y = = 0 ) ; timer timer-unit ( . c l k ( c l k ) , . r e s e t ( r e s e t ) , .timer-tick(timer-tick), .timer-start(timer-start), .timer-up(timer-up)); // instantiate 2-digit decade counter 5 m100-counter counter-unit (. clk(c1k) , .reset ( r e s e t ) , .d-inc (d-inc) , .d-clr (d-clr) , .dig0 (dig01 , .dig1 (digl)) ; ......................................................... / / FSMD ......................................................... / / FSMD s t a t e & d a t a r e g i s t e r s always Q (posedge clk , posedge reset) if (reset) begin s t a t e - r e g <= newgame ; b a l l - r e g <= 0 ; r g b - r e g <= 0 ; end else begin s t a t e - r e g <= s t a t e - n e x t ; b a l l - r e g <= b a l l - n e x t ; if (pixel-tick) rgb-reg <= rgb-next ; 7: end / / FSMD n e x t - s t a t e l o g i c always Q* begin gra-still = l'bl; timer-start = l'bO; d-inc = l'bO; d-clr = l'bO; state-next = state-reg; ball-next = ball-reg ; case (state-reg) newgame : begin ball-next = 2 ' b l l ; // three balls d-clr = l'bl; // clear score i f ( b t n ! = 2'bOO) // button pressed begin state-next = play; ball-next = ball-reg - 1; end end play : begin g r a - s t i l l = l'bO; // animated screen if (hit) d-inc = l ' b l ; // increment score else if (miss) begin if (ball-reg==O) state-next = over; else state-next = newball ; t i m e r - s t a r t = l ' b l ; // 2 sec timer ball-next = ball-reg - 1; end end newball : // wait for 2 sec and until button pressed i f ( t i m e r - u p && ( b t n != 2'bOO)) state-next = play; over : // wait f o r 2 sec to d i s p l a y game over i f ( timer-up) s t a t e - n e x t = newgame ; endcase 120 end ......................................................... // rgb multiplexing c i r c u i t ......................................................... always Q* 125 if (-video-on) rgb-next = "000"; // blank the e d g e / r e t r a c e e1se // d i s p l a y s c o r e , r u l e , or game over if (text-onC31 I I ( ( s t a t e - r e g = = n e w g a m e ) && t e x t - o n Cll I I / / ( ( s t a t e - r e g = = o v e r ) && t e x t - o n [O] ) rgb-next = text-rgb; else i f (graph-on) // display graph rgb-next = graph-rgb ; else if (text-on [21) // display logo rgb-next = text-rgb; else rgb-next = 3'b110; // yellow background // output I40 assign rgb = rgb-reg; endmodule rule 14.5 BIBLIOGRAPHIC NOTES Several other character fonts are available. Rapid Prototyping of Digital Systems by James 0.Hamblen et al. uses a compact 64-character 8-by-8 font set. The tile-mapped scheme is not limited to the text display. It is widely used in the early video game. The article "Computer Graphics During the 8-Bit Computer Game Era" by Steven Collins (ACMSIGGRAPH, May 1998)provides a comprehensive review of the history and design techniques of the tile-based game. 14.6 SUGGESTED EXPERIMENTS 14.6.1 Rotating banner A rotating banner on the monitor screen moves a line from right to left and then wraps around. It is similar to the Window's Marquee screen saver. Let the text on the banner be "Hello, FPGA World." The banner should be displayed in four different font sizes and can travel at four different speeds. The font size and speed are controlled by four switches. Derive the HDL description and then synthesize and verify operation of the circuit. 14.6.2 Underline for the cursor The full-screen text display circuit in Section 14.3uses reversed color to indicate the current cursor location. Modify the design to use an underline to indicate the cursor location. Derive the HDL description and then synthesize and verify operation of the circuit. 14.6.3 Dual-mode text display It is sometimes better for text to be displayed on a "vertical" screen. This can be done by turning the monitor 90 degrees and resting it on its side. Design this circuit as follows: 1. Modify the full-screen text display circuit in Section 14.3 for a vertical screen. 2. Merge the normal and vertical designs to create a "dual-mode" text display. Use a switch to select the desired mode. 3. Derive the HDL description and then synthesize and verify operation of the circuit. 14.6.4 Keyboard text entry Instead of switches and buttons, it is more natural to use a keyboard to enter text. We can use the four arrow keys to move the cursor and use the regular keys to enter the characters. Use the keyboard interface discussed in Section 9.4 to design the new circuit. Derive the HDL description and then synthesize and verify operation of the circuit. 14.6.5 UART terminal The UART terminal receives input from the UART port and displays the received characters on a monitor. When connected to the PC's serial port, it should echo the text on Window's HypterTerminal. The detailed specifications are: A cursor is used to indicate the current location. The screen starts a new line when a "carriage return" code (Od16)is received. pattern code 00 01 11 10 (a) Tile patterns - sampledvalues 0 0 0 1 1 1 1 0 0 0 0 (b) Encoding of sampled values Figure 14.7 Tile patterns and encoding of a square wave A line wraps around (i.e., starts a new line) after 80 characters. When the cursor reaches the bottom of the screen (i.e., the last line), the first line will be discarded and all other lines move up (i.e., scroll up) one position. Derive the HDL description and then synthesize and verify operation of the circuit. 14.6.6 Square-wave display We can draw a square wave by using the four simple tile patterns shown in Figure 14.7(a). Follow the procedure of a full-screen text display in Section 14.3 to design a full-screen wave editor: 1. Let the tile size be 8 columns by 64 rows. Create a pattern ROM for the four patterns. 2. Calculate the number of tiles on a 640-by-480 resolution screen and derive the proper configuration for the tile memory. 3. Use three pushbuttons for control and a 2-bit switch to enter the pattern. 4. Derive the HDL description and then synthesize and verify operation of the circuit. 14.6.7 Simple four-trace logic analyzer A logic analyzer displays the waveforms of a collection of digital signals. We want to design a simple logic analyzer that captures the waveforms of four input signals in "freerunning" mode. Instead of using a trigger pattern, data capture is initiated with activation of a pushbutton switch. For simplicity, we assume that the frequencies of the input waveform are between 10 kHz and 100 kHz. The circuit can be designed as follows: 1. Use a sampling tick to sample the four input signals. Make sure to select a proper rate so that the desired input frequency range can be displayed properly on the screen. 2. For a point in the sampled signal, its value can be encoded as a tile pattern by including the value of the previous point. For example, if the sampled sequence of one signal is "00001 1 1 1000", the tile patterns become "00 00 00 01 1l 11 1l 10 00 OO", as shown in Figure 14.7(b). 3. Follow the procedure of the preceding square-wave experiment to design the tile memory and video interface to display the four waveforms being stored . 4. Derive the HDL description and then synthesize the circuit. To verify operation of the circuit, we can connect four external signals via headers around the prototyping board. Alternatively, we can create a top-level test module that includes a 4-bit counter (say, a mod-10 counter around 50 kHz) and the logic analyzer, resynthesize the circuit, and verify its operation. 14.6.8 Complete two-player pong game The free-running two-player pong game is described in Experiment 13.7.6. Follow the procedure of the pong game in Section 14.4 to derive the complete system. This should include the design of a new text display subsystem and the design of a top-level FSM controller. Derive the HDL description and then synthesize and verify operation of the circuit. 14.6.9 Complete breakout game The free-running breakout game is described in Experiment 13.7.7. Follow the procedure of the pong game in Section 14.4 to derive the complete system. This should include the design of a new text display subsystem and the design of a top-level FSM controller. Derive the HDL description and then synthesize and verify operation of the circuit. PART Ill PICOBLAZE MICROCONTROLLERX~LINXS P E C ~ F ~ C This Page Intentionally Left Blank CHAPTER 15 PICOBLAZE OVERVIEW 15.1 INTRODUCTION The PicoBlaze processor is a compact 8-bit microcontroller core for Xilinx FPGA devices. It is provided as a cell-level HDL description (which is known as so3 core) and can be synthesized along with other logic. PicoBlaze is optimized for efficiency and occupies only about 200 logic cells, which amount to less than 5% of the resources of a 3S200 device. While not intended as a high-performance processor, it is compact and flexible and can be used for simple data processing and control, particularly for non-time-critical "housekeeping" and 110 operations. The PicoBlaze processor can easily be integrated into a larger system and adds another dimension of flexibility in an FPGA-based design. Although the detailed coverage of assembly language programming and microcontrollers is beyond the scope ofthis book, this part provides a comprehensive overview of PicoBlaze's organization and instruction set, and illustrates the general assembly program development and 110 interface through a set of examples. We review PicoBlaze's organization and instruction set in this chapter, introduce assembly language programming in Chapter 16, and discuss the general I10 interface and interrupt interface in Chapters 17 and 18. FPGA Prototyping by Verilog Examples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons. Inc. 15.2 CUSTOMIZED HARDWARE AND CUSTOMIZED SOFTWARE 15.2.1 From special-purpose FSMD to general-purpose microcontroller The RT-level design and FSMD discussed in Chapter 6 provide a general methodology to convert a sequential algorithm to customized hardware. The rearranged block diagram is shown in Figure 15.l(a). In an FSMD, all components, including the number of registers, the routing of registers' input and output, the number and types of functional units, and the control FSM, are tailored to the target application. The data path may contain multiple function units and multiple routing paths, as shown in the diagram. An alternative is to keep the same hardware but use customizedsoftware for different applications. The transformation can be done as follows. First, we can replace the customized data path with a fixed configuration, as shown at the top of Figure 15.1(b). The data registers and customized routing networks are replaced by a register file, which has a fixed number of registers and contains only two read ports and one write port. The customized function units are replaced with an ALU (arithmetic and logic unit), which can only perform a set of predefined functions. The data path can now perform RT operations in the following format only: r d t r l op r 2 where ri,1-2,and r d are the addresses of two source registers and one destination register, and op is one of the available ALU functions. Second, we can replace the customized FSM with a programmable state machine, as shown at the bottom of Figure 15.l(b). Recall that operation of an FSM consists of three parts: The state register keeps track of the current state. The output logic activates certain output signals according to the current state. The next-state logic determines the new state. The programmable state machine modifies these operations as follows: It replaces the state register with the program counter. The content of the program counter represents the current state of the control path. In an FSM, each state activates certain output signals to control operation of the data path. The programmable state machine encodes these output patterns into instructions and stores them in a memory module, known as program memory or instruction memory. A memory address corresponds to a state (i.e., a value) of the program counter. During execution, the instruction pointed to by the program counter is retrieved from memory and decoded to generate the control signals. The instruction memory and decoding logic function as a sophisticated output logic circuit. In an FSM, there is no limitation on where to go next. From a given state, the FSM can check the input condition and move to one of many possible next states. In a programmable state machine, the next state is usually the value of the current state plus 1 (i.e., the program counter is incremented by l), which reflects the nature of the sequential execution. The sequential execution may be altered only by several special instructions, such as ajump instruction, in which the program counter is loaded with a different value. The incrementor and associated multiplexing logic function as a simple next-state logic circuit. After we replace the data path with a register file and an ALU and replace the dedicated FSM with a programmable state machine, customizing the system corresponds to developing a new sequence of instructions (i.e., developing a software program) and loads the CUSTOMIZED HARDWARE AND CUSTOMIZED SOFTWARE 373 --* -* - + 4 + rout data rout 4 functional -ing + registers + -ing units -- .......... 4 ctrl next- 4 ctrl state register 4 i ctrl status ctrl A .........i logic (a) Block diagram o f an FSMD replace data registersand routing redace fuktional units ctrl ctrl flag replace next-state logic replace state register replace output logic (b) Simplified block diagram o f a microcontroller Figure 15.1 Diagrams of an FSMD and a microcontroller. 374 PICOBLAZE OVERVIEW instructions to the instruction memory. The organization of the FSMD is now the same for different applications and becomes ageneral-purpose hardware platform. The platform constitutes the basic skeleton of the PicoBlaze microcontroller. 15.2.2 Application of microcontroller In a customized FSMD, the data path can be created to accommodate an individual application's needs. It may contain multiple customized functional units and parallel routing paths, and can complete complex computation in a single state (i.e., one clock cycle). On the other hand, the PicoBlaze microcontroller can perform only one predefined RT operation (i.e., an instruction) at a time. It may need many instructions to perform the same task and thus require much more time. Many tasks can be carried out using either a customized FSMD or a microcontroller. The trade-off is between the hardware complexity, performance, and ease of development. There is no exact rule on which one to choose. Because developing software is usually easier than creating customized hardware, the microcontroller option is generally preferable for nontime-critical applications. We can determine the feasibility of this option by examining the computation complexity. PicoBlaze requires two clock cycles to complete an instruction. If the system clock is 50 MHz, 25 million instructions can be performed in 1 second. For a task (or a collection of tasks), we can examine how frequently a request is issued and how fast the task must be completed, and then estimate the number of available instructions. For example, assume that a keyboard interface generates new input data every 1 ms and the data must be processed within this interval. Within the 1-ms period, PicoBlaze can complete 25,000 instructions. The PicoBlaze controller will be a viable option ifthe required processing can be carried out by using fewer than 25,000 instructions. In general, the microcontroller is suitable for many non-time-critical 110-interface or housekeeping tasks. 15.3 OVERVIEW OF PICOBLAZE 15.3.1 Basic organization PicoBlaze is a compact 8-bit microcontroller with the following characteristics: 8-bit data width 8-bit ALU with carry and zero flags 16 8-bit general-purpose registers 64-byte data memory a 18-bit instruction width 10-bit instruction address, which supports a program up to 1024 instructions 31-word calllretum stack 256 input ports and 256 output ports 2 clock cycles per instruction 5 clock cycles for interrupt handling PicoBlaze is based on the skeleton described in Figure 15.l(b) and adds several enhancements to make it more versatile. The expanded diagram is shown in Figure 15.2. To reduce clutter, only the main data flow is shown. The sizes of main storage components are listed in round brackets. The processor makes several enhancements over the original skeleton: Add a 64-word data memory. This is known as scratch RAM in the Xilinx literature, but we call it data RAM. The data RAM can be considered as a reservoir to store OVERVIEW OF PICOBLAZE 375 in-port \- data memory address memory I -* 4 b register tile (16-by-8) out-port port-id T stack (31-by-10) instruction memory address outside processor module instruction decoding L----r-..-----.....! 1 I ~nstruction Figure 15.2 B l o c k diagram o f PicoBlaze. instruction dr 1 ingort reset instruction outgort port-id read-strobe write-strobe intempt-ack I address I Figure 15.3 Top-level diagram of PicoBlaze. additional data. Note that there is no direct path between the data RAM and the ALU. Data must be fetched to a register for processing and then stored back to the data RAM. Add an immediate constantfield in some instructions. This allows a constant, rather than the content of a register, to be used in ALU and other operations. The two-to-one multiplexer before the ALU's bottom input is used to select the register output or the constant field. a Add a 31-word stack to support a function call. We discuss the call and return procedure in more detail in Section 15.5.8. a Addpaths to input and output external data. An 8-bit p o r t - i d signal is used to identify a port and thus up to 256 input ports and 256 output ports can be supported. The I10 interface is discussed in detail in Chapter 17. a Add an interrupt-handlingcircuit (not shown in the diagram). The interrupt mechanism is discussed in detail in Chapter 18. 15.3.2 Top-level HDL modules During synthesis, a PicoBlaze system is organized as two top-level HDL modules, as shown in Figure 15.3. The KCPSM3 module is the PicoBlaze processor. KCPSM3,which stands for constant (K) codedprogrammablestate machine,reflects the original name of the PicoBlaze processor. It has the following input and output signals: a clk (input, 1 bit): system clock signal a r e s e t (input, 1 bit): reset signal a address (output, 10 bits): address of the instruction memory, which specifies the location of the instruction to be retrieved a i n s t r u c t i o n (input, 18 bits): fetched instruction a p o r t - i d (output, 8 bits): address of the input or output port a in-port (input, 8 bits): input data from 110 peripherals a read-storbe (output, 1 bit): strobe associated with the input operation out-port (output, 8 bits): output data to I10 peripherals a write-storbe (output, 1 bit): strobe associated with the output operation a i n t e r r u p t (input, 1 bit): interrupt request from I10 peripherals a i n t e r r u p t - a c k (output, 1 bit): interrupt acknowledgment to 110 peripherals The second module is for the instruction memory. During the development, we usually store the compiled assembly code to memory in advance and configure it as a ROM in HDL code. It is thus known as an instruction ROM. DEVELOPMENT FLOW 377 15.4 DEVELOPMENT FLOW While developing a system based on a conventional microcontroller, we examine the required functionalities and select a processor with the proper computation capability and adequate I10 interface. Additional chips are frequently needed to perform special functions. One advantage of using a soft-core microcontroller is that we can have both a customized circuit and a microcontroller developed and implemented in the same FPGA device. A large application usually includes many different tasks. In an FPGA platform, we can implement the time-critical tasks in a customized circuit (i.e., "hardware") for performance and realize the remaining housekeeping and low-speed 110 functions in a microcontroller (i.e., "software"). The basic PicoBlaze-based development flow is shown in Figure 15.4. It consists of the following steps: 1. Determine the software-hardware partition. 2. Develop the assembly program for the software portion. 3. Compile the assembly program to generate an instruction ROM. The ROM is an HDL file. 4. Perform instruction-set-level simulation. 5. Derive HDL code for the hardware portion. The hardware includes customized circuits to perform special 110 and time-critical functions and customized circuits to interface with PicoBlaze. 6. Create top-level HDL code that combines the codes for the PicoBlaze core, the instruction ROM, and customized hardware. 7 . Develop a testbench and perform HDL simulation for the entire system. 8. Synthesize and implement the HDL code and program the FPGA chip on the prototyping board. We explain these steps in detail in subsequent chapters. Step 9, shown in the dotted line, is not a part of the normal development flow. It reloads the instruction memory after the entire system is synthesized. This step is discussed in Section 16.5.3. 15.5 INSTRUCTION SET PicoBlaze has 57 instructions. The instructions have five general formats. We organize the instructions according to the nature of their operations and divide them into the following categories: Logical instructions Arithmetic instructions Compare and test instructions Shift and rotate instructions Data movement instructions Program flow control instructions Interrupt related instructions In this section, we first examine the program model and instruction format and then list and explain each instruction. 1 1 softwarel hardware 0 partition 0 process + hardware development @ + @ software development .c g w r PicoBlaze code RTL code I testbench / r l r HtoDpL-level @ I I 1r ] O RTL, simuiat~on synthesis @ 1 + instruction simulation @ r _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ . ~ ~0 - . . . . . . ~ ~ ~ ~ ~ ~ ~ ~ . ~ ~ FPGA chip Figure 15.4 Development flow of a system with PicoBlaze. INSTRUCTION SET 379 register tile data Instruction calllreturn flags RAM memory stack Figure 15.5 PicoBlaze programming model. 15.5.1 Programming model From an assembly programming point of view, PicoBlaze contains sixteen 8-bit registers, a 64-byte data RAM, three flags (for zero, cany, and interrupt), the program counter, and the top-of-stack pointer. The model, sometimes known as the instruction set architecture, is shown in Figure 15.5. After an instruction is executed, the contents of these components are modified explicitly or implicitly. The operations associated with each instruction are discussed in Section 15.5.3. We use the following notations for these memory components and some constant definitions: sX, sY: each representing one of the 16 general-purpose registers, where X and Y take on hexadecimal values from 0 to f pc: program counter t o s : top-of-stack pointer of the calllreturn stack c, z, i: carry. zero, and interrupt flags KK: 8-bit constant value or port id, which is usually expressed as two hexadecimal digits SS: 6-bit constant data memory address, which is usually expressed as two hexadecimal digits AAA: 10-bit constant instruction memory address, which is usually expressed as three hexadecimal digits 15.5.2 Instruction format In an assembly program, we generally follow the conventions used in our HDL code, in which a keyword (an instruction mnemonic) is in boldface type and a constant is in capital letters. PicoBalze's instructions have five formats: op sX, sY: register-register format. The op term specifies the operation. The s X and s Y terms are the two operands and s X also serves as the destination register. It performs the s X t s X o p s Y operation. op sX, KK: register-constantformat. This format is similar to the register-register format except that the second operand is replaced by an immediate constant. It performs the s X + s X o p KK operation. op sX: single-registerformat. This format is used in shift and rotate instructions, which involve only one operand. It performs the s X t op s X operation. op AAA: single-addressformat. This format is used in jump and call instructions. The AAA term is an address of the instruction memory. If the specified condition is met, AAA is loaded into the program counter. op: zero-operandformat. This format is used in some miscellaneous instructions that do not involve any operand. There are two assembler programs for PicoBlaze: KCPSM3 from Xilinx and PBlazeIDE from Mediatronix. The two programs use different mnemonics for several instructions. In the following subsections, the alternative mnemonics used in PBlazeIDE are shown in round brackets. 15.5.3 Logical instructions There are six logical instructions, which support the and, or, and xor operations. An instruction performs bitwise logical operation between two registers or between one register and a constant. The carry flag, c, is always cleared. The zero flag, z, reflects the result ofthe operation. The mnemonics, brief descriptions, and pseudo operations of these instructions are: and sX, s Y - bitwise and operation - pseudo operation: sX + sX & sY; c + 0; and sX, KK - bitwise and operation - pseudo operation: sX + sX & KK; C + 0; o r sX, SY - bitwise or operation - pseudo operation: sX + sX I sY; c t 0; - bitwise or operation - pseudo operation: sX + sX I KK; c t 0; xor sX,sY - bitwise xor operation - pseudo operation: - sX t s X sY; C t 0; xor sX,KK - bitwise xor operation - pseudo operation: s X +- sX K K ; C t 0; 15.5.4 Arithmetic instructions There are eight arithmetic instructions, which support addition and subtraction with or without the carry flag. The carry flag, c, and the zero flag, z, reflect the result of operation. The mnemonics, brief descriptions, and pseudo operations of these instructions are: add sX,sY - add without the carry flag - pseudo operation: sX + sX + sY; add sX,KK - add without the carry flag - pseudo operation: sX +- sX + K K ; addcy sX, sY (addc sX,sY) - add with the carry flag - pseudo operation: sX +- sX + s Y + c ; addcy sX,KK (addc sX,KK) - add with the carry flag - pseudo operation: sX + sX + KK + c; sub sX,sY - subtract without the carry flag - pseudo operation: sX + sX - sY; sub sX,KK - subtract without the carry flag - pseudo operation: sX +- sX - K K ; subcy sX, sY (subc sX, sY) - subtract with the carry flag (flag functioning as a borrow bit) - pseudo operation: sX t sX - s Y - c: subcy sX,KK (subc sX,KK) - subtract with the carry flag (flag functioning as a borrow bit) - pseudo operation: sX + s X - K K - c : 15.5.5 Compare and test instructions The compare and test instructions examine two registers or one register and a constant, and set the carry and zero flags accordingly. The contents of the registers remain intact. These instructions are usually used in conjunction with a conditional jump or call instruction, whose operation is based on the values of the flags. A compare instruction performs subtraction operation. The result is used to set the cany and zero flags and not stored to any register. The mnemonics, brief descriptions, and pseudo operations of the two instructions are: compare sX,sY (comp sX, sY) - compare two registers and set the flags - pseudo operation: if sX==sY t h e n z t 1 e l s e z t 0 ; if s Y > s X t h e n c +- 1 e l s e c +- 0 ; compare sX,KK (comp sX,KK) - compare a register and a constant and set the flags - pseudo operation: i f s X = = K K t h e n z +- 1 e l s e z +- 0 ; if K K > s X then c t 1 e l s e c t 0; A test instruction performs an and operation. The result is used to set the flags and is not stored in any register. If the result is 0, the zero flag is set to 1. The result is also fed to an eight-input xor circuit to obtain the odd parity. If there are an odd number of 1's in the result, the carry flag is set to 1. The mnemonics, brief descriptions, and pseudo operations of the two instructions are shown below. The t is the 8-bit temporary result and will be discarded. test sX, sY - test two registers and set the flags - pseudo operation: t t s X & sY; i f t = = O t h e n z + 1 e l s e z +- 0 ; c + t [71 a t [61 . . . a t [Ol; test sX,KK - test a register and a constant and set the flags - pseudo operation: t +- s X & K K ; - - - if t = = O t h e n z t 1 e l s e z +- 0 ; c t t[7] t[6l ... t[OI; 76543210 76543210 srx 76543210 sra 76543210 Figure 15.6 Illustration of shift and rotate instructions. 15.5.6 Shift and rotate instructions There are four shift-left instructions, four shift-right instructions, and two rotate instructions. These instructions use the single-register format and have only one operand. The graphical representations of these instructions are shown in Figure 15.6. The mnemonics, brief descriptions, and pseudo operations of these instructions are: s10 sx - shift a register left 1 bit and shift 0 into the LSB - pseudo operation: . sX + (sX [6:01 , 0); c t sX [71 ; sll sX - shift a register left 1 bit and shift 1 into the LSB - pseudo operation: . SX +- {sXCG:Ol, c t s X [7]; SIX sx 1); - shift a register left 1 bit and shift sX [01 into the LSB - pseudo operation: sX t {sX[G:OI, sX[O]); c t s x [7]; sla sX - shift a register left 1 bit and shift c into the LSB - pseudo operation: sX t (sX[6:01, c); c + sX 171 ; 384 P I C O B W E OVERVIEW srO s X - shift a register right 1 bit and shift 0 into the MSB - pseudo operation: s X t C O , s X C7: 11I ; c t s X COI ; srl s X - shift a register right 1 bit and shift 1 into the MSB - pseudo operation: s X + C1, s X [ 7 : 1 l I ; c t sx COI ; srx s X - shift a register right 1 bit and shift s X [71 into the MSB - pseudo operation: sX t CsXC71, sXC7:lII; c t sx COI ; sra s X - shift a register right 1 bit and shift c into the MSB - pseudo operation: s x +-- { c , s X C 7 : l I I ; c t s X 101 ; - rotate a register left 1 bit - pseudo operation: sX t CsX[G:OI, sXC711; c t s X C71 ; - rotate a register right 1 bit - pseudo operation: s X t { s X CO1 , s X C7: 11I ; c t s X COI ; 15.5.7 Data movement instructions In PicoBlaze, the computation is done via the registers and ALU. The data RAM supplies additional storage and the 110 ports provide paths to peripherals. There are several instructions to move data between the registers, data RAM, and 110ports. The instructions can be divided into three categories: Between registers: the load instruction Between a register and data RAM: the fetch and store instructions Between a register and an I/Oport: the input and output instructions The mnemonics, brief descriptions, and pseudo operations of the data movement instructions are shown below. The RAM [ ] notation represents the content of the data RAM. Note that in some instructions, the indirect address notation, as in ( s Y ) , is used in the mnemonic to emphasize that the content of the s Y register is used. load sX,sY - move data between two registers - pseudo operation: sx +- s Y ; load sX,KK - move a constant to a register - pseudo operation: sX +- KK; fetch sX, (sY) (fetch sX,sY) - move data from the data RAM to a register - pseudo operation: sX +- RAMC(sYI1; fetch sX,SS - move data from the data RAM to a register - pseudo operation: sX +- RAMCSS]; store sX, (sY) (store sX,sY) - move data from a register to the data RAM - pseudo operation: RAM[(sY)I t s X ; store sX,SS - move data from a register to the data RAM - pseudo operation: RAM [SS] + sX; input sX, (sY) (in sX, sY) - move data from the input port to a register - pseudo operation: p o r t - i d t sY; sX +- i n - p o r t : input sX,KK (in sX,KK) - move data from the input port to a register - pseudo operation: p o r t - i d + KK; sX +- i n - p o r t ; output sx, (sY) (out sx, sY) - move data from a register to the output port - pseudo operation: p o r t - i d t sY; out-port t sX; output sX,KK (out sX,KK) - move data from a register to the output port - pseudo operation: p o r t - i d t KK; o u t - p o r t t sX; There is no explicit instruction to move data to or from instruction memory. However, many instructions include a field for an immediate constant. Since the constant is part of the instruction and stored in the instruction memory, it can be considered as data that is moved implicitly from the instruction memory to a register. 15.5.8 Program flow control instructions In PicoBlaze, the program counter indicates where to fetch the instruction. By default, the execution proceeds to the next address in the instruction memory and the program counter is incremented implicitly (i.e., pc t pc + 1). The jump, call, and return instructions can explicitly load a value to the program counter and modify the program flow. These instructions can be executed unconditionally or conditionally based on the values of the carry and zero flags. A jump instruction loads a new value to the program counter if the corresponding condition is met. The program execution changes the regular flow and branches to the new address. The program flow continues normally after this point. The mnemonics, brief descriptions, and pseudo operations of these instructions are shown below. Recall that AAA is for the 10-bit instruction memory address and pc is for the program counter. jump AAA - unconditionally jump - pseudo operation: pc + AAA, jump c, AAA - jump if the carry flag is set - pseudo operation: i f c = = l then pc t A A A else pc + pc + 1; jump nc, AAA - jump if the cany flag is not set - pseudo operation: i f c==O then pc t A A A else pc t pc + 1, jumpz, AAA - jump if the zero flag is set - pseudo operation: if z==1 then pc t AAA else pc t pc + 1; jump nz, AAA - jump if the zero flag is not set - pseudo operation: if z==0 then pc + A A A else pc t pc + 1, The call and return instructions are used to implement a software function. When a function is called, the processor suspends the current execution and branches to the corresponding routine. When the routine computation is completed, the processor returns to the suspended point and continues the execution. Like a jump instruction, a call instruction loads a new value to the program counter if the corresponding condition is met. In addition, it also saves the current value of the program counter in a special buffer, known as the stack. The new address represents the starting point of a routine. The routine should include a return instruction in the end. The return instruction obtains the saved value from the . --------- -- - main program ====== I add SO,s3 \ call routine1 sub s5,Ol I \ ' i ... ;====== routine 1 ===== routinel: Figure 15.7 Representative flow of a subroutine call. stack, increments the value by 1, and loads it to the program counter. This allows the execution to return to the instruction that immediately follows the original call instruction. A representative program flow is shown in Figure 15.7. PicoBlaze allows nested function calls, which means that a function can be called within another function. To support this feature, a stack, which is a last-in-first-out buffer, is used to store the program counter's values. In this buffer, the address of the newest call is pushed to the top of the stack (i.e., the "last-in"). Assume that this routine does not contain other function call inside. It will be completed first and the saved returned address is on the top of the stack. It should be popped from the stack (i.e., "first-out") to resume the previous execution. PicoBlaze provides a 31-word stack for the nested call and return operations. The mnemonics, brief descriptions, and pseudo operations of the call and return in- structions are shown below. Recall that t o s is for the top-of-stack pointer. The STACK [ I notation represents the content of the stack. call AAA - unconditional call subroutine - pseudo operation: t o s t t o s + 1; STACK [ t o s ] + PC; pc + AAA; call c, AAA - call subroutine if the carry flag is set - pseudo operation: i f c==l then t o s t t o s + 1; S T A C K C ~ O S+ I P C , pc t AAA; else call nc, AAA - call subroutine if the carry flag is not set - pseudo operation: if c==O t h e n t o s + t o s + 1; STACK [ t o s ] + p c ; pc + AAA; else PC t PC + 1; call z, AAA - call subroutine if the zero flag is set - pseudo operation: if z==1 t h e n t o s t t o s + 1; STACK[~OSI + pc; pc t AAA; e 1se pc t pc + 1; call nz, AAA - call subroutine if the zero flag is not set - pseudo operation: if z==0 t h e n t o s + t o s + 1; STACK [ t o s ] t p c ; pc + AAA; else pc + pc + 1; return (ret) - unconditional return - pseudo operation: pc + STACKCtos] + 1; t o s + t o s - 1; return c (ret c) - return if the carry flag is set - pseudo operation: if c==l then p c + STACK [ t o s l t o s + t o s - 1; else pc + pc + 1; + 1; return nc (ret nc) - return if the carry flag is not set - pseudo operation: if c==O t h e n p c + STACK [ t o s ] + 1 ; t o s t t o s - 1; else p c + pc + 1; return z (ret z) - return if the zero flag is set - pseudo operation: if z==1 then PC S T A C K [ ~ O S I+ 1; t o s t t o s - 1; else pc t pc + 1; return nz (ret nz) - return if the zero flag is not set - pseudo operation: if z==0 then p c t S T A C K E t o s ] + 1; t o s t t o s - 1; else pc t pc + 1; 15.5.9 Interrupt related instructions Interrupt is another mechanism to alter program execution and its detail is discussed in Chapter 18. Unlike the jump and call instructions, it is initiated from an external request. When the interrupt flag is enabled and the interrupt request is asserted, PicoBlaze completes execution ofthe current instruction, saves the address ofthe next instruction in the call/return stack, preserves the cany and zero flags, disables the interrupt flag, and loads the program counter with 3FF,which is the starting address of the interrupt service routine. PicoBlaze has two return-from-interrupt instructions, which resume operation from the interrupted location. It also has two instructions that enable and disable the interrupt request by setting or clearing the interrupt flag, i. The mnemonics, brief descriptions, and pseudo operations of these instructions are: returni disable (reti disable) - return from interrupt service routine and keep the interrupt flag disabled - pseudo operation: pc + STACK[tos] ; t o s t t o s - 1; i t 0; c + preserved c; z + preserved z ; returni enable (reti enable) - return from interrupt service routine and keep the interrupt flag enabled - pseudo operation: pc t STACK [tos] ; t o s + t o s - 1; i t 1; c + preserved c; z + preserved z; 390 PICOBLAZE OVERVIEW enable interrupt (eint) - enable interrupt request - pseudo operation: i t 1; disable interrupt (dint) - disable interrupt request - pseudo operation: i t 0; Note that the interrupt mechanism saves the address of the next instruction. When a returni instruction is executed, the address saved on the top of the stack (i.e., STACK [ t o s l ) is restored. This is different from a regular return instruction, in which the incremented address (i.e., STACK [ t o s ] +1)is restored. 15.6 ASSEMBLER DIRECTIVES An assembler directive looks like an instruction in an assembly program. However, it is not part of the microcontroller's instruction set but is used to help program development. As its name suggests, a directive "directs" the assembler to perform a specific task, such as defining a constant or reserving data space. The KCPSM3 and PBlazeIDE assemblers have somewhat different directives and they are discussed in the following subsections. 15.6.1 The KCPSM3 directives The mnemonics, descriptions, and examples of key directives used in the KCPSM3 assembler are: address - The directive specifies the subsequent code to be put to a specific address in the instruction ROM. - Example: address 3FF namereg - The directive gives a symbolic name for a register. It makes code more descriptive. - Example: namereg s 5 , i n d e x constant - The directive gives a symbolic name for a constant. It makes code more descriptive. - Example: constant m a x , FO 15.6.2 The PBlazelDE directives The mnemonics, descriptions, and examples of key directives used in the PBlazeIDE assembler are shown below. Note that a $ sign is needed for a number in hexadecimal format. org - The directive specifies the subsequent code to be put to a specific address in the instruction ROM (i.e., "originate" from this address). - Example: org $3FF equ - The directive "equates" a symbol to a value or register. It gives a symbolic name for a constant or a register. - Example: max equ index equ 128/8 s5 dsin, dsout, dsio - These directives equate a symbolic name for an 110port id. The corresponding port can be defined as input, output, or both input and output. The difference between these directives and equ is that PBlazeIDE generates "port indicators" for these directives on the simulation screen. The 110activities can be displayed and simulated via these indicators. - Example: keyboard switch led d s i n $OE d s i n $OF d s o u t $15 vhdl - This directive generates instruction ROM in VHDL format. The details are discussed in Chapter 16. - Example: vhdl "template. vhd" , " t a r g e t . vhd" , "ROM" 15.7 BIBLIOGRAPHIC NOTES The PicoBlaze manual from Xilinx, PicoBlaze 8-BitEmbeddedMicrocontroller User Guide, provides detailed information about this microcontroller, including the hardware organization, instruction set, development process, and KCPSM3 and PBlazeIDE assemblers. Ken Chapman, the designer of PicoBlaze, describes the derivation of this microcontroller in the article "Creating Embedded Microcontrollers," which is available in the TechXclusives section of the Xilinx Web site. The KCPSM3 assembler, PicoBlaze HDL code, and instruction ROM HDL template can be downloaded from the Xilinx Web site. Searching with the keyword "PicoBlaze" will lead to the downloading page. The PBlazeIDE assembler can be downloaded from the Mediatronix Web site, http://www .mediatronix.com. The site also provides more detailed information about the software. This Page Intentionally Left Blank CHAPTER 16 PICOBLAZE ASSEMBLY CODE DEVELOPMENT 16.1 INTRODUCTION Because of its simplicity, PicoBlaze cannot effectively support high-level programming languages and the code is generally developed in assembly language. In this chapter, we provide an overview of code development, which is illustrated in a bottom-up fashion. We first introduce the segments of frequently used data and control operations and then examine the use of a subroutine and finally outline the derivation of overall program structure. 16.2 USEFUL CODE SEGMENTS The PicoBlaze microcontroller contains instructions for byte-oriented data manipulation and simple conditional branch. In this section, we illustrate how to construct code to perform bit and multiple-byte operations and to realize frequently used high-level language control constructs. 16.2.1 KCPSM3 conventions The KCPSM3 assembler uses the following conventions in an assembly program: Use a ":" sign after a symbolic address in code, as in "done :". Use a ";" sign before a comment. Use HH for a constant, in which H is a hexadecimal digit. FPGA Proroyping b.v Verilog Examples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. 394 PICOBLAZEASSEMBLY CODE DEVELOPMENT An example of a code segment follows: ;t h i s i s a demo segment test SO, 82 ;compare SO with 1000-0010 jump z , clr-sl ;i f MSB o f S O i s 0 , go t o c l r - s f load sl, FF ;no, load 1111-1111 to s f clr-sl : load sl, 01 ;load 0000-0001 to s l 16.2.2 Bit manipulation PicoBlaze's instruction set is primarily for byte-oriented operations. Bit-oriented operations are frequently needed to control low-level 110activities, such as testing, setting, and clearing a I-bit flag signal. To manipulate a single bit, we first define a mask to isolate and preserve (i.e., mask) the unrelated bits and then apply the designated operation on the desired bits (i.e., unmasked bits). We can set, clear, and toggle (i.e., invert) some bits of a data byte by performing or, and,and xor instructions with a proper mask. The following code segment shows how to set, clear, and toggle the second LSB of the SO register: constant SET-MASK , 02 c o n s t a n t CLR-MASK , FD constant TOG-MASK , 02 ;m a s k = 0 0 0 0 _ 0 0 1 0 ;mask=llll-1101 ;m a s k = 0 0 0 0 - 0 0 1 0 or SO, SET-MASK and SO, CLR-MASK xor SO, TOG-MASK ; s e t 2nd LSB t o 1 ; c l e a r 2nd LSB t o 0 ; t o g g l e 2nd LSB The toggle operation is based on the observation that for any Boolean variable x, x @ 0 = x and x 69 1 = x'. The same principle can be applied to multiple bits. For example, we can clear the upper nibble (i.e., four MSBs) by using and SO, OF ;r n a s k = 0 0 0 0 - 1 1 1 1 We can also apply the concept of the and mask to the test instruction to check a single bit. For example, the following code segment tests the MSB of the SO register and branches to a proper routine accordingly: test SO, 80 ;m a s k = 1 0 0 0 _ 0 0 0 0 jump n z , msb-set ;MSB i s 1 , branch t o m s b - s e t ; c o d e f o r MSB n o t s e t jump done msb-set : ; c o d e f o r MSB s e t ... done : A single bit can be extracted by applying the previous code. For example, the following code segment extracts the MSB of the SO register and stores it in the sl register: load sl, 00 test SO, 80 jump z , done load sl, 01 ; m a s k = 1 0 0 0 - 0 0 0 0 , e x t r a c t MSB ; y e s , MSB i s 0 :no, load I to sl done : USEFUL CODE SEGMENTS 395 16.2.3 Multiple-byte manipulation A microcontroller sometimes needs to handle wide, multiple-byte data, such as a large counter. Since the data width of PicoBlaze is 8 bits, processing this type of data requires a mechanism to propagate information between two successive instructions. PicoBlaze uses the carry flag for this purpose. For the arithmetic instructions, there are two versions for addition and subtraction, one with carry and one without carry, as in the add and addcy instructions. For the shift and rotate instructions, carry can be shifted into the MSB or LSB of a register, and vice versa. Assume that x and y are 24-bit data and that each occupies three registers. The following code segment illustrates the use of carry in multiple-byte addition: namereg SO, xO namereg sl, xl namereg s2, x2 namereg s3, yo namereg s4, yl namereg s5, y2 ;least significant byte of x ;middle byte of x ;most significant byte of x ;least significant byte of y ;m i d d l e b y t e o f y ;most significant byte of y ;add: ( x 2 ,xl ,x 0 ) + ( y 2 ,yl , y o ) add xO, yo ;add least significant bytes addcy xl, yl ;add middle bytes with carry addcy x2, y2 ;add most significant bytes with carry The first instruction performs normal addition of the least significant bytes and stores the carry-out bit into the carry flag. The second instruction then includes the carry flag when adding the middle bytes. Similarly, the third instruction uses the carry flag from the previous addition to obtain the result for the most significant bytes. The incrementing and subtraction of multiple bytes can be achieved in a similar fashion: ;increment: (x2,xl ,xO) + 1 add xO , 01 ;i n c [ e a s t s i g n i f i c a n t b y t e addcy xl, 00 :add carry to middle byte addcy x2, 00 ;add carrv to most significant byte ;subtract: (x2,xl ,xO) - (y2,yl ,yo) sub xo, yo ;sub least significant byte subcy xl, yl ;sub middle byte with borrow subcy x2, y2 ;sub most significant byte with borrow Multiple-byte data can be shifted by including the carry flag in the individual shift instruction. For example, the sla instruction shifts data left one position and shifts the carry flag into LSB. The code for shifting a 3-byte data left can be written as ;s h i f t ( x 2 , x l , x 0 ) v i a c a r r y s10 x0 ;O t o LSB o f x O , MSB o f xO t o c a r r y s l a xl ; c a r r y t o LSB o f X I , MSB o f X I t o c a r r j j sla x2 ; c a r r y t o LSB o f x 2 , MSB o f x 2 t o c a r r y 396 PICOBLAZE ASSEMBLY CODE DEVELOPMENT 16.2.4 Control structure A high-level programming language usually contains various control constructs to alter the execution sequence. These include the if-then-else, case, and for-loop statements. On the other hand, PicoBlaze provides only simple conditional and unconditional jump instructions. Despite its simplicity, we can use them with a test or compare instruction to implement the high-level control constructs. The following examples illustrate the construction of the if-then-else, case, and for-loop statements. Let us first consider the if-then-else statement: if (sO==sl) 1 /* then-branch 1 else C /* else -branch 1 statements */ statements */ The corresponding assembly code segment is compare S O , sl jump n z , e l s e - b r a n c h ;code for then branch ... jump i f - d o n e else-branch : ;code for else branch ... i f -done : ;code following if statement The code uses the compare instruction to check the sO==sl condition and to set the zero flag. The following jump instruction examines the flag and jumps to the else branch if the flag is not set. The case statement can be considered as a multiway jump, in which execution is transferred according to the value of the selection expression. The following statement uses the SO variable as the selection expression and jumps to the corresponding branch: switch (SO) 1 case valuel: /* case valuel statements */ break; case value2: /* case value2 statements */ break; case value3: /* case value3 statements */ break ; default : /* default statements */ 1 The multiway jump can be implemented by a hardware feature known as "index address mode" in some processors. However, since PicoBlaze does not support this feature, the case statement has to be constructed as a sequence of if-then-else statements. In other words, the previous case statement is treated as USEFUL CODE SEGMENTS 397 if (sO==valuel) C /* case valuel statements */ 1 else i f (sO==value2) { /* case value2 statements */ > else i f (sO==value3) C /* case value3 statements */ 1 else( /* default statements */ 1 The corresponding assembly code segment becomes constant valuel , .. . constant value2, ... . c o n s t a n t v a l u e 3 , . . compare SO, v a l u e 1 jump n z , case-2 ;code for case 1 ; t e s t value1 ; n o t equal to value1 , jump jump case-done case-2 : compare S O , value2 jump n z , c a s e - 3 ;code for case 2 ;t e s t value2 ; n o t equal to v a l u e 2 , jump jump case-done case-3 : compare SO, v a l u e 3 ;t e s t v a l u e 3 jump d e f a u l t ;not equal to ;code for case 3 ... jump case-done default : ;code for default case ... case-done : ;code following case statement value3 , jump The for-loop statement executes a segment of the code repetitively. The loop statement can be implemented by using a counter to keep track of the iteration number. For example, consider the following: /* loop body statements */ 1 The assembly code segment is namereg s o , i constant MAX, ... ;loop index ;l o o p b o u n d a r y load i , MAX loop-body: ;code for loop body ... s u b i , 01 jump nz , l o o p - b o d y : c o d e f o l l o ~ ~ i nfgo r ;load loop index ;dec loop index? ;d o n e ? loop 16.3 SUBROUTINE DEVELOPMENT A subroutine, such as a hnction in C, implements a section of a larger program. It is coded to perform a specific task and can be used repetitively. Using subroutines allows us to divide a program into small, manageable parts and thus greatly improve the reliability and readability of a program. It is the base of modern programming practice and is supported by all high-level programming languages. PicoBlaze uses the call and return instructions to implement the subroutine. The call instruction savesthe current content ofthe program counter and transfers program execution to the starting address of a subroutine. A subroutine ends with a return instruction, which restores the saved program counter and resumes the previous execution. A representative flow is shown in Figure 15.7. Note that PicoBlaze only saves and restores the content of the program counter during a hnction call and return. We have to manage the register and data RAM use manually to ensure that the original system state is not altered after a subroutine call. The following multiplication example illustrates the development of subroutines. We assume that the inputs are two 8-bit numbers in unsigned integer format and the output is a 16-bit product. The algorithm is based on a simple shift-and-add method. This method iterates through 8 bits of multiplier. In each iteration, the multiplicand is shifted left one position. If the corresponding multiplier bit is 1, the shifted multiplicand is added to the partial product. The assembly code is shown in Listing 16.1. The multiplicand and multiplier are stored in the s3 and s4 registers. The individual bit of multiplier is obtained by repetitively shifting s4 to the right, which moves the LSB to the carry flag. Note that instead of actually shifting the multiplicand to the left, we shift the partial product, which consists of 2 bytes and is stored in s5 and s6, to the right. Listing 16.1 Software integer multiplication ;routine: mult-soft ; function : 8-bit unsigned multiplier using shift -and-add algorithm r ; input register: s3: mzrltiplicand s4: multiplier ; output register: s5: upper byte of product IO ; s6: lower byte of product ; temp r e g i s t e r : i ......................................................... mult-sof t : load s5, 00 PROGRAM DEVELOPMENT 399 15 load i, 0 8 mult-loop : srO s4 jump nc, shift-prod add s5, s3 20 shif t-prod : sra s5 sra s6 25 sub i, 01 jump n z , mult-loop return ;i n i t i a l i z e l o o p i n d e x ;s h i f t LSB t o c a r r y ;LSB is O :LSB is 1 : s h i f t upper byte right , ; c a r r y t o MSB, LSB t o c a r r y ;shift lower byte right , ;LSB o f s.5 t o MSB o f s 6 ;dec loop index ;repeat until i=O Because of the primitive nature of the assembly language, thorough documentation is instrumental. A subroutine should include a descriptive header and detailed comments. A representative header is shown in Listing 16.1. It consists of a short function description and the use of registers. The latter shows how the registers are allocated and is crucial to preventing conflict in a large program. 16.4 PROGRAM DEVELOPMENT Developing a complete assembly program consists of the following steps: 1. Derive the pseudo code of the mainprogram. 2. Identify tasks in the main program and define them as subroutines. Ifneeded, continue refining the complex subroutines and divide them into smaller routines. 3. Determine the register and data RAM use. 4. Derive assembly code for the subroutines. Steps 1, 2, and 4 basically follow a divide-and-conquer approach and are applicable for any software development. A microcontroller-based application is normally for a simple embedded system, in which the processor monitors the I10 activities continuously and responds accordingly. Its main program usually has the following structure: call initialization-routine forever : call taskl-routine call task2-routine call taskn-routine jump forever Step 3 is unique for assembly code development. Unlike a high-level language program, in which the compiler allocates storage to variables automatically, we must manage the data storage manually in assembly code. PicoBlaze has 16 registers and 64 bytes of data RAM to store data. The registers can be considered as fast storage, in which the data can be manipulated directly. The data RAM, on the other hand, is "auxiliary" storage. Its data needs to be transferred to a register for processing. For example, if we want to increment a data item located in the RAM, it must first be loaded into a register, incremented there, and then stored back to the RAM. Because of the limited space for data storage, its use has to be planned carefully in advance, particularly when the code is complex and involves nested subroutines. To assist unused lower byte of a2 upper by- te of a2 lower byte of b" + upper byte of b2 lower byte of a2 b2 + upper byte of a2 b" + carry of a' b2 Figure 16.1 Data RAM memory allocation. coding, we can first identify the needed global storage or local storage. The former keeps data that is needed in the entire program. The latter provides space to store intermediate results, and the data will be discarded after the required computation is completed. 16.4.1 Demonstration example The development process can best be explained by an example. Let us consider a program that uses the previous multiplication subroutine. It reads two inputs, a and b, from the + switch, calculates a2 b2, and displays the result on eight discrete LEDs. Since the 110 interface is to be discussed in Chapter 17, we limit the 110 to a single input port, the 8-bit switch, and a single output port, the 8-bit LEDs. We assume that a and b are obtained from the upper nibble (i.e., the four MSBs) and the lower nibble (i.e., the four LSBs) of the switch. The main program is call clear-data-ram forever : call read-switch call square call write-led jump forever The subroutines are defined as follows: c l r - d a t a ~ e m :clears data memory at system initialization read-switch: obtains the two nibbles from the switch and stores their values to the data RAM + square: uses the multiplication subroutine to calculate a2 b2 w r i t e - l e d : writes the eight LSBs of the calculated result to the LED port For demonstration purposes, we create two smaller routines, g e t - u p p e r n i b b l e and g e t - l o w e r n i b b l e , within the read-switch routine to obtain the upper nibble and lower nibble from a register. The next step in development is to plan the register and data RAM use. For global storage, we introduce a global register, sw-in, to store the input value of switch and allocate 11 bytes of data RAM to store the inputs and result of the s q u a r e routine. Allocation of the data RAM is shown in Figure 16.1. Note that the addresses 01 and 03 are not actually used. They are reserved to simplify the seven-segment LED display code, which is discussed in Chapter 17. All remaining registers are used as local storage. For program clarity, we define three symbolic names, data, addr, and i , as temporary registers for data, port and memory address, and loop index. The last step is to derive the assembly code for the subroutines. The complete code is shown in Listing 16.2. The clr-dataaem uses a loop to clear data memory. The i register is the loop index and is initialized with 64 (i.e., 4Ol6).The index is decremented in each loop and 0 is loaded to the corresponding data RAM address. The write-led routine fetches the eight LSBs of the calculated result from the data RAM and outputs them to the LED port. The read-switch routine includes two smaller routines. The get-uppernibble routine shifts the data register right four times to move the upper nibble to the four LSBs. The get-lowenibble routine clears the four MSBs of the d a t a register to 0's and thus removes the upper nibble. The "glue instructions" of read-switch input the switch values, set up the input for the two nibble routines, and store the result in the data RAM. The square routine fetches data from the data RAM, utilizes the mult-soft routine to calculate a2 and b2, performs addition, and stores the result back to the data RAM. Listing 16.2 Square program with simple nibble input ......................................................... ; square circuit with simple 1 / 0 interface ......................................................... ;program operation : 5 ; - read s w i t c h t o a ( 4 MSBs) and b ( 4 LSBs) ; - calculate a*a + b*b ; - display data on 8 leds ......................................................... lo ; data c o n s t a n t ......................................................... c o n s t a n t UP-NIBBLE-MASK , OF ;0 0 0 0 1 1 1 1 1s ; d a t a ram a d d r e s s a l i a s ......................................................... constant constant constant 20 c o n s t a n t constant constant constant constant 25 c o n s t a n t a-lsb, 00 b-lsb, 02 aa-lsb, 04 aa-msb, 05 bb-lsb, 06 bb-msb, 07 aabb-lsb, 08 aabb-msb, 09 aabb-cout , OA ; register alias ......................................................... 30 ; c o m m o n l y u s e d l o c a l v a r i a b l e s namereg SO, data ;reg for temporary data namereg sl , addr ; r e g f o r t e m p o r a r y mem & i / o namereg s2, i ;general -purpose loop index ;global variables 35 n a m e r e g s f , sw-in port addr ; port alias ......................................................... 40 ; constant constant input port definitions sw-port, 01 ;8-bit switches ozitput port definitions led-port , 05 a ;.-.-.-..-.-.-..-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.--------------- ; main program ......................................................... ;culling hierarchy: iu ;main ; - clr-data-mem ; - read-switch - get~trpper-nibble - get-lower-nibble 55 ; - s q u a r e - mult-soft ; - write-led 60 c a l l clr-data-mem forever : c a l l read-switch c a l l square c a l l write-led 6 jump forever ;routine : clr-data-mem : f u n c t i o n : c l e a r data ram 70 ; t e m p r e g i s t e r : d a t a , i ......................................................... clr-data-mem : load i, 40 load data, 00 75 c l r - m e m - l o o p : s t o r e data, (i) s u b i , 01 jump n z , clr-mem-loop return ; u n i t i z e loop index to 64 ;dec loop index ;repeat until i=O 80 ......................................................... ;r o u t i n e : read s w i t c h ; function: obtain two nibbles from input ; input register: sw-in 8s ; t e m p r e g i s t e r : d a t a ......................................................... read-switch : i n p u t sw-in , sw-port ;read switch input load data, sw-in 90 c a l l get-lower-nibble store data, a-lsb ; s t o r e a t o data ram load data, sw-in call get-upper-nibble store data, b-lsb ; s t o r e b t o data ram 95 ......................................................... ;r o u t i n e : g e t - l o w e r - n i b b l e ; function: get lower 4 bits of data ; input register: data loo ; o u t p u t r e g i s t e r : d a t a ......................................................... get-lower-nibble: and data, UP-NIBBLE-MASK ; c l e a r upper n i b b l e return 105 ......................................................... ;r o u t i n e : g e t - u p p e r - n i b b l e ; function: get upper 4 bits of data ; input register: data IIO ; output r e g i s t e r : data ......................................................... get-upper-nibble: srO data srO data 115 srO data srO data return ;right shift 4 times 120 ;r o u t i n e : w r i t e - l e d ; f u n c t i o n : output 8 LSBs of r e s u l t t o 8 leds ; temp r e g i s t e r : data ......................................................... write-led: 125 fetch data, aabb-lsb output data, led-port return I30 ; r o u t i n e : s q u a r e ; function: calculate a*a + b*b d a t a / r e s u l t stored in ram s t a r t e d w/ SQBASEADDR ; temp register: s3, s4, s5, s6, data ......................................................... 135 s q u a r e : ;c a l c u l a t e a * a fetch s3, a-lsb fetch s4, a-lsb c a l l mult-soft 140 store s6, aa-lsb store s5, aa-msb ;load a ;load a ;c a l c u l a t e a * a ; s t o r e lower byte of a*a ; s t o r e upper byte o f a*a ;calculate b*b fetch s3, b-lsb fetch s4, b-lsb In c a l l mult-soft store s6, bb-lsb s t o r e s5, 07 ;c a l c u l a t e a*a+b*b fetch data, aa-lsb I50 add d a t a , s 6 store data, aabb-lsb fetch data, aa-msb addcy data, s5 store data, aabb-msb 155 load data, 00 addcy data, 00 store data, aabb-cout return ;load b ;load b ;c a l c u l a t e b*b ;store lower byte of b*b ;store upper byte of b*b ;get lower byte of a*a ;add lower byte of a*a+b*b ; s t o r e lower byte of a*a+b*b ;get upper byte of a*a ;add upper byte of a*a+b*b ; s t o r e upper byte of a*a+b*b ;clear data, but keep carry ;get carry-out from previous + ;s t o r e c a r r y - o u t o f a*a+b*b ,--------------------------------------------------------- ;r o t r t i n e : m u i t - s o f t ; function : 8-bit unsigned multiplier using s h i f t -and-add a l g o r i t h m ; input register: 165 ; s3: multiplicand s4: multiplier ; output register: s5: upper byte of product s6: lower byte of product 170 , t e m p r e g i s t e r : i ......................................................... mult-sof t : load s5, 00 load i , 08 I75 mult-loop: srO s4 jump nc , shift-prod add s5, s3 shift-prod: IRO sra s5 sra s6 sub i, 01 la jump n z , mult-loop return ;clear s5 ;i n i t i a l i z e loop index ; s h i f t Isb to carry ;Isb is 0 ;Isb is 1 ;s h i f t upper b y t e r i g h t , ; c a r r y t o MSB, LSB t o c a r r y ;s h i f t l o w e r b y t e r i g h t , ; I s b o f s 5 t o MSB o f s6 ;dec loop index ; r e p e a t u n t i l i=O 16.4.2 Program documentation Developing an assembly program is a tedious process. The use of symbolic names and good documentation can make the code clear and reduce many unnecessary errors. It also helps future revision and maintenance. For the KCPSM3 assembler, we can use the constant directive to assign a symbolic name (alias) to a data constant, a memory address, or a port id, and use the namereg directive to assign a symbolic name to a register. A representative main program header is shown in Listing 16.2. It contains the following segments: General program description: provides a general description for the purpose, operation, and 110 of the program Data constants: declares symbolic names for constants Data RAM address alias: declares symbolic names for data RAM addresses Register alias: declares symbolic names for registers Port alias: declares symbolic names for I10 ports Program calling hierarchy: illustrates the calling structure and subroutines The aliases and directives have no effect on the final machine code. When the assembly code is processed, they are replaced with the actual constant values. However, using aliases can greatly enhance the readability of the assembly code and reduce unnecessary errors. The following code segment further illustrates the impact of the alias and documentation. The purpose of this segment is to obtain values for variables a, b, and c, and store them in proper data RAM locations. The location is specified by the UART input, which is the ASCII code of character a, b, or c. The segment with aliases and proper comments is ;constant a l i a s constant ASCII-a, 61 constant ASCII-b, 62 constant ASCII-c, 63 ; d a t a ram address a l i a s constant a-addr, 02 constant b-addr, 04 constant c-addr, 06 ;r e g i s t e r a l i a s namereg SO, data namereg sl, addr namereg SF, sw-in ;port alias constant sw-port, 01 constant uart-rx-port , 02 ;ASCII code for a ;ASCII code for b ;ASCII code for c ;reg for temporary data ;reg for temporary addr ;switch input ;switch input ;UART i n p u t ;assembly code with alias ;get input input sw-in, sw-port input data, uart-rx-port ;check received char compare data, ASCII-a jump n z , chk-ascii-b store sw-in, a-addr jump done chk-ascii-b : compare data, ASCII-b jump n z , chk-ascii-c store sw-in, b-addr jump done chk-ascii-c : compare data, ASCII-c jump n z , ascii-err ;get switch ;get char ;check ASCII a ;no, check next ; y e s , s t o r e a to data ram ;check ASCII b ;no, check next ; y e s , s t o r e b to data ram ;check ASCII c ;no, error store sw-in, jump done ascii-err: ... done : c-addr ; y e s , s t o r e b t o data ram If we use hard literals and strip the comments, the code becomes ;assembly code with no a l i a s or comments input s f , 01 i n p u t SO, 02 compare SO, 61 jump n z , a d d r l s t o r e s f , 02 jump addr4 addrl : compare SO, 62 jump nz , addr2 s t o r e s f , 04 jump addr4 addr2 : compare SO, 63 jump n z , addr3 s t o r e s f , 06 jump addr4 addr3 : ... addr4 : While the functionality of this code segment is the same, it is very difficult to comprehend, debug, or modify. 16.5 PROCESSING OF THE ASSEMBLY CODE PicoBlaze-based development flow is reviewed in Section 15.4. After the assembly code is developed, it is then compiled (translated) to machine instructions in step 3. The instructionset-level simulation can also be performed to verify the correctness of the code, as in step 4. The two steps and the direct downloading process (step 9) are discussed in detail in this section. Xilinx provides an assembler known as KCPSM3 for compiling in step 3 and downloading utility programs in step 9. The programs, HDL codes for the PicoBlaze processor, and relevant template files can be downloaded from the Xilinx Web site. A program known as PBlazeIDE from Mediatronix can perform the instruction-set-level simulation in step 4. It can also be used as an assembler. PBlazeIDE can be downloaded from Mediatronix's Web site. 16.5.1 Compiling with KCSPM3 Assembler is the software that translates the instruction mnemonics to machine instructions, which are represented as 0's and l's, and substitutes the aliases and symbolic branch addresses with actual values. The machine instructions are then downloaded to the instruction memory of a microcontroller. Since PicoBlaze is embedded inside FPGA, the instruction ROM becomes an HDL ROM module with the compiled assembly code. The ROM will be instantiated later in the top-level HDL code and synthesized along with PicoBlaze and the 110 interface circuit. Xilinx provides the KCPSM3 assembler for this task. It is a command-line, DOS-based program. KCPSM3 basically takes an assembly program, along with the necessary template files, and generates the HDL code for the instruction ROM. The procedure of compiling an assembly program is as follows: 1. Create a directory for the project and copy kcpsm3.exe, ROM-f o m v h d ROM-f orm.v, and ROM-form.coe to the directory. The latter three are code templates used by KCPSM3. 2. Create the assembly program and save it as plain text file with an extension of .psm. Any PC-based editor, such as Notepad, can be used for this purpose. + + + 3. Invoke a DOS window by selecting Start Programs Accessories Command Prompt. In the DOS window, navigate to the project directory. 4. Type kcpsm3 myf ile.psm to run the program. 5. Correct syntax errors if necessary and recompile. 6. After successfUl compiling, the file containing the instruction ROM, myf i l e . v , is generated. In addition to the HDL file, KCPSM3 also generates files that are suitable for block RAM initialization and other utilities. The file with the .hex extension can be used for JTAG downloading, which is discussed in Section 16.5.3, and the file with the .fmt extension is a reformatted .psm file for "pretty printing." 16.5.2 Simulation by PBlazelDE As the name indicates, instruction-set-level simulation simulates the operation of a PicoBlaze system instruction by instruction. The PBlazeIDE program can be used for this purpose. PBlazeIDE is a Windows-based program with an integrated development environment, which includes a text editor, an assembler, and an instruction-set-level simulator. PBlazeIDE uses slightly different instruction mnemonics and directives, as discussed in Section 15.5. Thus, the code written for by KCPSM3 cannot be used directly by PBlazeIDE, and vice versa. The mnemonic differences are summarized in Table 16.1, and the directive examples are shown in Table 16.2. Note that the PBlazeIDE assembler uses both decimal and hexadecimal format for constants. A hexadecimal number is started with a $ sign, as in $1A. The procedure of using PBlazeIDE for KCPSM3 code is as follows: 1. Compile the assembly code with KCPSM3. 2. Launch PBlazeIDE. + 3. Select Settings PicoBlaze 3. This specifies version 3 of PicoBlaze, which is used in the Spartan-3 device. 4. Select File + Import and a dialog window appears. Select the corresponding .fmt file. The "import" function converts the KCPSM3 code to the PBlazeIDE code. The formatted program is easier for conversion. The converted file may sometimes need minor manual editing. 5. Manually specify the dsin, dsout, and dsio directives for I10 ports. When one of these directives is used, a port indicator will be added to the simulation screen to show the activities of the port. Table 16.1 Mnemonic differences between KCPSM3 and PBlazeIDE KCPSM3 PBlazeIDE addcy subcy compare store s X , (sY) fetch s X , (sY) input s X , (sY) input s X , KK output sx, (sY) output s X , KK return returni enable interrupt disable interrupt addc subc comp store s X , s Y fetch s X , s Y in s X , sY in s X , $KK out sx, s Y out s X , $KK ret reti eint dint Table 16.2 Directive examples of KCPSM3 and PBlazeIDE Function code location constant register alias port alias KCPSM3 address 3FF constant MAX, 3F namereg addr, s 2 constant i n - p o r t , 00 constant out-port, 10 constant b i - p o r t , OF PBlazeIDE org $3FF MAX equ $3F a d d r equ s 2 i n - p o r t dsin $00 out-port dsout $10 b i - p o r t dsio $OF 6. Enter the simulation mode by selecting Simulate + Simulate. Perform simulation. 7. If the assembly code needs to be revised, it must be done outside PBlazeIDE. Simply close the current file, invoke an external editor to edit the original .psm file, save the file, and restart from step 1. If the file is edited within PBlazeIDE, it cannot be converted back to KCPSM3 code. A representative simulation screenshot is shown in Figure 16.2. The simulator displays the assembly code in the central window and highlights the next instruction to be executed. The instruction address, instruction code, and breakpoints are shown next to the code. The current state of PicoBlaze is shown at the left, including the status of the flags, the content of the registers, and the content of the data RAM. The values of the program counter and stack pointer as well as some execution statistics are shown in the bottom row. The emulated 110 ports created by the dsin, dsout, and dsio directives are shown at the right. There are an input port, switch,and an output port, l e d , on this particular screen. Since PBlazeIDE has no information about 110 behavior, the input port data must be entered and modified manually during simulation. During simulation, the assembly program can be executed continuously, by one step, by one instruction, or to pause at a specific breakpoint. The simulation action is controlled by the commands of the Simulate menu or the icons on the top: Figure 16.2 Screenshot of pBlazeIDE in simulation mode. Reset: clears the program counter and stack pointer Run: runs the program continuously until a breakpoint Single step: executes one instruction Step over: executes the entire subroutine for a call instruction and executes one instruction for other instructions Run to cursor: runs the program to the current cursor position Pause: pauses the simulation Toggle breakpoint: sets or clears a breakpoint at the current cursor position Remove all breakpoints: clears all breakpoints 16.5.3 Reloading code via the JTAG port After the instruction ROM HDL is generated, we can continue steps 6 and 8 in Figure 15.4 to synthesize the entire code and download the configuration file to the FPGA chips. Note that the synthesis flow must be repeated each time the assembly code is modified. Sincesynthesis is a complex process, it requires a significant amount of computation time. When the 110 configuration is fixed, resynthesizing the entire circuit after each assembly program modification is not really needed. It is possible to reload the machine code to the ROM, which is implemented by a block RAM, by using the FPGA's JTAG interface. This corresponds to the dotted line of step 9 in Figure 15.4. The basic procedure is as follows: 1. Replace the original ROM template with one that contains the JTAG interface circuit. 2. Use KCPSM3 to compile the assembly code as usual. 3. Synthesize the top-level HDL code and program the FPGA chip. 4. In subsequent assembly program modifications, compile the program as usual. Recall that a file in hex format (ended with the .hex extension) is generated. 5. Use the Xilinx utility to embed the .hexfile to a JTAG programming file and download the file to the FPGA's block RAM via the JTAG interface. The detailed procedure and the relevant programs and templates can be found in the JTAG-loader directory of the downloaded KCPSM file. 16.5.4 Compiling by PBlazelDE As discussed earlier, PBlazeIDE is an integrated program that contains an assembler and editor. PBlazeIDE can generate an instruction ROM HDL file as well. However, the file is only in VHDL format. Since Xilinx IST supports mixed-language synthesis, this file can still be incorporated into the top-level Verilog module. The detailed procedure can be found in the IST manual. To obtain the instruction ROM file, we simply include the vhdl directive in the assembly code. Its syntax is vhdl "ROM-form.vhdU, "rom-target.vhdU, "rom-entity-name" The three parameters specify a VHDL template file, which is the same file as that discussed in Section 16.5.1, the name of the generated ROM VHDL file, and the desired entity name in the VHDL file. Note that since PBlazeIDE does not generate a .hex file, the reloading scheme discussed in Section 16.5.3 cannot be applied directly. Figure 16.3 PicoBlaze with a simple 110 interface. 16.6 SYNTHESES WITH PICOBLAZE After generating the HDL file for the instruction ROM, we can combine it with PicoBlaze to synthesize the entire system in an FPGA chip. Unlike a normal microcontroller, PicoBlaze has no built-in 110 peripherals. The 110 interface is created and customized as needed. The circuit is described in HDL code. Since the focus in this chapter is on assembly program development, we use a simple 110 configuration, which contains only one switch input port and one led output port, for synthesis. The development of a more sophisticated I10 interface is discussed in detail in Chapters 17 and 18. The top-level block diagram of this design is shown in Figure 16.3. It contains the PicoBlaze processor, which is labeled kcpsm3, the instruction ROM, and a register. The register functions as a buffer for the eight LEDs. When PicoBlaze executes the output instruction, it places the data on out-port and asserts the w r i t e - s t r o b e signal, which enables the register and stores the data in the register. The s w signal is connected to i n - p o r t . When PicoBlaze executes the input instruction, it retrieves the value of the s w signal and stores it in an internal register. The corresponding HDL code is shown in Listing 16.3. It consists of instantiations of the PicoBlaze processor and instruction ROM, and a segment for the output buffer. The kcpsm3 module is the name of the PicoBlaze processor, and its code is stored in an HDL file ofthe same name. The sio-rom module is from the previously generated instruction ROM file. Listing 16.3 PicoBlaze with a simple 110 configuration module pico-sio ( input wire clk, reset, input wire [7:01 sw, 5 output wire [7:01 led 1; // signal declaration // KCPSM3/ROM s i g n a l s lo wire [9:01 address; wire [17:0] instruction; w i r e 17: 01 port-id , in-port , out-port ; wire write-strobe ; // r e g i s t e r signals IS reg [7:01 led-reg; //body / / ..................................................... / / KCPSM a n d ROM i n s t a n t i a t i o n 2o / / ..................................................... kcpsm3 proc-unit (.clk(clk), .reset(reset), .address(address), .instruction(instruction), .port-id(), .write-strobe(write-strobe), .out-port(out-port), 25 .read-strobe(), .in-port(in-port), .interrupt(l'bO), .interrupt-ack 0 ; sio-rom rom-unit ( . clk(c1k) , .address (address), .instruction(instruction)); / / ..................................................... // output interface / / ..................................................... always Q (posedge clk) if (write-strobe) led-reg <= out-port ; assign led = led-reg; / / ..................................................... // input interface / / ..................................................... 40 assign in-port = s w ; endmodule 16.7 BIBLIOGRAPHIC NOTES The bibliographic information for this chapter is similar to that for Chapter 15. The procedure of reloading compiled code via JTAG port is explained in the article "PicoBlaze JTAG Loader Quick User Guide" by Kris Chaplin and Ken Chapman, which appears in the JTAG-loader directory of the downloaded KCPSM file. 16.8 SUGGESTED EXPERIMENTS 16.8.1 Signed multiplication The subroutine in Listing 16.1 assumes that the inputs are in unsigned integer format. Modify the subroutine to perform the signed multiplication, in which the two inputs and output are interpreted as signed integers, and use simulation to verify its operation. 16.8.2 Multi-byte multiplication The subroutine in Listing 16.1 assumes that the inputs are 8 bits wide. Some application may need more precision and we want to extend the subroutine to take 16-bit unsigned inputs. An operand now requires two registers and the result needs four registers. Develop the subroutine and use simulation to verify its operation. 16.8.3 Barrel shift function PicoBlaze can only shift or rotate a single bit. A "barrel" shifting function can perform the shift and rotate operation for multiple bits. This function has three input registers. The first register contains data to be shifted or rotated; the second register specifies the amount, which is between 0 and 7; and the third register indicates the types of operation, which can be shift left, shift right, rotate left, or rotate right. We assume that 0 will be shifted in for the two shift operations. Develop the subroutine and use simulation to verify its operation. 16.8.4 Reverse function A reverse function reverses the bit order of an input. For example, ifthe input is "01010011", the output becomes "11001010". We can use the 8-bit switch as input and the 8-bit discrete LEDs as output. Derive and simulate the assembly code, obtain the instruction ROM and create the top-level HDL code, synthesize the system, and verify its operation. 16.8.5 Binary-to-BCD conversion Binary-to-BCD conversion is discussed in Section 6.3.3. This function can be implemented by using assembly code as well. Assume that the input is an 8-bit binary number and the output is a two-digit 8-bit BCD number. If the input exceeds 99, the output generates a special overflow pattern, " 1 1 111111". We can use the 8-bit switch as input and the 8-bit discrete LEDs as output. Derive and simulate the assembly code, obtain the instruction ROM and create the top-level HDL code, synthesize the system, and verify its operation. 16.8.6 BCD-to-binary conversion Repeat Experiment 16.8.5, but develop the assembly code and circuit for BCD-to-binary conversion. 16.8.7 Heartbeat circuit A "heartbeat circuit" is discussed in Experiment 4.7.4. We can create a similar pattern using the eight discrete LEDs as well. Derive and simulate the assembly code, obtain the instruction ROM and create the top-level HDL code, synthesize the system, and verify its operation. 16.8.8 Rotating LED circuit We want to design a circuit that rotates a simple LED pattern to the left or right at four differ- ent speeds. The four patterns are "00000001","0000001 1","00001 1 1 1",and "00001 101". The pattern, direction, and rotation speed can be selected from the 8-bit switch (only 5 bits are used). The speed should be chosen properly so that all four patterns are visually observable. Derive and simulate the assembly code, obtain the instruction ROM and create the top-level HDL code, synthesize the system, and verify its operation. 16.8.9 Discrete LED dimmer The concept of PWM and LED dimmer are discussed in Experiment 4.7.2. In this experiment, we want to use eight discrete LEDS to show the various degrees of brightness. This E , g , i. can be done by changing the "on" fraction of an LED. The "on" fraction of the eight LEDS will be $ , . . . , Derive and simulate the assembly code, obtain the instruction ROM and create the top-level HDL code, synthesize the system, and verify its operation. CHAPTER 17 PICOBLAZE I10 INTERFACE 17.1 INTRODUCTION To interact with the external environment, a regular microcontroller chip consists of a variety of built-in 110 peripherals, such as a UART, SPI (serial peripheral interface), timer, and so on. When starting a new development, we select a microcontroller chip according to the 110 requirements of the application and may sometimes need to use additional chips to realize less commonly used fbnctions. Unlike a regular microcontroller, PicoBlaze has no built-in I10 peripherals. It just provides a simple generic input and output structure for an 110 interface. I10 peripherals are constructed as needed and thus are customized to each application. PicoBlaze uses the input and output instructions to transfer data between its internal registers and 110 ports, and its interface consists of the following signals: p o r t - i d : an 8-bit signal that specifies the port id (i.e., port address) of an input or output instruction i n - p o r t : an 8-bit signal where PicoBlaze obtains input data during operation of an input instruction o u t - p o r t : an 8-bit signal where PicoBlaze places output data during operation of an output instruction r e a d - s t r o b e : a 1-bit signal that is asserted in the second clock cycle of an input instruction w r i t e - s t r o b e : a 1-bit signal that is asserted in the second clock cycle of an output instruction FPGA Profopping by Verilog Examples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. Figure 17.1 Timing diagram of an output instruction. Although there are only two 8-bit ports to input and output data, the 8-bit port-id signal can be used to distinguish different peripherals, and thus it is said that PicoBlaze can support up to 256 (i.e., 28) input ports and 256 output ports. In the remaining chapter, we examine the detailed 110timing of PicoBlaze and illustrate the 110 interface development by adding a series of peripherals for the square circuit of Chapter 16. 17.2 OUTPUT PORT 17.2.1 Output instruction and timing The output instruction writes data to the output port. It has two forms: output sx, (sY) o u t p u t sX , port-name In the first form, the port id is stored in the s Y register. In the second form, the port id is specified explicitly by port name, which is a two-digit hexadecimal number or a previously defined symbolic constant. The output data is always stored in the s X register. The timing diagram of an output instruction, output so, 02 is shown in the top five traces of Figure 17.1. Recall that each PicoBlaze instruction takes two clock cycles. When the instruction is executed, the content of SO is placed on out-port and 02 is placed on port-id for two clock cycles. The write-strobe signal is asserted in the second clock cycle. It can be used as an enable tick to store data in an output register or to initiate the designated peripheral operation. Figure 17.2 Output decoding of four output registers. Table 17.1 Truth table of a decoding circuit input output write-strobe p o r t - i d [I] port-id101 en-d 17.2.2 Output interface The output interface between PicoBlaze and an output peripheral usually consists of a decoding circuit and necessary output buffers, which are normally an array of registers. The decoding circuit decodes the port id and generates an enable tick accordingly. After the output instruction, the data will be stored in the designated buffer. To illustrate the construction, let us consider a PicoBlaze interface with four output buffers. We assign OOI6,Oils, 0216, and 0316 as their port ids. Note that the six MSBs of the port addresses are identical and only two LSBs are needed to distinguish a port. The block diagram is shown in Figure 17.2. The key is the decoding circuit, whose function table is shown in Table 17.1. It is a 2-t0-2~decoder. In the second clock cycle of an output instruction, w r i t e - s t r o b e is asserted and 1 bit of the Cbit en-d signal is asserted accordingly. The one-clock-cycle enable tick activates the corresponding output register to retrieve data from the o u t - p o r t signal. The decoding timing diagram of the instruction o u t p u t s o , 02 is shown at the bottom of Figure 17.1. During the second clock cycle of the output instruction, the en-d [21 signal is asserted and the data value on out-port is stored in the corresponding buffer at the rising edge of the next clock. Once understanding the basic operation, we can derive the HDL code accordingly. The code segment is always Q* if (write-strobe) c a s e (port-id El: 01 ) 2'bOO: en-d = 4'bOOOl; 2'bOl: en-d = 4'bOOlO; 2'blO: en-d = 4'bOlOO; 2'bll: en-d = 4'blOOO; endcase else en-d = 4'bOOOO; This scheme is very general and can be applied to any number of output ports. The choice of the port address is somewhat arbitrary. We use the binary code in the previous example. If the number of the output port is smaller than eight, one-hot code can be used to simplify the decoding circuit. For example, we can define the four previous port ids as 0Il6(i.e., 000000012),0 2 (i~.e., ~00000010~)0,416 (i.e., 000001002),and 0816(i.e., 000010002).The decoding logic can be simplified to always Q* i f (write-strobe) en-d = p o r t - i d [3:01 ; else en-d = 4'bOOOO; Note that no decoding logic is needed ifthere is only a single output port. The write-strobe signal can be connected to the register's enable signal, as shown in Figure 16.3. As discussed in Section 16.4.2, it is good practice to use symbolic aliases for 110 ports and declare their binary addresses in the header. For example, the initial output port address assignment can be declared as constant constant constant constant output port out-port-a , 00 out-port-b, 01 out-port-c , 0 2 out-port-d, 04 definitions Ifthe assignment is changed, we need to modify the header but keep the remaining assembly code intact. Using a clear header also allows us easily to identify the port ids when the companion HDL code is developed. 17.3 INPUT PORT 17.3.1 Input instruction and timing The input instruction reads data from the input port. Similar to the output instruction, it has two forms: input sX, (sY) input sX, port-name clk instruction port-id in-port read-strobe register SO Figure 17.3 Timing diagram of an input instruction. The s Y register or p o r t n a m e specifies the read port id. The retrieved data is stored in the s X register. The timing diagram of an input instruction, input SO, 02 is shown in Figure 17.3. When the instruction is executed, 02 is placed on p o r t - i d . After two clock cycles, i n - p o r t will be sampled at the rising edge of the clock and its value is stored in the SO register. The external circuit must ensure that the input data is stable during the sampling edge to avoid a timing violation. As in the output instruction, the r e a d - s t r o b e signal is asserted in the second clock cycle. The hnction of the r e a d - s t r o b e signal is less obvious and is discussed in the next subsection. 17.3.2 Input interface The input interface between PicoBlaze and input peripherals usually consists of a multiplexing circuit, which uses p o r t - i d as the selection signal to route the desired value to i n - p o r t . Sometimes, a decoding circuit similar to the one in the output interface is also necessary to signal the completion of the data access. For the purpose of input interface design, an input port can be classified as a continuousaccess or single-access port. For a continuous-access port, the data is presented continuously, such as the switch input of Section 16.4.1. On the other hand, the availability of data of a single-access port is triggered by a single discrete event, such as receiving a character in an UART buffer. The flag FF and buffers discussed in Section 8.2.4 are in this category. After the data is retrieved, we must remove it from the buffer to prevent the same data from being processed again. This is usually done by utilizing a one-clock-cycle tick to clear the flag FF or remove a word from a FIFO buffer. The interface for continuous-access ports involves only a multiplexing circuit. Consider an interface with four such ports. The block diagram is shown in Figure 17.4. The interface for single-access ports needs a mechanism to remove the retrieved data from the buffer in the end of an input instruction. This can be done by using a decoding circuit that decodes the p o r t - i d and r e a d - s t r o b e signals. The circuit is identical to the decoding circuit of the output interface except that w r i t e - s t r o b e is replaced by read-strobe. The decoded output can be considered as a "removal" signal, which is asserted for one clock Figure 17.5 Block diagram of four single-access ports. cycle and removes the previously retrieved data. Consider an interface with four FIFOs. The diagram of the complete decoding and multiplexing circuit is shown in Figure 17.5. The r v signal is the decoded removal signal. In the end of an input instruction, 1 bit of this 4-bit signal is asserted and the corresponding FIFO performs a read operation, in which the first word is removed from the buffer. Assume that 0Ol6,0116,0216,and 0316are assigned as the port ids. The HDL code segment for the interface is // multiplexing c i r c u i t always Q* c a s e ( p o r t - i d [l :01 2'bOO: d a t a = i n - d a t a 0 ; 2'bOl: data = in-datal; 2'blO: data = in-data2; 2'bll: data = in-data3; endcase // decoding c i r c u i t always Q* if (read-strobe) c a s e ( p o r t - i d [I :01 ) 2'bOO: r v = 4'bOOOl; 2'bOl: r v = 4'bOOlO; 2'biO: r v = 4'bOiOO; 2'bll: r v = 4'blOOO; endcase else r v = 4'bOOOO; In a real application, it is likely that the input interface contains both continuous- and single-access ports. A decoding circuit is only needed for single-access ports. 17.4 SQUARE PROGRAM WITH A SWITCH AND SEVEN-SEGMENT LED DISPLAY INTERFACE To demonstrate the construction of the PicoBlaze I10 interface, we add more versatile input and output peripherals to the square routine of Chapter 16. Recall that the square routine calculates a% b2,where a and b are 8-bit unsigned integers. We use the 8-bit switch and a pushbutton to enter the values of a and b. The pushbutton generates a one-clock-cycle tick when pressed. The tick indicates that the current value of the switch should be loaded. The values of a and b are loaded alternately; i.e., the first pressing loads a , the second pressing loads b, the third pushing loads a, and so on. A second pushbutton is also included to clear the PicoBlaze's data RAM and relevant registers. We use four seven-segment LEDs to display the inputs and computed results. The LEDs + are arranged as four hexadecimal numbers. Since the range of a2 b2 is up to 17 bits, the decimal point of the leftmost LED is used for the MSB. The three lower bits of the switch + select what to display, which can be a, b, a2, b2,or a2 b2. In summary, the interface consists of the following: Switch: provides the values of a and b and selects the content of the LED display Pushburron 0: loads the a and b alternately when pressed Pushburron 1: clears data RAM and relevant registers when pressed Seven-segment LED: displays the selected 17-bit value in four hexadecimal digits 17.4.1 Output interface Recall that the four seven-segment LEDs on the prototyping board share the same input pins, and a time-multiplexing circuit is required. For a PicoBlaze-based design, the multiplexing can be done by either an external circuit or a software routine. We use the external-circuit approach, which is simpler for assembly code development, in this section and discuss the software approach in Chapter 18. The LED time-multiplexing circuit designed in Section 4.5.1 can be used for this purpose. This circuit shields the timing and appears as four independent seven-segment LEDs for an external system. The block diagram of the PicoBlaze output interface is shown in Figure 17.6. The interface consists of four 8-bit output ports, each port representing a seven-segment LED pattern. In the assembly code, the four LED patterns are stored in PicoBlaze's data RAM with symbolic addresses of ledO, ledl, led2,and led3. The corresponding code segment is Figure 17.6 Output interface of a square circuit. ; d a t a RAM a d d r e s s a l i a s constant ledO, 10 c o n s t a n t ledl, 11 constant led2, 12 constant led3, 13 output port definitions constant sseg0-port , 00 constant ssegl-port , 01 constant sseg2_port, 02 constant sseg3_port, 03 ... disp-led : fetch data, ledO output data, sseg0-port fetch data, ledl output data, ssegl-port fetch data, led2 output data, sseg2-port fetch data, led3 output data, sseg3-port return ;7-seg ;7-seg ;7-seg ;7-seg led 0 led 1 led 2 led 3 17.4.2 Input interface The input interface consists of an 8-bit switch and two 1-bit pushbuttons. The former is a continuous-access port since the value is always present. The latter is a single-access port since pressing a button leads to only a single event (e.g., loading a to the register once rather Figure 17.7 Input interface of a square circuit. than continuously). Because of the mechanical glitches, a debouncing circuit is needed to generate a clean one-clock-cycle tick. Since PicoBlaze's port can take up 8-bit data, inputs from the two pushbuttons can be grouped together as a single input port. The block diagram of the input interface is shown in Figure 17.7. The interface consists of two debouncing circuits, a two-to-one multiplexer, a decoding circuit, and two flag FFs. The function of the two flag FFs is discussed in Section 8.2.4. They provide a mechanism to set and clear the "button-pressing event." When a button is pressed, the debouncing circuit's output sets the flag. It remains asserted until it is retrieved by the PicoBlaze's input instruction, which sets the selection signal of the multiplexer to route the desired value to PicoBlaze's input port, and activates the clear signal. For clarity, we name the pushbutton 1 as the s button (for setting the value) and pushbutton 0 as the c button (for clearing the data RAM). The pseudo code to process the input is ;input the button flags ;i f c=l t h e n ; call the clearing-ram routine ;i f s=I then ; input switch value ; s t o r e i t to data ram ; toggle a/b address offset Since the s button inputs the values of a and b alternately, we use a global register, switch-a-b,to keep track of which one is being read currently. The register serves as the data RAM address offset, which can be 0 or 2, and its value toggles when the s button is pressed. The corresponding assembly code subroutine is ;input port d e f i n i t i o n s c o n s t a n t rd-f l a g - p o r t , 00 constant sw-port , 01 ;2 flags (xxxxxxsc): ;&bit switch proc-btn : input s3, rd-flag-port ;get flag ;check and process c button test s3, 01 ;check c button flag jump z , chk-btns ; f l a g not set call init ;flag set, clear jump proc-btn-done chk-btns : ;check and process s button test s3, 02 ;check s button flag jump z , proc-btn-done ; f l a g not s e t input data, sw-port ;get switch load addr, a-lsb ; g e t addr of a add addr , switch-a-b ;a d d of f s e t store data, (addr) ;w r i t e d a t a t o ram ;update current disp position xor switch-a-b, 02 ;t o g g l e b e t w e e n 0 0 , 02 proc-btn-done : return 17.4.3 Assembly code development After designing the 110 interface, we can derive the assembly program. The development follows the divide-and-conquer approach discussed in Chapter 16 and partitions the main program into several subroutines. The main program is call init forever : ;main loop body call proc-btn call square call load-led-pttn call disp-led jump f o r e v e r ;i n i t i a l i z a t i o n ;c h e c k & p r o c e s s b u t t o n s ;c a l c u l a t e s q u a r e ; s t o r e l e d p a t t e r n s to ram ;output led pattern The complete code is shown in Listing 17.1. The square subroutine is from Chapter 16, and the proc-btn and d i s p - l e d sub- routines are discussed in the two preceding subsections. The i n i t subroutine performs system initialization. It uses a loop to load 0's to data RAM (i.e., clear the RAM) and sets the switch-a-b register to 0 (i.e., read a). The l o a d - l e d - p t t n subroutine reads the switch input, retrieves the desired values from the data RAM, converts the values to sevensegment LED patterns, and stores them to the corresponding locations in the data RAM. These patterns are then written to the output ports in the subsequent disp-led routine. The load-led-pttn routine consists of the g e t - u p p e r n i b b l e and g e t - l o w e r n i b b l e routines to extract the two hexadecimal digits and the hex-to-led routine to convert a hexadecimal digit to the corresponding seven-segment LED pattern. The program requires more storage. In addition to the data RAM and registers required for the square subroutine, this program utilizes a new global register switch-a-b to keep track of whether a o r b is being read, and 4 bytes in data RAM, whose addresses are labeled ledO, l e d i , led2, and led3, to store four seven-segment LED patterns. Listing 17.1 Square program with a switch and seven-segment LED interface ......................................................... ; s q u a r e c i r c l t i t w i t h 7-seg LED i n t e r f a c e ......................................................... ;program operation : c ; - read a and b jkom switch : - calculate a*a + b*b : - d i s p l a y data on 7-seg led ......................................................... lo : d a t a RAM a d d r e s s a l i a s ......................................................... constant constant constant 1% c o n s t a n t constant constant constant constant zo c o n s t a n t constant constant constant constant a-lsb, 00 b-lsb, 02 aa-lsb, 04 aa-msb, 05 bb-lsb, 06 bb-msb, 07 aabb-lsb, 08 aabb-msb, 09 aabb-cout , OA ledO, 10 ledl, 11 led2, 12 led3, 13 5 ......................................................... ; register alias ......................................................... ;c o m m o n l ~ v u s e d l o c a l v a r i a b l e s 70 namereg SO, data ;reg for temporary data namereg sl, addr ; r e g f o r t e m p o r a r y mem & i / o p o r t a d d r namereg s2, i ;g e n e r a l - p u r p o s e l o o p i n d e x ;global variables namereg sf, switch-a-b ;ram o f f s e t for current switch input 15 ......................................................... ; port alias ......................................................... 40 c o n s t a n t constant constant constant 45 c o n s t a n t constant -input port definitions rd-f l a g - p o r t , 0 0 ;2 f l a g s ( x x x x x x s c ): sw-port, 01 ;8-bit switch output port definitions sseg0-port, 00 ;7-seg led 0 ssegl-port , 01 :7-seg led 1 sseg2_port, 02 :7-seg led 2 sseg3_port, 03 :7-seg led 3 : main progranz 5" ;.-.-.-.-.-..-.-.-.-.-.-..-.-.-.-.-..-.-.-.-.-..-.-.-.-.-.-..-.-.-.-.-..-.-.-.-.-..-.-.-.-.-.-..-.-.-.-.-.--------- ;c a l l i n g h i e r a r c h y : ;m a i n , - init 5 5 , - proc-btn - init ; - square - mult-soft ; - load-led-pttn 60 ; - get-lower-nibble - get-upper-nibble - hex-to-led ; - disp-led c a l l init forever : ;main loop body 70 call proc-btn call square call load-led-pttn c a l l disp-led jump forever ;i n i t i a l i z a t i o n ;check & process buttons ;c a l c u l a t e s q u a r e ; s t o r e led p a t t e r n s to ram ;output led pattern 75 ......................................................... :r o u t i n e : i n i t ; function : perform initialization , clear register/ram ; output register: 80 ; s w i t c h - a - b : c l e a r e d t o 0 ; temp r e g i s t e r : data, i ......................................................... init : ;c l e a r memory 0s load i, 40 load data, 00 clr-mem-loop: store data, (i) sub i, 01 oo jump n z , clr-mem-loop ;clear register load switch-a-b, 00 return ;u n i t i z e l o o p i n d e x t o 64 ;dec loop index ; r e p e a t u n t i l i=O ;r o u t i n e : p r o c - b t n ; f u n c t i o n : check two buttons and process the display ; input reg: s w i t c h - a - b : ram o f f s e t (0 for a and 2 f o r b ) IW ; output r e g i s t e r : s3: store input port flag s w i t c h - a - b : may be t o g g l e d ;.-.-.--.-t.-e-.m-.--p.-.--.-r.--e.-.-g-.-i-.s-.-t-.e-.-r-.-.--.u-.-s-.-e.--d.-.-:-.-.-d-.-a.--.t-.-a-.-,.--.-a.--d.-.-d-.r................... 10s proc-btn : input s3, rd-flag-port ;get flag ;check and process c button t e s t s3, 01 ;check c button flag jump z , chk-btns ;flag not set 110 c a l l init ;flag set, clear jump proc-btn-done chk-btns : ;check and process s button test s3, 02 ;check s button flag 115 jump z , p r o c - b t n - d o n e ; f l a g n o t s e t input data, sw-port ;get switch load addr, a-lsb ;get addr of a add addr , switch-a-b ;add offset store data, (addr) ;write data to ram 120 ; u p d a t e c u r r e n t d i s p p o s i t i o n xor switch-a-b, 02 : t o g g l e between 0 0 , 02 proc-btn-done : return :.-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..--------------- :r o u t i n e : l o a d - l e d - p t t n : f u n c t i o n : read 3 LSBs of switch input and convert t h e desired values to four led patterns and load them t o ram 130 ; s w i t c h : 0 0 0 : ~ ;0 0 1 : b ; 0 1 0 : a " 2 ; 0 1 1 : b " 2 ; others: a-2 + b"2 ; temp register used: data, addr ; s 6 : data from sw i n p u t port ,? ,--------------------------------------------------------- load-led-pttn : input s6, sw-port s10 s6 compare s6, 08 I40 jump c , sw-ok load s6, 08 sw-ok: ;process byte 0, lower load addr, a-lsb I45 add addr, s6 fetch data, (s6) c a l l get-lower-nibble c a l l hex-to-led store data, led0 I5IJ :process byte 0 , upper fetch data, (addr) c a l l get-upper-nibble c a l l hex-to-led store data, led1 155 ;process byte 1 , lower add addr , 01 fetch data, (addr) c a l l get-lower-nibble ;get switch ;*2 to obtain addr offset ;sw>100? ;n o ; y e s , sw e r r o r , make d e f a u l t nibble ;get lower addr ;get lower byte ;get lower nibble ;convert to led pattern nibble nibble ;get upper addr c a l l hex-to-led 160 s t o r e data, led2 ;process byte I , upper nibble f e t c h data, (addr) c a l l get-upper-nibble c a l l hex-to-led lbi ; c h e c k f o r SMI=IOOt o p r o c e s s c a r r y as l e d dp compare s6, 08 ;d i s p l a y f i n a l r e s u l t ? jump n z , led-done ;no add addr , 01 ;get carry addr f e t c h s 6 , (addr) ;s6 to store carry 170 t e s t s6, 01 ;c a r r y = I ? jump z , led-done :no and data, 7 F ; y e s , a s s e r t msb ( d p ) to 0 led-done : s t o r e data, led3 175 return ;r o u t i n e : d i s p - l e d ; function: output four led patterns 1x0; temp r e g i s t e r used: data ......................................................... disp-led : f e t c h data, led0 o u t p u t data, sseg0-port 185 f e t c h data, led1 output data, ssegl-port f e t c h data, led2 output data, sseg2-port f e t c h data, led3 I90 o u t p u t data, sseg3-port return ;r o u t i n e : h e x - t o - l e d 195 ; f u n c t i o n : c o n v e r t a h e x d i g i t t o 7 - s e g l e d p a t t e r n ; input register: data ; output register: data ......................................................... hex-to-led: zoo compare data, 00 jump n z , comp-hex-1 load data, 81 jump hex-done ;7-seg pattern 0 comp-hex-1: 203 compare data, 01 jump n z , comp-hex-2 l o a d data, CF jump hex-done comp-hex-2 : 210 compare data, 02 jump n z , comp-hex-3 ;7-seg pattern I load data, 92 jump hex-done comp-hex-3: 215 compare data, 03 jump n z , comp-hex-4 load data, 86 jump hex-done comp-hex-4 : zzo compare data, 04 jump n z , comp-hex-5 l o a d data, CC jump hex-done comp-hex-5: --7 7 5 compare data, 05 jump n z , comp-hex-6 load data, A4 jump hex-done comp-hex-6 : 230 c o m p a r e data, 06 jump n z , comp-hex-7 l o a d data, A0 jump hex-done comp-hex-7: 2 compare data, 07 jump n z , comp-hex-8 load data, 8F jump hex-done comp-hex-8 : 240 c o m p a r e data, 0 8 jump n z , comp-hex-9 load data, 80 jump hex-done comp-hex-9: 245 c o m p a r e data, 09 jump n z , comp-hex-a l o a d data, 84 jump hex-done comp-hex-a: 250 c o m p a r e data, OA jump n z , comp-hex-b l o a d data, 88 jump hex-done comp-hex-b : 2 5 compare data, OB jump n z , comp-hex-c l o a d data, EO jump hex-done comp-hex-c: 260 compare data, O C jump n z , comp-hex-d load data, B1 jump hex-done comp-hex-d: ;7-seg pattern 2 ;7-seg pattern 3 ;7-seg pattern 4 ;7-seg pattern 5 ;7-seg pattern 6 ;7-seg pattern 7 :7-seg pattern 8 ;7-seg pattern 9 ;7-seg pattern a ;7-seg pattern b ;7-seg pattern C 265 c o m p a r e d a t a , O D jump n z , comp-hex-e load data, C2 jump hex-done comp-hex-e: 270 compare data, O E jump n z , comp-hex-f load data, BO jump hex-done comp-hex-f : 275 load data, B8 hex-done : return ;7-seg pattern d ;7-seg pattern E ;7-seg pattern F 280 ;r o u t i n e : g e t - l o w e r - n i b b l e ; function: get lower 4 bits of data ; input register: data ; output register: data ......................................................... 28s get-lower-nibble : and data, OF return ;clear upper nibble 290 ;r o u t i n e : g e t - u p p e r - n i b b l e ; function: get upper 4 bits of in-data ; input register: data ; output register: data ......................................................... 295 get-upper-nibble : srO data srO data srO data srO data loo return ;right shift 4 times ......................................................... ;r o u t i n e : s q u a r e : function: calculate a*a + b*b 30s ; d a t a / r e s u l t s t o r e d in ram s t a r t e d w/ SQBASEADDR ; temp r e g i s t e r : s 3 , s 4 , s 5 , s 6 , data ......................................................... square : ;c a l c u l a t e a * a 110 f e t c h s3, a-lsb fetch s4, a-lsb c a l l mult-soft store s6, aa-lsb store s5, aa-msb 315 ;calculate b*b fetch s3, b-lsb fetch s4, b-lsb ;load a ;load a ;c a l c u l a t e a * a ;store lower byte of a*a ;store upper byte of a*a ;load b ;load b c a l l mult-soft ;c a l c u l a t e b*b store s6, bb-lsb ;store lower byte of b*b :zo store s5, bb-msb ; s t o r e zrpper b y t e o f b * b ;c a l c ~ r l a t ea*a+b*b fetch data, aa-lsb ;get lower byte of a*u add data, s6 ;add lower byte of a*a+b*b s t o r e data, aabb-lsb ;s t o r e l o w e r b y t e o f a*a+b*b fetch data, aa-msb ; g e t u p p e r b y t e o,f a * a addcy data, s5 ;add upper byte of a*a+b*b s t o r e data, aabb-msb ; s t o r e zcpper b y t e o f a*a+b*b l o a d data, 00 ;clear data, but keep carry addcy data, 00 ;get carry from previous + o store data, aabb-cout : s t o r e carry of a*a+b*b return ......................................................... :r o u t i n e : m1rlt_soft 7% ; f u n c ~ i o n: 8- b i t u n s i g n e d m u l t i p l i e r u s i n g s h i f t -and-add algorithm : input register: .s3: n ~ z i l t i p l i c a n d s4: multiplier : 34n o u t p u t r e g i s t e r : s 5 : zipper byte o f product s6: lower byte of product ; temp register: i ......................................................... wt mult-sof t : load s5, 00 load i, 08 mult-loop : srO s4 350 jump n c , shift-prod add s5, s3 shift-prod: sra s5 355 sras6 s u b i, 01 jump n z , mult-loop return ;clear s5 ;initialize loop index ; s h i f t Isb to carry ;Isb is O ;l s b i s l ; s h i f t upper byte r i g h t , ; c a r r y t o MSB, LSB t o c a r r y :s h i f t lower byte right , ; I s b o f s 5 t o MSB o f s 6 ;dec loop index ; r e p e a t u n t i l i=O 17.4.4 HDL code development The complete HDL code simply combines the PicoBlaze processor, instruction ROM, the input interface and peripherals shown in Figure 17.7,and the output interface and peripherals shown in Figure 17.6. It is shown in Listing 17.2. Listing 17.2 PicoBlazewith aswitchand seven-segmentLED interface module pico-btn ( input wire clk, reset, i n p u t w i r e [7:01 sw, i n p u t w i r e [1:01 btn, o u t p u t w i r e [3:01 an, o u t p u t w i r e [7:01 sseg 1; lo // s i g n a l d e c l a r a t i o n // KCPSM3/ROM s i g n a l s w i r e [9:0] address; w i r e [17:0] instruction; w i r e [7:01 port-id , out-port ; 15 r e g C7:Ol in-port; wire write-strobe , read-strobe ; // 1 / 0 port signals // output enable r e g [3:0] en-d; 20 // f o u r - d i g i t s e v e n - s e g m e n t l e d d i s p l a y r e g [7:01 ds3_reg, ds2_reg, dsl-reg, ds0-reg; // two pushbuttons reg btnc-flag-reg, btns-flag-reg; wire btnc-flag-next , btns-f lag-next ; 25 w i r e set-btnc-flag, set-btns-flag, clr-btn-f lag; //body / / ----------------------------------=================== , // 1 / 0 modules / / -----------------------------------================== disp-mux disp-unit (.clk(clk), .reset(reset), . in3 (ds3-reg), . in2 (ds2-reg), . in1 (dsl-reg), .inO(dsO-reg), .an(an), .sseg(sseg)); a debounce btnc-unit ( . clk(c1k) , . reset (reset) , . sw (btn [o] ) , . db-level() , . db-tick(set-btnc-f lag)) ; debounce btns-unit (.clk(clk), .reset(reset), .sw(btn[1]), 40 .db-level(), .db-tick(set-btns-flag)); / / ----------------------------------=================== // KCPSM and ROM i n s t a n t i a t i o n / / ----------------------------------=================== kcpsm3 proc-unit 45 (.clk(clk), .reset(l'bO), .address(address), .instruction(instruction), .port-id(port-id), .write-strobe(write-strobe), .out-port(out-port), .read-strobe(read-strobe), .in-port(in-port), .interrupt(l'bO), .interrupt-ack0); 0 btn-rom rom-unit ( . clk(c1k) , . address(address) , .instruction(instruction)); SQUARE PROGRAM WITH A SWITCH AND SEVEN-SEGMENT LED DISPLAY INTERFACE 433 // output interface // // // // 60 // outport port id: 0x00: ds0 0x01: dsl 0 x 0 2 : d.s.2 0x03: ds3 // r e g i s t e r s a l w a y s Q ( p o s e d g e clk) begin 63 i f (en-d [Ol) ds0-reg <= out-port ; i f (en-d [I] ) dsl-reg <= out-port ; i f (en-d [2] ) ds2-reg <= out-port ; i f (en-d [3] ) ds3-reg <= out-port ; end // decoding c i r c u i t for enable signals 71 a l w a y s Q * i f (write-strobe) c a s e (port-id [l:01 ) 2'bOO: en-d = 4'bOOOI; 2'bOl: en-d = 4'bOOIO; xo 2'blO: en-d = 4'bOlOO; 2'bll: en-d = 4'biOOO; endcase else en-d = 4'bOOOO; // input interface // 90 // // input port id 0x00: flag 0x01: switch // input register (for f l a g s ) a l w a y s Q ( p o s e d g e clk) 95 begin btnc-flag-reg <= btnc-flag-next; btns-flag-reg <= btns-flag-next; end a s s i g n btnc-f lag-next = (set-btnc-f lag) ? l'bl : Ino (clr-btn-flag) ? l'bO : btnc-flag-reg; a s s i g n btns-flag-next = (set-btns-flag) ? l'bl : (clr-btn-flag) ? l J b O : btns-flag-reg; lor // d e c o d i n g c i r c u i t f o r c l e a r s i g n a l s 434 PICOBLAZE 110 INTERFACE a s s i g n clr-btn-f lag = read-strobe && (port-id [0]==1' b0) ; // input multiplexing always Q* c a s e (port-id LO1 IID 1 bO : in-port = {6'b0, btns-f lag-reg , btnc-f lag-reg); 1 'bl: in-port = sw; endcase endmodule 17.5 SQUARE PROGRAM WITH A COMBINATIONAL MULTIPLIER AND UART CONSOLE In this section, we add two more I10 peripherals to the previous design. One is a combinational multiplier, which accelerates the multiplication, and the other is an UART, which provides a communication link to a PC. 17.5.1 Multiplier interface Since PicoBlaze does not contain a hardware multiplier, the multiplication is done by a software routine, mult-soft. It uses a shift-and-add algorithm to iterate through the 8-bit multiplier and requires about 60 instructions in the worst-case scenario. An alternative is to utilize the Spartan-3 device's built-in combinational multiplier. Since PicoBlaze provides no mechanism to use a coprocessor, the multiplier must be configured as an I10 peripheral. We can create an 8-bit combinational multiplier that takes two 8-bit operands and returns a 16-bit product. To facilitate this peripheral, the PicoBlaze's interface requires two additional output ports and buffers for the two operands and two additional input ports for the 16-bit product. The assembly routine now only needs to pass the operands to the output ports and then retrieve the results from the input ports. The code becomes ;input port definitions c o n s t a n t mult-prodo-port , 0 3 ;m u l t i p l i c a t i o n p r o d u c t constant mult-prodl-port, 04 ; m u l t i p l i c a t i o n product ;output port d e f i n i t i o n s constant mult-src0-port , 05 constant mult-srcl-port , 06 ... ;m u l t i p l i e r o p e r a n d 0 ;m u l t i p l i e r o p e r a n d I mult-hard: output s3, mult-src0-port output s4, mult-srcl-port input s5, rnult-prodl-port input s6, mult-prodo-port return 8 LSBs 8 MSBs Note that the combinational multiplier can complete the computation with one instruction (i.e., two clock cycles), and thus no additional timing mechanism is needed in the code. This routine can be used in place of the previous mult-sof t routine. SQUARE PROGRAM WITH A COMBINATIONALMULTIPLIER AND UART CONSOLE 435 Figure 17.8 Representative console screen. 17.5.2 UART interface With the UART interface, information can be entered and displayed in Windows HyperTerminal, which is more flexible and versatile than switches and LEDs. We use it as a simple control console for the square routine. A representative screen is shown in Figure 17.8. The console generates an SQ> prompt and a user can respond with a lowercase a , b, c, or d character. The a and b characters are used to input values for a and b of the square routine. When the key is pressed, the value of the 8-bit switch is read and stored into the corresponding data RAM location. The c character is used to clear the data RAM and reinitialize the program. Its function is identical to that of the c button. The d character leads to a "data RAM dump," in which the 64 bytes of the data RAM are displayed on screen. This allows us to observe the various values of the s q u a r e routine and the four seven-segment LED patterns. An E r r o r message is returned for all other characters. The UART module designed in Section 8.4 can be used for this purpose. Since the transmission and receiving FIFO buffers provide a storage and flagging mechanism, no additional circuit is needed. We need only expand the decoding and multiplexing circuits to accommodate the additional 110 ports. The UART interface block diagram is sketched in Figure 17.9, in which the other 110 peripherals are omitted to reduce clutter. PicoBlaze's output port, out-port, is connected to a-data of UART. The decoded enable signal is connected to wr-uart, and the data is written to UART transmitting FIFO when it is asserted. Similarly, r - d a t a of UART is routed to PicoBlaze's input multiplexing circuit, Figure 17.9 UART 110 interface. and the decoded clear signal is connected to rd-uart. When the UART receiving FIFO port is specified in an input instruction, the receiving FIFO's output is routed to PicoBlaze's input port, in-port, and the decoded remove signal is asserted one clock cycle to remove one word from the receiving FIFO. The UART interface also needs to route the two status signals, rx-empty and t x - f u l l , to PicoBlaze's input multiplexing circuit. The assembly program needs to check the status before reading or writing the UART's FIFOs. Since the signals are only 2 bits wide, they can be grouped with the previous s and c buttons in the same input port. 17.5.3 Assembly code development Since the previous assembly code is developed in a modular fashion, we can expand the program by adding a routine, proc-uart, to process UART transactions. The main program becomes call init forever : ; m a i n l o o p bod-v call proc-btn call proc-uart call square call load-led-pttn call disp-led jump f o r e v e r ;i n i t i a l i z a t i o n ;check & process buttons ;check & process uart rx ;c a l c u l a t e s q u a r e ; s t o r e l e d p a t t e r n s t o ram ;output led pattern Because of the complexity of the required console operation, the proc-uart is quite involved. The pseudo code of this routine is ; i f (no c h a r a c t e r in UART r e c e i v i n g FIFO) then return ; i n p u t c h a r a c t e r s f r o m FIFO ; if (characters is a ) then input switch value s t o r e i t t o d a t a ram d i s p l a y prompt return ; if (characters is b ) then SQUARE PROGRAM WITH A COMBINATIONAL MULTIPLIER AND UART CONSOLE 437 input switch value store i t to data ram display prompt return ; if (characters is c) then perform i n i t i a l i z a t i o n return ; if (characters is d ) then dump data ram return ; display error message , return We follow the modular development approach and further divide this routine into simpler routines. A key low-level routine is tx-one-byte, which transmits 1 byte via the UART port. Its code is ;input port d e f i n i t i o n s constant rd-flag-port, 00 ; 4 flags (xxxxtrsc): ; I: uart tx f u l l , r : uart rx not empty ; s: s button flag, c: c button flag ;o u t p u t p o r t d e f i n i t i o n s constant uart-tx-port , 04 ;uart receiver port ;r e g i s t e r a l i a s namereg sd, tx-data ... ;data to be tx by uart tx-one-byte : input s6, rd-f lag-port t e s t s6, 08 ;check uart-tx-full jump n z , tx-one-byte ; y e s , keep on waiting output tx-data, uart-tx-port ;no, write t o uart tx f i f o return Since PicoBlaze's processing speed is much higher than the UART's transmission speed, we must prevent buffer overflow. The routine keeps on checking the status of the transmitting FIFO buffer, and writes data only when the buffer is not full. The task ofdumping data RAM requires the most work. It displays the data RAM address and contents as an 8-by-8 table, which lists the byte address first and then the 8 bytes of data in hexadecimal format, as in The routine consists of three major routines: dispram-addr, which sends ASCII codes to display the 5-bit base address in binary format; disp-ram-data, which sends ASCII codes to display 8 bytes of data; and hex-to-ascii, which converts a hexadecimal digit to the corresponding ASCII code. The complete code is shown in Listing 17.3. It includes detailed comments to explain operation of the subroutines. The unmodified subroutines of Listing 17.1 are omitted. Listing 17.3 Square program with a UART console ......................................................... ; s q u a r e c i r c u i t w i t h UART and m u l t i p l i e r i n t e r f a c e ......................................................... ;program operation : 5 ; - read a and b from switch ; - calculate a*a + b*b ; - display data on HyperTerminal and 7-seg led ......................................................... 10 ; data c o n s t a n t s ......................................................... ;s e l e c t e d ASCII c o d e s constant ASCII-0, 30 c o n s t a n t ASCII-1, 31 it c o n s t a n t ASCII-2, 32 c o n s t a n t ASCII-3, 33 constant ASCII-a, 61 constant ASCII-b, 62 c o n s t a n t ASCII-c , 6 3 20 c o n s t a n t ASCII-d, 64 constant ASCII-o, 6F c o n s t a n t ASCII-r, 72 constant ASCII-E, 45 constant ASCII-S, 53 25 c o n s t a n t constant constant constant constant 3" c o n s t a n t ASCII-Q, 51 ASCII-D-U ,44 ASCII-GT, 3E ASCII-SP, 20 ASCII-CR, OD ASCII-LF, OA ; uppercase D ;> ; space ; carriage return ; line feed ......................................................... : d a t a RAM a d d r e s s a l i a s ......................................................... ;< c o n s t a n t a-lsb, 00 c o n s t a n t b-lsb, 02 c o n s t a n t aa-lsb, 04 c o n s t a n t aa-msb, 05 c o n s t a n t bb-lsb, 06 4u c o n s t a n t bb-msb, 07 c o n s t a n t aabb-lsb, 08 c o n s t a n t aabb-msb, 09 c o n s t a n t aabb-cout , OA c o n s t a n t ledO, 10 45 c o n s t a n t ledl, 11 c o n s t a n t led2, 12 c o n s t a n t led3, 13 ......................................................... so ; r e g i s t e r a l i a s ......................................................... ;cotnmonl~v u s e d l o c a l v a r i a b l e s SQUARE PROGRAM WITH A COMBINATIONAL MULTIPLIER AND UART CONSOLE 439 namereg SO, data namereg sl , addr 5s namereg s2, i ;global variables namereg sc, switch-a-b namereg sd , tx-data ;reg for temporary data ; r e g f o r t e m p o r a r y mem & i / o p o r t a d d r ;general -purpose loop index ;ram o f f s e t for current switch input ;data to be tx by uart ; port alias ......................................................... input port definitions constant rd-flag-port, 00 65 ; 4 f l a g s ( x x x x t r s c ) : ; t : uart tx full : r . uart rx not empty ; s: s button flag ; c: c button flag 70 c o n s t a n t sw-port , 01 ;8-bit switches constant uart-rx-port , 0 2 ;u a r t r e c e i v e r p o r t c o n s t a n t mult-prodo-port , 0 3 ;m u l t i p l i c a t i o n p r o d u c t constant mult-prodl-port , 04 ;m u l t i p l i c a t i o n product output port definitions 75 c o n s t a n t sseg0-port , 00 ;7-seg led 0 constant ssegl-port , 01 ;7-seg led 1 constant sseg2_port, 02 ;7-seg led 2 constant sseg3_port, 03 ;7-seg led 3 constant uart-tx-port , 04 ;u a r t r e c e i v e r p o r t so c o n s t a n t mult-src0-port , 0 5 constant mult-srcl-port , 06 ;m u l t i p l i e r o p e r a n d 0 ;multiplier operand I 8 LSBs 8 MSBs ......................................................... ; main program *5 .......................................................... ;c a l l i n g h i e r a r c h y : ;m a i n , - init 94; - tx-prompt - tx-one-byte ; - proc-btn - init ; - proc-uart 95 ; - tx-prompt - init - proc-uart-err - tx-one-byte - dump-mem loo ; - tx-prompt - disp-ram-addr - tx-one-byte - disp-ram-data - tx-one-byte I05 ; - get-upper-nibble . - square - get-lower-nibble - hex-to-ascii - mult-hard IIO ; - load-led-pttn - get-lower-nibble - get-upper-nibble - hex-to-led : - disp-led lli ; . ......................................................................................... c a l l init ;i n i t i a l i z a t i o n forever : ;main loop body 120 c a l l proc-btn c a l l proc-uart c a l l square c a l l load-led-pttn c a l l disp-led I?? jump f o r e v e r ;c h e c k & p r o c e s s b u t t o n s ;check & process uart rx ;c a l c u l a t e s q u a r e ; s t o r e led p a t t e r n s t o ram ;output led pattern ;routine: init ; function : perform initialization , clear register /ram I30 , o u t p u t r e g i s t e r : switch-a-b: cleared to 0 ; temp r e g i s t e r : d a t a , i ......................................................... init : 135 ;c l e a r memory load i , 40 load data, 00 clr-mem-loop : store data, (i) 140 s u b i , 01 jump n z , clr-mem-loop ;clear register load switch-a-b, 00 c a l l tx-prompt 145 return ; u n i t i z e loop index to 64 ;dec loop index ; r e p e a t u n t i l i=O ......................................................... ;r o u t i n e : p r o c - ~ a r t ; function: read uart input char: ISO ; a or b : read a or b from s w i t c h ; c : c l e a r ; d : dump/display data ram o t h e r : error ; input reg: s3 (input port f l a g ) ; temp register used: data ; s4: store received uart char or 00 (no uart input) 155 .......................................................... proc-uart : t e s t s3, 04 jump z , uart-rx-done ;check uart rx status ;go to done i f rx empty ;process received char I60 i n p u t s4, uart-rx-port ; g e t c h a r ;check if received char is a compare s4, ASCII-a ;check ASCII a jump n z , chk-ascii-b ;no, check next i n p u t data, sw-port ;get switch I65 s t o r e data, a-lsb ;w r i t e a t o d a t a ram c a l l tx-prompt ;new prompt line jump uart-rx-done chk-ascii-b : ;check if received char is b 170 c o m p a r e s4, ASCII-b ;check ASCII b jump n z , chk-ascii-c ;no, check next i n p u t data, sw-port ;get switch s t o r e data, b-lsb ;w r i t e b t o d a t a ram c a l l tx-prompt ;new prompt line I75 jump uart -rx-done chk-ascii-c : ;check if received char is c compare s4, ASCII-c ;check ASCII c jump n z , chk-ascii-d ;no check next I00 c a l l init ;c l e a r jump uart-rx-done chk-ascii-d: ;check if received char is d compare s4, ASCII-d ;check ASCII d la jump nz , ascii-undef ined c a l l dump-mem ;dump/display ram jump uart-rx-done ascii-undefined: ;u n d e f i n e d char 190 c a l l proc-uart-error uart-rx-done : return ......................................................... 195 ; r o u t i n e : p r o c - ~ a r t - e r r o r ; f u n c t i o n : display "Error" for unknown uart char ......................................................... proc-uart-error: load tx-data, ASCII-LF 200 c a l l tx-one-byte load tx-data, ASCII-CR c a l l tx-one-byte l o a d tx-data, ASCII-SP c a l l tx-one-byte zns c a l l tx-one-byte l o a d tx-data, ASCII-E c a l l tx-one-byte l o a d tx-data, ASCII-r c a l l tx-one-byte 210 l o a d tx-data, ASCII-r c a l l tx-one-byte :t r a n s m i t LF ;t r a n s m i t CR ; t r a n s m i t SP ; t r a n s m i t SP ;transmit E ;t r a n s m i t r ;transmit r load tx-data , ASCII-o c a l l tx-one-byte ;transmit o load tx-data, ASCII-r :IS c a l l tx-one-byte ;transmit r c a l l tx-prompt return zzo ;r o u t i ti e : dump-men~ ; f u n c t i o n : when d r e c e i v e d , dump 64 b y t e s o f ram as 001000 XX xx XX X X X X x x xx XX 010000 xx xx X X X X X X X X X X x x ... <,-.. ' 111000 xx X X x x x x X X X X X X xx ; temp register used ; s3: as o u t e r l o o p i n d e x s 4 : ram base address :lo dump-mem : load s3, 00 dump-loop : ;l o o p hod-v load s4, s3 <;. slOs4 s10 s4 s10 s4 c a l l disp-ram-addr c a l l disp-ram-data 240 add s3, 01 compare s3, 08 jump n z , dump-loop c a l l tx-prompt return :a< ;addr used as loop index ; g e t ram base addr ( x x x 0 0 0 ) ;i n c l o o p i n d e x ;loop not reach 8 yet ;new prompt ;r o u t i n e : t x - p r o m p t ; f u n c t i o n : g e n e r a t e prompt "SQ>" : temp r e g i s t e r : tx-data 2-5" ;.-.-.-..-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-..-.-.-..-.-.-..-.-.-..-.-..-.-.-..-.-.-..-.-.-..-.-.-. --------------- tx-prompt : load tx-data, ASCII-LF c a l l tx-one-byte load tx-data, ASCII-CR 35 c a l l tx-one-byte load tx-data, ASCII-S c a l l tx-one-byte load tx-data, ASCII-Q c a l l tx-one-byte 260 load tx-data, ASCII-GT c a l l tx-one-byte load tx-data, ASCII-SP c a l l tx-one-byte return ; t r a n s m i t LF ; t r a n s m i t CR ;t r a n s m i t S ;transmit Q ;transmit > ; t r a n s m i t SP SQUARE PROGRAM WITH A COMBINATIONAL MULTIPLIER AND UART CONSOLE 443 ;r o u t i n e : d i s p - r a m - a d d r ; f u n c t i o n : display 6-bit ram addr bbbO0O 270 : i n p u t r e g i s t e r : s4 : base address : temp r e g i s t e r : i , s 7 : 1-bit mask ......................................................... 275 disp-ram-addr : ;new line load tx-data, ASCII-LF call tx-one-byte ; t r a n s m i t LF load tx-data, ASCII-CR 280 call tx-one-byte ;t r a n s m i t CR load tx-data , ASCII-SP call tx-one-byte ;t r a n s m i t SP call tx-one-byte ; t r a n s m i t SP ; i n i t i a l i z e t h e loop index and mask 28s load i, 06 ;addr used as loop index load s7, 20 ; s e t mask to 00I0-0000 tx-loop : ;l o o p b o d v load tx-data, ASCII-1 ;load d e f a u l t ASCII 1 290 test s7, s4 ;check the bit jump nz, tx-01 ;the bit is 1 l o a d t x - d a t a , ASCII-0; ; t h e b i t is 0 , l o a d A S C I I 0 tx-01: call tx-one-byte ; t r a n s m i t the ASCII 1 or 0 29s ; u p d a t e l o o p i n d e x and mask srO s7 ; s h i f t mask b i t sub i, 01 ;d e c l o o p i n d e x jump nz , tx-loop ;loop not reach 0 yet ;done with loop, send ASCII space iw load tx-data, ASCII-SP ; l o a d ASCII SP call tx-one-byte ; t r a n s m i t SP return 305 :r o u t i n e : d i s p - r a m - d a t a ; function: 8-bvte data in form of 00 I1 22 33 44 55 66 77 88 ; input register: s 4 : ram base address (xxx00O) I temp register: i , addr, data disp-ram-data : ;i n i t i a l i z e t h e load i, 08 315 d-ram-loop : ;loop body load addr, s4 loop index and mask ;a d d r u s e d a s loop index 444 PICOBLAZE 110 INTERFACE add addr, i sub addr , 01 calculate addr offset I :send upper nibble fetch data, (addr) c a l l get-upper-nibble c a l l hex-to-ascii ;convert to ascii load tx-data, data lri c a l l tx-one-byte ;send lower nibble fetch data, (addr) c a l l get-lower-nibble c a l l hex-to-ascii ;c o n v e r t t o a s c i i 110 load tx-data, data c a l l tx-one-byte ;send a space load tx-data, A S C I I - S P ; c a l l tx-one-byte ;t r a n s m i t SP ;.3r sub i, 01 ;dec loop index jump n z , d-ram-loop ;loop not reach 0 vet return ~.lo ;r o u t i n e : h e x - t o - a s c i i ; f u n c t i o n : convert a hex number to a s c i i code add 3 0 f o r 0 - 9 , add 37 f o r A-F : it~plrt register: data ......................................................... . ~ hi e x - t o - a s c i i : compare data, Oa jump c , add-30 add data, 07 add-30 : iiu add data, 30 return ;O to 9 , o f f s e t 30 ; a t o f , e x t r a o f f s e t 07 ;r o u t i n e : t x - o n e - b y t e i ~ r; f u n c t i o n : ~ , a i t u n t i l u a r t t x f i f o n o t then write a byte to ,fifo ; input register: tx-data ; temp r e g i s t e r : s6: read port flag :(,I ,--------------------------------------------------------- full; tx-one-byte : input s6, rd-f lag-port test s6, 08 jump n z , tx-one-byte 3hS output tx-data, uart-tx-port return ;check uart_tx_full ;yes , keep on waiting ; n o , w r i t e t o u a r t t.u f i f o ;r o u t i n e : square : 370 f u n c t i o n : c a l c u l a t e a * a + b * b SQUARE PROGRAMWITH A COMBINATIONAL MULTIPLIER AND UART CONSOLE 445 d a t a / r e s u l t stored in ram s t a r t e d w/ SQBASEADDR ; temp r e g i s t e r : s 3 , s 4 , s.5, s 6 , data ......................................................... square : 375 ; c a l c u l a t e a * a fetch s3, a-lsb fetch s4, a-lsb c a l l mult-hard store s6, aa-lsb 380 store s5, aa-msb ;c a l c u l a t e b*b fetch s3, b-lsb fetch s4, b-lsb c a l l mult-hard 38s store s6, bb-lsb store s5, bb-msb ;c a l c u l a t e a*a+b*b fetch data, aa-lsb add data, s6 390 s t o r e d a t a , aabb-lsb fetch data, aa-msb addcy data, s5 store data, aabb-msb load data, 00 395 addcy data, 00 store data, aabb-cout return ;load a ;load a ;c a l c u l a t e a * a ; s t o r e lower byte of a*a ;store upper byte of a*a ;load b :load b ;c a l c u l a t e b * b ; s t o r e lower byte of b*b ; s t o r e upper byte of b*b ;get lower byte of a*a ;add lower byte of a*a+b*b ; s t o r e lower byte of a*a+b*b ;get upper byte of a*a ;add upper byte of a*a+b*b ; s t o r e upper byte of a*a+b*b ;clear data, but keep carry ;get carry from previous + ; s t o r e carry of a*a+b*b 4m ;r o u t i n e : m u l t - h a r d ; function : 8-bit unsigned multiplication using external combinational multiplier; ; input register: s3: multiplicand 405 ; s4: multiplier , output register: s5: upper byte of product s6: lower byte of product ; temp r e g i s t e r : 4,0 ;.-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..-.-.-..--------------- mult-hard: output s3, mult-src0-port output s4, mult-srcl-port input s5, mult-prodl-port 415 input s6, mult-prodo-port return ;The following are the same as the previous l i s t i n g s 420 ; p r o c - b t n , l o a d - l e d - p t t n , d i s p - l e d ; hex-to-led, get-lower-nibble , get-upper-nibble 446 PICOBLAZE 110 INTERFACE 17.5.4 HDL code development The new square circuit adds a UART and a combinational multiplier to an I10 interface. The former is the module discussed in Section 8.4, and the latter can be inferred from the HDL's * operator. The decoding and multiplexing parts of HDL code in Listing 17.2 can be expanded to accommodate the two new peripherals. The complete HDL code is shown in Listing 17.4. The detailed I10 port address assignment can be found in the header section of Listing 17.3. Listing 17.4 PicoBlaze with UART console and multiplier interface module pico-uart ( i n p u t wire clk, reset, i n p u t w i r e [7:01 s w , input wire rx, i n p u t w i r e [1:01 btn, output wire tx, o u t p u t w i r e [3:01 an, o u t p u t w i r e [7:01 sseg 111 ); // signal declaration / / KCPSM3/ROM s i g n a l s w i r e [9:01 address; Ir w i r e [17:0] instruction; w i r e [7:0] port-id, out-port ; r e g [7:0] in-port; w i r e write-strobe , read-strobe ; // 1 / 0 port signals 20 // ozttput enable r e g [6:0] en-d; // four-digit seven-segment led display r e g [ 7 :01 ds3_reg, ds2_reg, dsl-reg , ds0-reg; // two pztshbzrttons 2 r e g btnc-f lag-reg , btns-f lag-reg ; w i r e btnc-flag-next , btns-f lag-next ; wire set-btnc-flag, set-btns-flag, clr-btn-flag; // uart w i r e [7:01 rx-char; 20 w i r e rd-uart , rx-not-empty , rx-empty; w i r e wr-uart , tx-full ; // multiplier r e g [7 :01 m-srco-reg , m-srcl-reg ; w i r e [15:01 prod; ?( // bodv / / ..................................................... " // 1 / 0 modtrles / / ..................................................... disp-mux disp-unit ( . clk(clk1, . reset (reset 1 , . in3(ds3_reg), . in2 (ds2_reg), . in1 (dsl-reg) SQUARE PROGRAM WITH A COMBINATIONAL MULTIPLIER AND UART CONSOLE 447 . in0 (dsO-reg) , . an(an), . sSeg(sseg)) ; debounce btnc-unit ( . clk(cik), .reset(reset), . sw(btn LO]) , .db-ievei(), .db-tick(set-btnc-flag)); debounce btns-unit ( . cik(clk), .reset(reset), . sw(btn[1]), .db-ievei(), .db-tick(set-btns-flag)); uart uart-unit ( . elk (elk), . reset (reset), . rd-uart (rd-uart), . wr-uart (wr-uart) , . rx (rx) , . w-data (out-port) , . tx-full (tx-full), . rx-empty (rx-empty) , . r-data(rx-char), .tx(tx)) ; // combinational multiplier assign prod = m-src0-reg * m-srcl-reg; / / KCPSM and ROM i n s t a n t i a t i o n / / ..................................................... kcpsm3 proc-unit ( . clk(cik), .reset(l'bO), . address(address), uart-rom rom-unit ( . clk(c1k) , . address (address), // output interface port id: ds 0 ds 1 ds 2 ds 3 uart-tx-fifo rn-src0 m-srcl // registers always CI (posedge clk) begin if (en-d[0]) ds0-reg <= out-port ; if (en-d [I]) dsl-reg <= out-port ; if (en-d [2] ds2-reg <= out-port ; if (en-d [3] ds3-reg <= out-port ; if (en-d [5]) m-src0-reg <= out-port ; if (en-d C61) m-srcl-reg <= out-port ; 448 PICOBLAZE 110 INTERFACE end // decoding c i r c u i t for enable signals 100 always Q* if (write-strobe) case (port-id [2:01 ) 3'bOOO: en-d = 7'b0000001; 3'bOOl: en-d = 7'b0000010; 3'bOlO: en-d = 7'b0000100; 3'b011: en-d = 7'b0001000; 3'blOO: en-d = 7'b0010000; 3'b101: en-d = 7'b0100000; default: en-d = 7'b1000000; IIU endcase else en-d = 7'b0000000; assign wr-uart = en-d [41 ; / / ..................................................... // input interface / / ..................................................... // input port id // 0x00: flag IZU // 0x01: switch // 0x02: uart-rx-fifo // 0x03 : prod lower byte // 0x04: prod upper byte / / ..................................................... 125 / / i n p u t r e g i s t e r ( f o r f l a g s ) always Q (posedge clk) begin btnc-flag-reg <= btnc-flag-next; btns-flag-reg <= btns-flag-next; 130 end assign btnc-f lag-next = (set-btnc-f lag) ? l'bl : (clr-btn-flag) ? l J b O : btnc-flag-reg; assign btns-f lag-next = (set-btns-f lag) ? l'bl : 135 (clr-btn-flag) ? 1'bO : btns-flag-reg; // decoding circuit for clear signals assign clr-btn-f lag = read-strobe && (port-id [2:0]= = 3 ' b000) ; I40 assign rd-uart = read-strobe && (port-id [2:0]==3 ' b010) ; // input mzrltiplexing assign rx-not-empty = -rx-empty; always Q* case (port-id C2:OI) 3'bOOO: in-port = {4'b0, tx-full, rx-not-empty, btns-f lag-reg , btnc-f lag-reg); 3'bOOl: in-port = sw; 3'bOlO: in-port = rx-char; 3'b011: in-port = prod [7:01 ; BIBLIOGRAPHIC NOTES 449 I50 default : in-port = prod [15:81 ; endcase endmodule 17.6 BIBLIOGRAPHIC NOTES The basic bibliographic information for this chapter is similar to that for Chapter 15. The downloaded kcpsm file contains a comprehensive UART and timer design example. The Xilinx Web site has pages for "PicoBlaze Forum" and "PicoBlaze User Resources," where additional PicoBlaze examples are available. 17.7 SUGGESTED EXPERIMENTS 17.7.1 Low-frequency counter I An accurate low-frequency counter is discussed in Section 6.3.5. We can treat the period counter, division circuit, and binary-to-BCD conversion circuit as three I10 modules, and replace the top-level FSM with PicoBlaze. Design the 110 interface, derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 17.7.2 Low-frequencycounter II We can reduce the hardware of the frequency counter of Experiment 17.7.1 by replacing the division circuit and binary-to-BCD conversion circuit with software subroutines. Redesign the 110 interface, derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 17.7.3 Auto-scaled low-frequency counter An auto-scaled low-frequency counter is discussed in Experiment 6.5.5. We can use PicoBlaze to perform all non-time-critical functions. Redesign the circuit with PicoBlaze and minimal external hardware. Derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 17.7.4 Basic reaction timer with a software timer The reaction timer is discussed in Experiment 6.5.6. We can redesign the circuit using PicoBlaze. One task of the design is to keep track of the elapsed time interval. This can be done by a software counting routine. Recall that a 50-MHz clock is used on the prototyping board and each instruction takes two clock cycles. We can create a counting loop to record the number of instructions executed and derive the time interval accordingly. Since the interval is at least in the millisecond range, multiple registers are needed for this purpose. Design the I10 interface, derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 17.7.5 Basic reaction timer with a hardware timer We can repeat Experiment 17.7.4 with a customized hardware timer. The timer should be treated as an 110 peripheral. PicoBlaze can output a command to clear, start, or pause the timer, and can input the counter's content. Design the 110 interface, derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 17.7.6 Enhanced reaction timer An enhanced reaction timer keeps track of the last four response times and the fastest response time, and displays the data on Windows HyperTerminal. We can design a console similar to that of Section 17.5. There should be three commands: c: clears all data f : displays the fastest response r: displays the time of the last four responses All other characters: display "error" Expand the design in Experiment 17.7.4 or 17.7.5 to include this feature. Derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 17.7.7 Small-screen mouse scribble circuit A small-screen mouse scribble circuit is discussed in Experiment 13.7.10. We can use PicoBlaze to monitor the activities of the mouse and update the video memory accordingly. Design the 110 interface, derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 17.7.8 Full-screen mouse scribble circuit A full-screen mouse scribble circuit is discussed in Experiment 13.7.1 1. We can use PicoBlaze to monitor the activities of the mouse and update the video memory accordingly. Design the I10 interface, derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 17.7.9 Enhanced rotating banner A VGA rotating banner circuit is discussed in Experiment 14.6.1. Instead ofafixed message, we can enhance this circuit by using a keyboard to enter the message dynamically. Assume that the message buffer is 20 characters long and its characters are updated in a first-infirst-out fashion. Redesign the circuit with PicoBlaze. Design the 110 interface, derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 17.7.10 Pong game The complete pong game is discussed in Section 14.4. Some functions of the design can be implemented by PicoBlaze: Top-level control FSM Top-level two-second timer and two-digit decade counter The circuit that updates the paddle position, ball position, and ball velocities in Listing 13.5 Modify the original circuit, design the I10 interface, derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 17.7.11 Text editor A UART terminal is discussed in Experiment 14.6.5. We can use PicoBlaze to obtain data and commands from the UART and update the tile memory accordingly. Design the 110 interface, derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. This Page Intentionally Left Blank CHAPTER 18 PICOBLAZE INTERRUPT INTERFACE 18.1 INTRODUCTION During normal program execution, a microcontroller polls the 110 peripherals (i.e., checks the status signals) and determines the course of action accordingly. An I10 peripheral is passive and waits for its turn. The interrupt is a mechanism that allows an external I10 peripheral to initiate the operation. It, as the name shows, interrupts normal program execution and starts a service routine for the 110 peripheral. For a microcontroller, the interrupt is usually reserved for a time-critical peripheral operation, which must be processed immediately. The PicoBlaze microcontroller provides support for simple interrupt-handling capability. In this chapter, we examine the PicoBlaze's interrupt mechanism and use an example to illustrate software and interface development. 18.2 INTERRUPT HANDLING IN PICOBLAZE Interrupt handling is a coordinated effort between hardware and software. When an external peripheral needs service through interrupt, it asserts the interrupt signal of PicoBlaze. If the interrupt service is enabled, PicoBlaze completes execution of the current instruction, activates the interrupt-acksignal to acknowledge the acceptance ofthe interrupt request, and then implicitly executes the call 3FF instruction. When the instruction is executed, the current content of the program counter is saved in a stack and the 3FF address is loaded to the programmer counter. Note that the 3FF address is the last location in the instruction FPGA Prototyping by Verilog Examples. B y Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. 454 PICOBLAZE INTERRUPT INTERFACE . - -------- main loop ====== forever: enable interrupt -1- add SO, s3 sub s5,01 ... call criticaltiming ... jump forever .,------time critical segment === critical-timing: disable interrupt ... enable interrupt return 2 ,---interrupt service routine== isr: 4 L returni enable 3 \-- .---interrupt vector === address 3FF jump isr Figure 18.1 Interrupted flow. memory and serves as the starting point of the interrupt service routine. It usually contains a jump instruction, which leads to the body of the service routine. The service should be ended with a returni instruction to return to the interrupted point and resume the previous execution. 18.2.1 Software processing Four instructions are associated with interrupt, as discussed in Section 15.5.9. The enable interrupt and disable interrupt instructions enable and disable the interrupt request, and the two return-from-interrupt instructions, returni enable and returni disable, return execution to the interrupted point. A typical program segment with interrupt service routine is shown in Figure 18.1. It generally consists of the following segments: An initial enable interrupt instruction: used to enable the interrupt service. This is needed since the interrupt request is disabled by default. INTERRUPT HANDLING IN PICOBLAZE 455 clk instruction address interrupt interrupt-ack I ~ h insteruction is preemptedand "call 3FF" is implicitly executed Figure 18.2 Timing diagram of an interrupt event. A jump instruction in the end of the instruction memory (i.e., 3FF): leads to the interrupt service routine. Interrupt service routine: the code that actually performs the requested service. The routine should be ended with a returni instruction. A representative flow of an interrupt event is shown in Figure 18.1. We assume that the external I10 asserts the i n t e r r u p t signal in the middle of the add SO,s 3 instruction. PicoBlaze performs the following steps in sequence: 1. Completes execution of the current execution. 2. Saves the content ofthe program counter, clears the interrupt flag, i , to zero, preserves the zero and carry flags, and loads the program counter with 3FF. 3. Executes the jump isr instruction in the 3FF address. 4. Performs the service routine. 5. Executes the returni instruction, in which the saved program counter and flags are restored. 6. Resumes the interrupted program and executes the sub s 5 , 0 1 instruction. 18.2.2 Timing The detailed timing diagram of the previous interrupt event is shown in Figure 18.2. The basic sequence is: At t i : The external interrupt interface asserts the i n t e r r u p t signal. PicoBlaze continues the normal operation to complete execution of the current add SO, s3 instruction. At t 2 : PicoBlaze recognizes the interrupt and aborts the next instruction (sub s5,Oi) and implicitly executes the call 3FF instruction. At t 3 : PicoBlaze asserts the i n t e r r u p t - a c k signal. It also saves the address of the sub s5,Oi instruction, preserves the zero and carry flags, and clears the interrupt flag to 0. At t 4 : PicoBlaze loads and executes the instruction in address 3FF, jump i s r . The external interrupt interface circuit acknowledges the i n t e r r u p t - a c k signal and deasserts the i n t e r r u p t signal. 456 PICOBLAZE INTERRUPT INTERFACE 1 in-port I reset I out-port I port-id interrupt-ack address KCPSM3 Figure 18.3 Interrupt interface with a single request. At t5: PicoBlaze starts the interrupt service routine. Note that it requires up to five clock cycles from the time that the interrupt signal is asserted to the time that the first instruction of interrupt service routine is executed. 18.3 EXTERNAL INTERFACE The nature of the interrupt request is similar to that of a single-access port discussed in Section 17.3.2. After the request is accepted, it must be cleared so that the same request will not be processed multiple times. The flag FF discussed in Section 8.2.4 can be used for this purpose. 18.3.1 Single interrupt request If there is only one 110 peripheral in a PicoBlaze system that can generate an interrupt request, we just need a single flag FF in the interrupt interface circuit, as shown in Figure 18.3. When the service is required, the external 110 circuit asserted the int request signal for one clock cycle, which sets the flag FF to 1 and activates the interrupt input of PicoBlaze. If the interrupt is enabled in PicoBlaze, it acknowledges acceptance of the request by asserting the interrupt-acksignal for one clock cycle, which clears the flag FF to 0. 18.3.2 Multiple interrupt requests Processing a PicoBlaze system with two or more interrupt requests is more involved. The PicoBlaze microcontroller must determine which peripheral issues the request and clear the corresponding flag FF after the request is accepted. This needs the coordination of the hardware interface and the interrupt service routine. The interrupt interface with two requests is shown in Figure 18.4. The two individual requests, int request0 and int request 1, are connected to two flag FFs, and the output signals of the FFs are passed to an or gate to generate the final interrupt request signal. In addition, the two signals are also routed to the input multiplexer. If at least one request is asserted, the interrupt signal of PicoBlaze is asserted. When PicoBlaze senses the request, it does not know which peripheral or whether both peripherals issue the request. The interrupt service routine must first input the two request signals and check their values according to the assigned priority, and then perform the corresponding service. int request 0 set flag - clr t+ -- >flag FF int request 1 set flag -1 -+ clr >flag FF SOFMlARE DEVELOPMENT CONSIDERATIONS 457 in-port reset instruction outgort potid read-stmbe write-strobe intempt intempt-a& > address KCPSM3 , output decoding - - Figure 18.4 Interrupt interface with two requests. In addition,PicoBlazealso needs to clearthe correspondingflag FF. The i n t e r r u p t- a c k signal cannot be used for this purpose because it is not'known which peripheral's request is accepted when the i n t e r r u p t - a c k signal is asserted. Instead, we need to use a special output decoding circuit to generate a clear tick. The c l r signal of each flag FF is assigned to a unique port id. In the interrupt service routine, we add an output instruction after determining which interrupt request is accepted. The instruction does not actually output any data. It is used to generate a single-clock-cycle tick to clear the correspondingflag FF. To reduce the softwareoverhead and increase response speed,we can design an interrupt controller to facilitate the process. This approach is discussed in Experiment 18.7.5. 18.4 SOFTWARE DEVELOPMENT CONSIDERATIONS 18.4.1 Interrupt as an alternative scheduling scheme Recall that a microcontroller-based application usually follows a simple polling program structure: c a l l initialization-routine forever : c a l l taskl-routine; c a l l task2-routine; ... c a l l taskn-routine, jump forever; Some tasks may involve 110 operations. During execution, the microcontroller checks the VO status in turn and takes actions accordingly. The program structure implicitly implements a round-robin schedule, in which each task waits in turn to be executed. This scheme can work properly if the loop interval is short enough so that each I10 request can be checked and processed in a timely manner. In some applications, there may exist one or two time-critical 110 requests that require immediate attention. The interrupt mechanism provides a way to alter the original schedule and gives certain tasks higher priorities. Since an interrupt can occur at any time, the original loop must consider the frequency of interrupt and the required service time of each interrupt request. This can be complicated if there are multiple interrupt requests and the service routine is involved. mod-500 counter in-port reset out-port potid read-strobe ;-l d q- en sseg > instruction write-strob flag FF + interrupt - interrupt-ack circuit an > address KCPSM3 en > Figure 18.5 Interrupt interface with a timer. 18.4.2 Development of an interrupt service routine The interrupt service routine is somewhat like a subroutine. It suspends normal program execution, performs an independent task, and then resumes the previous execution. However, unlike a subroutine call, an interrupt can occur any time. To resume execution later, the service routine must save the current state (also known as the context) of the PicoBlaze processor. In other words, the service routine must save all registers used in service routine computation and then restore them before returning to normal execution. This process is known as context switching. Since PicoBlaze is a compact 8-bit microcontroller, the hardware support for context switching and scheduling is very limited. We should use the polling scheme in general and keep the interrupt structure simple and straightforward. Instead of worrying about context switching, we can allocate several dedicated registers to be used exclusively in the interrupt service routine. 18.5 DESIGN EXAMPLE The square circuit of Chapter 17 uses a seven-segment LED display to show the values of input operands and result. We use the predesigned LED multiplexing module, dispmux, for this purpose. The design of this module is discussed in Section 4.5.1. It consists of a large counter to generate slow enable pulses and a multiplexing circuit to route the input patterns. To save hardware, we can implement this functionality in software and let PicoBlaze control the 4-bit enable signal, an, and the 8-bit LED signal, sseg, of the four-digit LED display directly. To generate a visually continuous pattern, the enable pulse and LED patterns must be refreshed at a constant rate, as shown in Figure 4.6. While using pure software to keep track of time is possible, the code is tedious and error-prone. We use a dedicated hardware timer and PicoBlaze's interrupt facility to perform the task. The required hardware and software modifications are illustrated in the following subsections. 18.5.1 Interrupt interface The block diagram of the timer and interrupt interface, as well as the new output buffers, is shown in Figure 18.5. The timer is a mod-500 counter and generates a single-clock-cycle tick every 500 clock cycles. Since the 50-MHz clock is used for the timer, the period of the tick is 0.01 ms. Because there is only one interrupt request, we use the flag FF scheme DESIGN EXAMPLE 459 discussed in Section 18.3.1 for the interrupt interface. The tick sets the flag FF and activates the i n t e r r u p t signal of PicoBlaze. 18.5.2 Interrupt service routine development To keep track of the elapsed time, PicoBlaze counts the number of timer ticks. As discussed in Section 18.4.2, we want to keep the interrupt service routine simple and use two dedicated registers, c o u n t n s b and count-lsb, for this task. The two registers are cascaded as a 16-bit register and are incremented each time the interrupt service routine is called. They can count to 0.6 second (i.e., 216 * 0.01 ms). The interrupt-related code segment is namereg se, count-msb ; t i m e r t i c k namereg sf, count-lsb ; t i m e r t i c k ... ;interrupt service routine int-service-routine: add count-lsb, 01 ;inc 1 6 - b i t addcy count-msb, 00 returni enable c o u n t 8 MSBs count 8 LSBs counter ;i n t e r r u p t v e c t o r address 3FF jump int-service-routine 18.5.3 Assembly code development With the timing information available, we can derive a new subroutine, displaynux-out, for the LED display. This routine replaces the disp-led routine used in Chapter 17. Two new output buffers are needed to store the an and s s e g signals, as shown in Figure 18.5. The main task of the subroutine is to store the an pattern, which can be "111O", "1101"," 1011", or "01 11",and the corresponding seven-segment LED pattern to the registers periodically. As discussed in Section 4.5.1, the refreshing rate should be around from a few hundred to a few thousand hertz. In our code we update these registers every 21° ticks, which is about 10 ms. We also use a register, led-pos, to keep track of the current display position (i.e., one of the four LED displays). To incorporate the new interrupt feature into Listing 17.3, the code is modified as follows: Add new port and register definitions. Replace the original disp-led routine with the d i s p l a y n u x - o u t routine. Add the enable interrupt instruction in the i n i t routine to enable interrupt handling. Initialize the led-pos, c o u n t n s b , and count-lsb registers in the i n i t routine. Add the interrupt service routine. The modified portion of the assembly code is shown in Listing 18.1. Listing 18.1 Square program with interrupt interface ... :r e g i s t e r a l i a s namereg sb, led-pos ;l e d d i s p p o s i t i o n (0, I , 2 o r 3 ) namereg se, count-msb ; t i m e r t i c k c o u n t 8 MSBs s namereg sf, count-lsb ;t i m e r t i c k c o u n t 8 LSBs 460 PICOBLAZE INTERRUPT INTERFACE ;output port definitions constant an-port , 00 constant sseg-port , 01 10 . . . ; main program c a l l init forever : ;main l o o p b o d y 15 c a l l proc-btn c a l l square call load-led-pttn c a l l display-mux-out jump forever ;i n i t i a l i z a t i o n ;check & process buttons ;c a l c u l a t e s q u a r e ; s t o r e led p a t t e r n s t o ram ; multiplex led patterns 20 ......................................................... ;r o u t i n e : i n i f ......................................................... init : 5 enable interrupt ... load led-pos, 00 load count-msb, 00 load count-lsb, 00 30 return ......................................................... ;r o u t i n e : d i s p l a y - m u x - o u t ; function: generate enable pulse & led pattern IS ; for 4-digit 7-segment led display ; input register: count-msb , count-lsb : timer count led-pos : current led position ; output register: 40 ; led-pos : updated led position ; tmp r e g i s t e r : data, addr ......................................................... display-mux-out : compare count-msb , 0 2 ;c o u n t =00000100~0000OOOO 5 jump c , mux-out-done ;clear time counter (count > 20) load count-lsb, 00 load count-msb, 00 ;update 7-segment led position SO add led-pos, 01 compare led-pos, 04 jump nz , gen-an-signal load led-pos, 00 ;l e d - p o s wraps a r o u n d gen-an-signal : 55 ; g e n e r a t e 4 - b i t a n o d e e n a b l e s i g n a l load data, OE ;xxxx-11 10 compare led-pos, 00 jump z, shift-an-0 compare led-pos, 01 6 jump z , shift-an-1 compare led-pos, 02 jump z, shift-an-2 sll data ;shift shift-an-2: 65 slldata ;shift shift-an-1: sll data ;shift shift-an-0: output data, an-port 70 :o ~ r t p u t7-seg l e d p a t t e r n load addr, led0 add addr, led-pos fetch data, (addr) output data, sseg-port 7s mux-out-done : return Ill0 Ill0 I110 3 times 2 times I times ;r o u t i n e : i n t e r r u p t s e r v i c e routine RO : f u n c t i o n ; i n c r e m e n t 16- b i t c o u n t e r ; input register: count-msb , count-lsb : timer count : ozrtput r e g i s t e r : count-msb , count-lsb : incremented *5 .......................................................... int-service-routine: add count-lsb, 01 addcy count-msb , 00 returni enable ;i n c 16- b i t c o u n t e r YO ......................................................... ;interrupt vector ......................................................... address 3FF 5 jump int-service-routine ......................................................... :The following are the same as the previous l i s t i n g s : ; proc-btn , load-led-pttn , loo ; h e x _ t o _ l e d , g e t ~ l o w e r - n i b b l e, g e t - u p p e r - n i b b l e ; square , multLsoft , ... ......................................................... 18.5.4 HDL code development The 110 interface of the interrupt-based square circuit includes three parts. The input interface is similar to that in Section 17.4. The output interface consists of a decoding circuit and two output registers for the an and sseg signals, as shown on the right of Figure 18.5. The interrupt interface consists of a timer and a flag FF, as shown on the left of Figure 18.5. The HDL code basically follows the block diagram and is shown in Listing 18.2. Listing 18.2 PicoBlaze-based square circuit with interrupt module pico-int ( input wire clk, reset, input wire [7:01 sw, s input wire [1:0] btn, output wire [3:01 an, o u t p u t w i r e [ 7 : 0 1 sseg 1; 10 // s i g n a l d e c l a r a t i o n // KCPSM3/ROM s i g n a l s wire [9:0] address; wire [17:01 instruction; w i r e [ 7 : 01 port-id , out-port ; 15 r e g [ 7 : 0 1 in-port ; wire write-strobe , read-strobe ; w i r e interrupt , interrupt-ack ; // 1 / 0 port signals // output enable 20 r e g [ 1 : 0 1 en-d; // four-digit seven-segment led d i s p l a y reg [7:01 sseg-reg; reg [3:01 an-reg; // two pushbuttons 25 r e g btnc-f lag-reg , btns-f lag-reg ; wire btnc-f lag-next , btns-f lag-next ; wire set-btnc-flag, set-btns-flag, clr-btn-flag; // i n t e r r u p t r e l a t e d signals r e g C8: 01 timer-reg; lo wire [ 8 : 0 1 timer-next ; wire ten-us-tick; r e g timer-f lag-reg ; wire timer-f lag-next ; 35 //body / / ..................................................... // 1 / 0 modules / / ..................................................... debounce btnc-unit JO (.clk(clk), .reset(reset), .sw(btn[Ol), .db-level(), .db-tick(set-btnc-flag)); debounce btns-unit ( . clk(c1k) , . reset (reset ) , . sw (btn Ell , .db-level(), .db-tick(set-btns-flag)); a / / ..................................................... / / KCPSM a n d ROM i n s t a n t i a t i o n / / ..................................................... .instruction(instruction), .port-id(port-id), .write-strobe(write-strobe), .out-port(out-port), .read-strobe(read-strobe), .in-port(in-port), .interrupt(interrupt), .interrupt-ack(interrupt-ack)); int-rom rom-unit 55 ( . clk(c1k) , .address(address), .instruction(instruction)); / / -------------------------------------======~========= // output interface / / ..................................................... 60 // // // outport port id: 0-x-00: an 0x01: ssg // registers 65 always Q(posedge clk) begin if (en-d C01) an-reg <= out-port [3:01 ; if (en-dC11) sseg-reg <= out-port ; end assign an = an-reg; assign sseg = sseg-reg; // decoding circuit for enable signals 75 always Q* if (write-strobe) case (port-id [Ol) l'bO: en-d = 2'bOl; l'bl: en-d = 2'blO; endcase else en-d = 2'bOO; / / ..................................................... // inp~rt interface // input port id // 0x00: flag // 0x01: switch 90 // input r e g i s t e r ( f o r f l a g s ) always Q (posedge clk) begin btnc-flag-reg <= btnc-flag-next; btns-flag-reg <= btns-flag-next; 95 end assign btnc-flag-next = (set-btnc-flag) ? l'bl : (clr-btn-flag) ? l'bO : btnc-flag-reg; assign btns-flag-next = (set-btns-flag) ? l'bl : 100 (clr-btn-flag) ? l'bO : btns-flag-reg; // decoding c i r c u i t for clear signals assign clr-btn-f lag = read-strobe && (port-id [O]==l ' bO) ; // input multiplexing 105 always Q* case (port-id [O] l'bO: in-port = {6'b0, btns-flag-reg, btnc-flag-reg); l'bl: in-port = sw; endcase 110 / / ..................................................... // interrupt interface / / ..................................................... // 10 us c o u n t e r 115 always Q(posedge clk) timer-reg <= timer-next ; assign ten-us-tick = ( t i m e r _ r e g = = 4 9 9 ); assign timer-next = ten-us-tick ? 0 : timer-reg + 1; // I0 us t i c k f l a g 120 always @(posedge clk) timer-flag-reg <= timer-flag-next; assign timer-f lag-next = (ten-us-tick) ? 1' bl : (interrupt-ack) ? l'bO : timer-flag-reg; I25 // i n t e r r u p t r e q u e s t assign interrupt = timer-f lag-reg; endmodule 18.6 BIBLIOGRAPHIC NOTES The bibliographic information for this chapter is similar to that for Chapters 15 to 17. 18.7 SUGGESTED EXPERIMENTS 18.7.1 Alternative timer interrupt service routine The interrupt service routine in Listing 18.1 uses two dedicated registers to record the number of timer ticks. The two registers thus cannot be used for other computation. An alternative is to use 2 bytes of the data RAM for this purpose and use the registers only temporarily in the service routine. Since an interrupt can occur anytime, we must save and restore the corresponding registers. For example, if the SO and sl registers are used in the service routine for computation, their contents must be saved when the service routine is invoked and then restored later when the computation is completed. Derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 18.7.2 Programmable timer We can replace the mod-500 counter of Section 18.5 with a general mod-m counter and thus make the timer "programmable." The new timer operates as follows: a m is a 12-bit unsigned number. Figure 18.6 Interrupt interface with a four-request interrupt handler. ThefourLSBsofn~is"1111". The timer has an 8-bit register to store the eight MSBs of m. The register is treated as a new output port of PicoBlaze. A new pushbutton controls the loading of the register. When it is pressed, PicoBlaze inputs the value from the 8-bit switch and outputs the value to the timer's register. Design the new 110 interface, derive the assembly and HDL codes, and compile and synthesize the circuit. Load different values in the timer and observe what happens to the LED display. 18.7.3 Set-button interrupt service routine In the square circuit discussed in Section 17.4, the s button is used to load the n and b operands from the 8-bit switch. Its status is polled continuously in the main loop. We can revise this portion of the code and use an interrupt mechanism to perform this task. The interrupt service routine involves several temporary registers, and they must be saved and restored properly, as discussed in Experiment 18.7.1. Design the new 110 interface, derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 18.7.4 Interrupt interface with two requests Assume that we want to implement both the timer interrupt request of Listing 18.1 and the set-button interrupt request of Experiment 18.7.3 in a PicoBlaze system. Follow the discussion in Section 18.3.2 to design the new interrupt interface and interrupt service routine. Derive the assembly and HDL codes, compile and synthesize the circuit, and verify its operation. 18.7.5 Four-request interrupt controller An interrupt controller helps the processor to process multiple interrupt requests. The block diagram of a four-request interrupt controller is shown in Figure 18.6. The interrupt controller should contain four flag FFs and a special priority encoding circuit. If one or more interrupt requests are activated, the controller determines which request has the highest priority, places its 2-bit code on the req-idport, and asserts the int signal. When PicoBlaze asserts the interrupt-ack signal, the controller clears the corresponding flag. For simplicity, we assume that int-request-3has the highest priority and int-request-0 has the lowest priority. Derive HDL code for the interrupt controller and repeat Experiment 18.7.4using the new controller (the two unused interrupt requests can be tied to 0). APPENDIX A SAMPLE VERILOG TEMPLATES A.l NUMBERS AND OPERATORS A.l.l Sized and unsized numbers number stored value comment 5'bllOlO 5'blI-010 5'032 5 'hla 5'd26 5'bO 5'bl 5'bz 5'bx 5'bxOl -5 'b0000 1 ' b11010 'hee 1 -1 11010 11010 11010 11010 11010 00000 00001 ZZZZZ XXXXX xxx0l I1111 - ignored 0 extended 0 extended z extended x extended x extended 2's complement of 00001 00000000000000000000OOOOOOOllOlO extended to 32 bits 00000000000000000000OOOOl1101110 extended to 32 bits 00000000000000000000000000000001 extended to 32 bits 11111111111111111111111111111111 extended to 32 bits FPGA Proto@ping by Verilog Examples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. A.1.2 Operators n p e of operation Arithmetic Operator symbol + - * / % +* Description addition subtraction multiplication division modulus exponentiation Number of operands 2 2 2 2 2 2 Shift >> logical right shift 2 << logical left shift 2 >>> arithmetic right shift 2 <<< logical left shift 2 Relational > greater than 2 < less than 2 >= greater than or equal to 2 <= less than or equal to 2 Equality -- equality != inequality --- case equality I == case inequality Bitwise - bitwise negation 1 & bitwise and 2 .I bitwise or bitwise xor 2 2 Reduction & reduction and 1 .I reduction or reduction xor 1 1 Logical ! logical negation 1 && logical and 2 II logical or 2 Concatenation { } concatenation any { { ) ) replication any Conditional ?: conditional 3 A.2 GENERAL VERILOG CONSTRUCTS A.2.1 Overall code structure Listing A . l Overall code structure module bin-counter // optional parameter declaration #(parameter N=8) // default 8 // port declaration 5 ( input wire clk, reset, // input wire syn-clr, load, en, // input wire [N-1:Ol d, // output wire max-tick, // 10 output wire [N-1:Ol q // ); clock & reset input control input data output status output data // constant declaration localparam MAX = 2**N - 1; I? // signal declaration reg IN-1:01 r-reg, r-next; // body ............................................. 20 // c o m p o n e n t i n s t a n t i a t i o n ............................................. // no i n s t a n t i a t i o n in t h i s code zr // memory e l e m e n t s // register always Q(posedge clk, posedge reset) i f (reset) 1u r-reg <= 0; else r-reg <= r-next; 35 // combinational c i r c u i t s // next-.state logic always Q* i f (syn-clr) r-next = 0; e l s e i f (load) r-next = d; e l s e i f (en) r-next = r-reg + 1; 45 else r-next = r-reg; // output logic a s s i g n q = r-reg; a s s i g n max-tick = (r-reg==2**N-1) ? l J b l : l J b O ; 50 endmodule A.2.2 Component instantiation Listing A.2 Component instantiation template module counter-inst ( i n p u t w i r e clk , reset, input wire syn-clrl6, loadl6, en16, 5 i n p u t w i r e [15:01 d , output wire max-tick8, max-tickl6, o u t p u t w i r e [15:01 q 1; lo //body // i n s t a n t i a t i o n of 16-bit counter, a l l ports used bin-counter #(.N(16)) counter-16-unit ( . clk(c1k) , .reset (reset), . syn-clr (syn_clrl6), . load(loadl6), . en(enl61, IS .d(d), .max-tick(max_tickl6), . q ( q ) ) ; // i n s t a n t i a t i o n of free-running 8-bit counter // with only the max-tick signal bin-counter counter-8-unit (.clk(clk), .reset(reset), 20 . syn-clr (1 'bO), . load(lJbO), . en(lJbl) , .d(8'h00), .max-tick(max_tick8), . q O ) ; endmodule A.3 ROUTING WITH CONDITIONAL OPERATOR AND IF AND CASE STATEMENTS A.3.1 Conditional operator and if statement Listing A.3 Priority encoder using conditional operator and if statement ( i n p u t w i r e [ 4 : 11 r , o u t p u t w i r e [2:0] yl, o u t p u t r e g [2:0] y2 s 1; // Conditional operator a s s i g n yl = (r [41) ? 3lb100 : (r[31) ? 3'b011 : (r [ 2 ] ) ? 3'bOlO : // can also use ( r [ 4 ] = = l ' b l ) // I f statement 15 // - each branch can contain multiple statements // with begin . . . end delimiters a l w a y s Q* i f (rC41) y2 = 3'blOO; 20 e l s e i f (r [31) y2 = 3'b011; e l s e i f (r C21) y2 = 3'bOlO; e l s e i f (r [I]) zj y2 = 3'bOOl; else y2 = 3'bOOO; endmodule A.3.2 Case statement Listing A.4 Priority encoder using case statement module prio-encoder-case ( i n p u t w i r e [4:11 r , o u t p u t r e g [2:01 y 1 , y 2 5 1; // case statement // - each branch can contain multiple statements // with begin . . . end delimiters 10 always Q* case (r) 4'b1000, 4'b1001, 4'b1010, 4'b1011, 4'b1100, 4'b1101, 4'b1110, 4'bllll: yl = 3'blOO; 4'b0100, 4'b0101, 4'b0110, 4'b0111: yl = 3'b011; 4'b0010, 4'bOOll: yl = 3'bOlO; 4'b0001: 20 yl = 3'bOOl; 4'boo00 : // d e f a u l t can also be used yl = 3'bOOO; endcase 2% // c a s e z s t a t e m e n t always Q* c a s e z (r) 4'bl???: y 2 = 3'blOO; // u s e ? f o r don ' t - c a r e 4'b01??: y2 = 3'bOll; 30 4'b001?: y2 = 3'bOlO; 4'bOOOl: y2 = 3'bOOl; 4'bOOOO: y2 = 3'bOOO; // default can also be used endcase 35 endmodule A.4 COMBINATIONAL CIRCUIT USING AN ALWAYS BLOCK A.4.1 Always block without default output assignment Listing A.5 Always block template (without default output assignment) module compare-no-def ult ( input wire a, b, output reg gt, eq 5 1; / / - u s e @* t o i n c l u d e a l l i n p u t s i n s e n s i t i v i t y l i s t // - e l s e branch cannot be omitted // - a l l outputs must be assigned in a l l branches 10 a l w a y s O * i f (a > b) begin gt = l'bl; eq = l J b O ; end e l s e i f (a == b) begin gt = l J b O ; eq = l'bl; end else // else branch cannot be omitted begin gt = l J b O ; eq = l J b O ; 25 end endmodule A.4.2 Always block with default output assignment Listing A.6 Always block template (with default output assignment) module compare-with-default ( input wire a , b, output reg gt, eq MEMORY COMPONENTS 473 // - u s e @* t o i n c l u d e a l l i n p u t s i n s e n s i t i v i t y l i s t // - assign each output with a default value always Q* lo begin gt = l'bO; // d e f a u l t value f o r g t eq = I'bO; // d e f a u l t value f o r eq i f (a > b) gt = l'bl; e l s e i f (a == b) eq = l'bl; end endmodule A.5 MEMORY COMPONENTS A.5.1 Register template Listing A.7 Register template module reg-template ( input wire c l k , reset, input wire en, 5 i n p u t w i r e [ 7 : 01 ql-next , q2-next , q 3 _ n e x t , output reg [7:01 ql-reg, q2-reg, q3-reg 1; 10 // register without reset ............................................. / / use n o n b l o c k a s s i g n m e n t ( <= ) always Q(posedge clk) ql-reg <= q l - n e x t ; Ii ............................................. // r e g i s t e r with asynchronozrs reset / / u s e n o n b l o c k a s s i g n m e n t ( <= ) I always Q(posedge c l k , posedge reset) i f (reset) q2-reg <= 8'bO; else q2-reg <= q 2 - n e x t ; 3 ............................................. // r e g i s t e r with enable and asynchronous ............................................. / / use n o n b l o c k a s s i g n m e n t ( <= ) reset 474 SAMPLE VERILOG TEMPLATES 3 always @(posedge clk, posedge reset) if (reset) q 3 - r e g <= 8 ' b O ; else if (en) q 3 - r e g <= q 3 - n e x t ; 35 endmodule A.5.2 Register file Listing A.8 Register file module reg-f i l e #( parameter B = 8 , // number of b i t s W = 2 // number of address 5 1 ( input wire clk, input wire wr-en, i n p u t w i r e [W-1:OI w - a d d r , r - a d d r , input wire [B-1:Ol w-data, output wire [B-1:Ol r - d a t a ); bits // signal declaration 15 r e g [B-1:Ol a r r a y - r e g [2**W-1:Ol ; // body // write operation always @(posedge clk) 20 i f (wr-en) a r r a y - r e g [w-addr] <= w - d a t a ; // read operation assign r-data = array-reg [r-addrl ; A.6 REGULAR SEQUENTIAL CIRCUITS Listing A.9 Sequential circuit template II // Universal counter function table ,, // s y n - c l r load en q* 5 // // I - - 0 // 0 1-d // 0 0 I q+l operation synchronous clear parallel load count up REGULAR SEQUENTIAL CIRCUITS 475 // 0 0 0 9 pause module bin-counter # ( p a r a m e t e r N=8) // d e f a u l t 8 ( input wire clk, r e s e t , // IS input wire s y n - c l r , l o a d , e n , // input wire [N-1:01 d , // output wire max-tick, // o u t p u t wire [N-1:OI q // 1; 20 // constant declaration l o c a l p a r a m MAX = 2**N - 1 ; // signal declaration reg [N-1:Ol r - r e g , r - n e x t ; clock & reset input control input data output status output data // r e g i s t e r ............................................. 30 // register always O(posedge c l k , posedge r e s e t ) if (reset) r - r e g <= 0 ; else 3s r - r e g <= r - n e x t ; ............................................. // next-state logic ............................................. always Q* 40 if (syn-clr) r-next = 0; else if (load) r-next = d; else if (en) r-next = r-reg + 1; else r-next = r-reg; ............................................. // output logic ............................................. assign q = r-reg; assign max-tick = (r-reg==2**N-1) ? l ' b l : 17bO; endmodule (a) State diagram (b) A S M chart Figure A.l State diagram and ASM chart of an FSM template. A.7 FSM Listing A.10 FSM template // code f o r [ h e FSM in Figure A . 1 module f sm-eg-2-seg ( input wire clk, reset, input wire a, b, output reg yo, yl ); // symbolic state declaration 10 l o c a l p a r a m [1:0] SO = 2Ib00, sl = 2'b01, s2 = 2'biO; // signal declaration r e g [I:01 state-reg , state-next ; FSM 477 // state register always Q(posedge clk, posedge r e s e t ) if (reset) s t a t e - r e g <= s o ; else s t a t e - r e g <= s t a t e - n e x t ; // next-state logic and output logic always Q* zs begin state-next = state-reg; // default next s t a t e : the same yl = l'bO; // default output: 0 yo = l ' b O ; // default output: 0 case (state-reg) SO : begin yl = l'bl; if (a) if (b) begin state-next = s2; yo = l ' b l ; end else state-next = s l ; end s l : begin yl = l'bl; if (a) s t a t e - n e x t = SO; end s 2 : s t a t e - n e x t = SO; d e f a u l t : s t a t e - n e x t = SO; endcase end sa e n d m o d u l e A.8 FSMD Figure A.2 ASMD chart of an FSMD template. Listing A . l l FSMD template / / c o d e f o r t h e FSMD shown i n F i g u r e A . 2 module f i b ( input wire clk, reset, input wire start, i n p u t w i r e C4:OI i , FSMD 479 output reg ready, done-tick , output wire [19:0] f 1; 10 // symbolic state declaration l o c a l p a r a m 11 :01 idle = 2'b00, op = 2 ' b 0 1 , IS done = 2'blO; // signal declaration r e g [ I : 01 s t a t e - r e g , s t a t e - n e x t ; reg [19:0] to-reg , to-next , tl-reg , tl-next ; 20 reg [4:01 n-reg , n-next ; // body // s t a t e & data r e g i s t e r s always O(posedge clk, posedge reset) 25 if (reset) begin s t a t e - r e g <= i d l e ; t o - r e g <= 0 ; t l - r e g <= 0 ; n - r e g <= 0 ; end else begin s t a t e - r e g <= s t a t e - n e x t ; t o - r e g <= t o - n e x t ; t l - r e g <= t l - n e x t ; n - r e g <= n - n e x t ; end // next-state logic and data path functional units 40 a l w a y s O* begin state-next = s t a t e - r e g ; // default return to same s t a t e ready = l'bO; // default output 0 done-tick = l'bO; // default output 0 to-next = to-reg; // default keep previous value tl-next = tl-reg; // default keep previous value n-next = n-reg; // default keep previous value case (state-reg) idle : begin ready = l J b l ; if (start) begin to-next = 0; tl-next = 20'dl; n-next = i ; state-next = op; end end 61) op : i f (n-reg==O) begin tl-next = 0; state-next = done; end else if (n-reg==l) state-next = done; else begin tl-next = tl-reg + to-reg; to-next = tl-reg; n-next = n-reg - 1; end done : begin done-tick = l ' b l ; state-next = idle; end default: state-next = idle; endcase end / / OLltplrt assign f = tl-reg; A.9 S3 BOARD CONSTRAINT FILE (S3 .UCF) # Pin assignment f o r Xilinx # Spartan-3 S t a r t e r board ......................................................... # c l o c k and r e s e t ......................................................... NET " c l k " LOC = " T 9 " ; NET " r e s e t " LOC = " L 1 4 " ; # buttons & switches ......................................................... # 4 pushbuttons NET " b t n < O > " LOC = "M13"; NET " b t n < l > " LOC = "M14"; NET " b t n < 2 > " LOC = " L 1 3 " ; #NET " b t n < 3 > " LOC = " L 1 4 " ; # b t n < 3 > also used as reset # 8 slide switches NET " s w < O > " LOC = " F 1 2 " , NET " s w < l > " NET " s w < 2 > " NET " s w < 3 > " NET " s w < 4 > " NET " s w < 5 > " NET " s w < 6 > " NET " s w < 7 > " LOC = " G 1 2 " ; LOC = " H 1 4 " ; LOC = " H 1 3 " ; LOC = " 5 1 4 " ; LOC = " 5 1 3 " ; LOC = " K 1 4 " ; LOC = " K 1 3 " ; ......................................................... # RS232 ......................................................... NET " r x " LOC = " T 1 3 " 1 DRIVE=8 I SLEW=SLOW; NET " t x " LOC = " R 1 3 " I DRIVE=8 I SLEW=SLOW; ......................................................... # 4-digit time-multiplexed 7-segment ......................................................... # digit enable NET " a n < O > " LOC = " D 1 4 " ; NET " a n < l > " LOC = " G 1 4 " ; NET " a n < 2 > " LOC = " F 1 4 " ; NET " a n < 3 > " LOC = " E 1 3 " ; LED d i s p l a y # 7-segment l e d segments NET " s s e g < 7 > " LOC = " P 1 6 " ; # d e c i m u l p o i n t NET " s s e g < 6 > ' LOC = " E 1 4 " ; # s e g m e n t a NET " s s e g < 5 > " LOC = "G13" , # s e g m e n t b NET " s s e g < 4 > " LOC = " N 1 5 " ; # s e g m e n t c NET " s s e g < 3 > " LOC = " P 1 5 " ; # s e g m e n t d NET " s s e g < 2 > " LOC = " R 1 6 " ; # s e g m e n t e NET " s s e g < l > " LOC = " F 1 3 " ; # s e g m e n t f NET " s s e g < O > " LOC = " N 1 6 " ; # s e g m e n t g ......................................................... # 8 d i s c r e t e LEDs ......................................................... NET " l e d < O > " NET " l e d < l > " NET " l e d < 2 > " NET " l e d < 3 > " NET " l e d < 4 > " NET " l e d < 5 > " NET " l e d < 6 > " NET " l e d < 7 > " LOC = " K 1 2 " ; LOC = " P 1 4 " ; LOC = " L 1 2 " ; LOC = "N14"; LOC = " P 1 3 " ; LOC = " N 1 2 " ; LOC = ' 1 P 1 2 " ; LOC = " P 1 1 " : ......................................................... # VGA outputs ......................................................... NET " r g b < 2 > " NET " r g b < i > " NET " r g b < O > " NET " v s y n c " NET " h s y n c " LOC = " R 1 2 " I DRIVE=8 I SLEW=FAST; LOC = " T 1 2 " I DRIVE=8 1 SLEW=FAST; LOC = " R 1 1 " I DRIVE=8 I SLEW=FAST; LOC = " T 1 0 " I DRIVE=8 I SLEW=FAST; LOC = "R9" I DRIVE=8 I SLEW=FAST; ......................................................... # PS2 port ......................................................... NET "ps2c" LOC="M1GW I IOSTANDARD=LVCMOS33 I DRIVE=8 ISLEW=SLOW: NET "ps2d1'LOC="M15" I IOSTANDARD=LVCMOS33 I DRIVE=8 ISLEW=SLOW; ......................................................... # two SRAM chips ......................................................... # shared 18-bit memory a d d r e s s NET "ad<17>" LOC="L3" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad<16>" LOC="KS1'I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad<15>" LOC="K3" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad<14>" LOC="J3" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad<13>I1 LOC="J4" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad<12>" LOC="H4" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad" LOC="H3" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad" LOC="GS" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad<9>" LOC="E4" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad<8>" LOC="E3" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad<7>" LOC="F4" I IOSTANDARD = LVCMOS33 I SLEW=FAST: NET "ad<6>" LOC="F3" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad<5>" LOC="G4" I IOSTANDARD = LVCMOS33 I SLEW=FAST; IOI NET "ad<4>" LOC="L4" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad<3>" LOC="M3" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad<2>I1 LOC="M4" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad" LOC="N3" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET "ad" LOC="LSM I IOSTANDARD = LVCMOS33 I SLEW=FAST; # shared oe, we NET "oe-n" LOC="K4" I IOSTANDARD = LVCMOS33 I SLEW=FAST; NET " we-n" LOC="G3" 1 IOSTANDARD = LVCMOS33 I SLEW=FAST; # sram chip 1 data, ce, ub, lb NET "dio-a" LOC="RIN I IOSTANDARD=LVCMOS33 NET "dio-a" LOC="PIM I IOSTANDARD=LVCMOS33 NET "dio-a<13>" LOC="L2" I IOSTANDARD=LVCMOS33 NET "dio-aIt LOC="J2" I IOSTANDARD=LVCMOS33 NET "dio-a" LOC="Hll'I IOSTANDARD=LVCMOS33 NET "dio-a" LOC="F2" I IOSTANDARD=LVCMOS33 NET "dio-a<9>" LOC="P8" I IOSTANDARD=LVCMOS33 NET "dio-a<8>" LOC="D3" I IOSTANDARD=LVCMOS33 NET "dio-a<7>" LOC="B1" I IOSTANDARD=LVCMOS33 NET "dio-a<6>" LOC="C1" I IOSTANDARD=LVCMOS33 NET "dio-a<5>" LOC="C2" I IOSTANDARD=LVCMOS33 NET " dio-a < 4 > " LOC="RS1' I IOSTANDARD=LVCMOS33 NET "dio-a<3>" LOC="TSN I IOSTANDARD=LVCMOS33 NET "dio-a<2>" LOC="RGM I IOSTANDARD=LVCMOS33 NET "dio-a" LOC="T8" I IOSTANDARD=LVCMOS33 NET " dio-a " LOC="N7" I IOSTANDARD=LVCMOS33 NET "ce-a-nu LOC="P7" I IOSTANDARD=LVCMOS33 NET "ub-a-n" LOC="T4" I IOSTANDARD=LVCMOS33 53 BOARD CONSTRAINT FILE (S3.UCF) 483 NET "lb-a-n" LOC="P6" I IOSTANDARD=LVCMOS33 I SLEW=FAST; # sram chip 2 data, ce, ub, lb NET "dio-bI1 LOC="N1" I IOSTANDARD=LVCMOS33 NET " dio-b " LOC="M1" I IOSTANDARD=LVCMOS33 NET "dio-b" LOC="K2" I IOSTANDARD=LVCMOS33 NET "dio-b" LOC="C3" I IOSTANDARD=LVCMOS33 NET "die-b " LOC="F5" I IOSTANDARD=LVCMOS33 NET " dio-b " LOC="GI " I IOSTANDARD=LVCMOS33 NET "dio-b<9>" LOC="E2" I IOSTANDARD=LVCMOS33 NET " dio-b <8>" LOC="D2" I IOSTANDARD=LVCMOS33 NET " dio-b < 7 > " LOC='Dll' I IOSTANDARD=LVCMOS33 NET "dio-b<6>" LOC="Ell' I IOSTANDARD=LVCMOS33 NET "dio-b<5>" LOC="G2" I IOSTANDARD=LVCMOS33 NET "dio-b<4>" LOC="Jl" I IOSTANDARD=LVCMOS33 NET "dio-b<3>" LOC="Kl" I IOSTANDARD=LVCMOS33 NET "dio-b<2>" LOC="M2" I IOSTANDARD=LVCMOS33 NET "dio-b" LOC="N2" I IOSTANDARD=LVCMOS33 NET "die-b" LOC="P2" I IOSTANDARD=LVCMOS33 NET "ce-b-n" LOC="N5" I IOSTANDARD=LVCMOS33 NET "ub-b-n" LOC="R4" I IOSTANDARD=LVCMOS33 NET " lb-b-n" LOC="P5" I IOSTANDARD=LVCMOS33 ......................................................... # Timing constraint of S3 50-MHz onboard oscillator # name of the clock signal is clk ......................................................... NET "clk" TNM-NET = "clk"; TIMESPEC "TS-clk" = PERIOD "clk" 40 ns HIGH 50 %; This Page Intentionally Left Blank REFERENCES 1. P. J. Ashenden, The Designer's Guide to VHDL, 2nd ed., Morgan Kaufmann, 200 1. 2. J. Axelson, Serial Port Complete, 2nd ed., Lakeview Research, 2007. 3. L. Bening and H. D. Foster, Principles of Ver~jiablRe TL Design, 2nd ed., Springer-Verlag, 2001. 4. J. Bergeron, Writing Testbenches: Functional VeriJication of HDL Models, Springer-Verlag, 2003. 5. K. Chapman, "Creating Embedded Microcontrollers," TechXcIusivesat http://ww~.~ilinx.~~m. 6. A. Chapweske, "PSI2 MouseIKeyboard Protocol," http://www.computer-engineering.org. 7. A. Chapweske, "PSI2 Keyboard Interface," http://www.computer-engineering.org. 8. A. Chapweske. "PSI2 Mouse Interface," http://www.computer-engineering.org. 9. P. P. Chu, RTL Hardware Design Using VHDL: Codingfor Eflciency, Portability, andScalability, Wiley-IEEE Press, 2006. 10. M. D. Ciletti, Advanced Digital Design with the Verilog HDL, Prentice Hall, 2003. 1I. M. D. Ciletti, Starter's Guide to Verilog 2001, Prentice Hall, 2003. 12. C. E. Cummings, ""full_case parallel-case", the Evil Twins of Verilog Synthesis," SNUG (Syn- opsys Users Group Conference), Boston, 1999. 13. C. E. Cummings, "Nonblocking Assignments in Verilog Synthesis, Coding Styles That Kill!" SNUG (Svnops-vsUsers Group Conference),San Jose, 2000. 14. C. E. Cummings, "Coding and Scripting Techniques for FSM Designs with Synthesis-Optimized, Glitch-Free Outputs," SNUG (Synopsys Users Group Conference), Boston, 2000. 15. C. E. Cummings. "New Verilog-2001 Techniques for Creating Parameterized Models (or Down With 'define and Death of a defparam!)," International HDL Conference, 2002. 16. D. D. Gajski, Principles ofDigita1 Design, Prentice Hall, 1997. FPGA Prototyping by Verilog Examples. By Pong P. Chu Copyright @ 2008 John Wiley & Sons, Inc. 17. J. 0.Hamblen et al., RapidPrototyping ofDigital Svstems: Quartus8 II Edition, Springer, 2005. 18. IEEE, IEEE Standardfor Verilog Hardware Description Language (IEEE Std 1364-2001), In- stitute of Electrical and Electronics Engineers, 2001. 19. IEEE, IEEE Standard VHDL Language Reference Manual (IEEE Std 1076-2001), Institute o f Electrical and Electronics Engineers, 2001. 20. M. Keating and P. Bricaud, Methodology Manualfor System-on-a-Chip Designs, 3rd ed., Springer- Verlag, 2002. 2 1. C. M. Maxfield. The Design Warrior's Guide to FPGAs, Newnes, 2004. 22. Mentor Graphics, ModelSim Tutorial, Mentor Graphics Corporation. 23. S. Palnitkar, Verilog HDL, 2nd ed., Prentice Hall, 2003. 24. D. A. Patterson and J. L. Hennessy, Computer Organization andDesign: TheHardware/Sof~are Interface, 3rd ed., Morgan Kaufmann, 2004. 25. J. M. Rabaey, Digital Integrated Circuits, 2nd ed., Prentice Hall, 2002. 26. S. Sutherland, "What's New in the IEEE 1364 Verilog-2001 Standard," International HDL Con- ference, 2000. 27. J. F. Wakerly. Digital Design: Principles and Practices, Prentice Hall, 2002. 28. W. Wolf, FPGA-Based System Design, Prentice Hall, 2004. 29. Xilinx, DS099 Spartan-3 FPGA Family: Complete Data Sheet, Xilinx, Inc. 30. Xilinx, ISE 8.li Quick Start Tutorial, Xilinx, Inc. 3 1. Xilinx, ISE In-Depth Tutorial, Xilinx, Inc. 32. Xilinx, PicoBlaze 8-Bit Embedded Microcontroller User Guide, Xilinx, Inc. 33. Xilinx, Spartan-3 Starter Kit Board User Guide, Xilinx, Inc. 34. Xilinx, XAPP462 Using Digital Clock Managers (DCMs) in Spartan-3 FPGAs, Xilinx, Inc. 35. Xilinx, XAPP463 Using Block RAM in Spartan-3 Generation FPGAs, Xilinx, Inc. 36. Xilinx, XAPP464 Using Look-Up Tables as Distributed RAM in Spartan-3 GeneratioriFPGAs, Xilinx, Inc. 37. Xilinx. XST User Guide v8.li, Xilinx, Inc. INDEX always block, 48, 194 ASCII code, 230,246 ASM chart, 120 ASMD chart, 140 assignment blocking, 49, 175 continuous, 7 nonblocking, 49, 176 barrel shifter, 73 BCD, 160 binary decoder, 53-54 bit-length adjustment, 45 CLB, 17 comments, 3 connection by name, 10 connection by ordered list, 10 constant, 64 constraint file, 26 Core Generator, 299 counter, 93, 107 D FF, 83 data type, 4 net group, 4 reg, 5 4 9 signed, 190 variable, 49 variable group, 5 wire, 4 x value, 47 z value, 46 DCM, 293 DDR register, 294 debouncing circuit, 130, 144 delay control, 196 development flow, 19 division circuit, 157 edge detector, 125 event control, 197 FIFO buffer, 110,223 flag FF, 221 floating-point adder, 75 FSM, 86, 119 FSMD, 86, 139,372 function, 191 system, 198 user defined, 202 hold time, 84 HyperTerminal, 229,246, 260 identifier, 3 initial block, 194 instantiation, 9 instruction memory, 372 instruction ROM, 376,4 1 1 instruction set, 377 interrupt, 389,453 IOB, 293 KCPSM3,376,380,390,393,407 localparam, 64 logic cell, 15 logic synthesis, 20 LUT, 16,297 macro cells, 17 maximal operating frequency, 85 Mealy output. 120 memory controller, 269, 274,298 Moore output, 120 multiplexer, 59 number, 5 sized, 5 unsized, 5 operator, 39 arithmetic, 41 bitwise, 42 concatenation, 43 conditional. 44 logical, 43 precedence, 44 reduction, 42 relational, 42 shift, 41 pad delay, 288 parameter, 65 PBlazeIDE. 380,390,407 placement and routing, 20 port declaration, 6 primitive, 10 priority encoder, 52, 54 priority routing network. 57 procedural statement, 194 case. 54 full, 56 parallel, 57 casex, 56 casez, 56 for, 194 forever, 195 if, 51 repeat, 195 wait, 197 while. 195 program counter, 372 PS2 keyboard, 240 mouse, 252 receiver, 236 transmitter, 253 RAM block, 298, 332, 342 distributed, 297 dual-port, 303, 332, 348 single-port, 300 static, 269-270 register, 84, 89 register file, 90, 1 l I, 276 register transfer operation, 139 regular sequential circuit, 86 ROM, 305,325 font, 342 RS-232,215 sensitivity list, 48 setup time, 84 shift register, 91 sign-magnitude adder, 7 1 signal declaration, 7 slice, 17 state diagram, 120 static timing analysis, 20 synchronous design methodology, 83 technology mapping, 20 testbench, 12, 32, 96,204 tri-state buffer, 46, 274 UART, 2 15,434 ucf file, 26 user defined primitive, I I VGA mode, 3 12 video memory, 332 video synchronization, 3 12

Top_arrow
回到顶部
EEWORLD下载中心所有资源均来自网友分享,如有侵权,请发送举报邮件到客服邮箱bbs_service@eeworld.com.cn 或通过站内短信息或QQ:273568022联系管理员 高进,我们会尽快处理。