43
ENGN 3213 REVERSE POLISH CALCULATOR PROJECT REPORT NAN ZHU [U4342034] VASANTA GAYATRI CHAGANTI [U4238388]

Final Project Doc

Embed Size (px)

Citation preview

Page 1: Final Project Doc

ENGN 3213

REVERSE POLISH CALCULATOR PROJECT REPORT

NAN ZHU [U4342034]

VASANTA GAYATRI CHAGANTI [U4238388]

Page 2: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

AbstractThe project involves the simulation, building and testing of a Reverse Polish Calculator implementing a four –level register stack with four basic arithmetic operations. The Reverse Polish Calculator is built using a modular approach and the project separately builds the Keyboard interface, the RP Engine and the Display Unit. The project has three levels of implementation, the first level of integer addition and subtraction was coded and tested using Xilinx ISE Webpack 9.2i, successfully and the Keyboard Interface and Display Drive are successfully implemented on hardware. Level 2 of the project is designed to integrate multiplication and division into the earlier modules, with input to the calculator consisting of fixed point numbers. The multiplication and division have been tested on the Simulation Test benches developed and executed successfully.

Page 2 of 33

Page 3: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

TABLE OF CONTENTS1 INTRODUCTION........................................................................................................................................... 6

1.1 REVERSE POLISH NOTATION................................................................................................................................6

2 PROJECT DESIGN......................................................................................................................................... 7

2.1 DESIGN APPROACH...........................................................................................................................................72.2 EQUIPMENT UTILISED........................................................................................................................................82.3 VERILOG CODING STYLE.....................................................................................................................................82.4 DESIGN TRADE-OFFS.........................................................................................................................................92.5 TEAM WORK DISTRIBUTION................................................................................................................................9

3 KEYBOARD INTERFACE.............................................................................................................................. 10

3.1 THE KEYBOARD’S CONNECTOR..........................................................................................................................103.2 RECEIVING DATA............................................................................................................................................103.3 THE KEYBOARD SCAN-CODES.............................................................................................................................113.4 KEYBOARD IMPLEMENTATION............................................................................................................................12

3.4.1 Finite State Machine of the keyboard.................................................................................................123.5 SWITCH DE-BOUNCING....................................................................................................................................13

4. CONTROLLER............................................................................................................................................ 14

5 ARITHEMATIC & LOGIC UNIT (ALU)............................................................................................................ 16

5.1 ALU INPUT....................................................................................................................................................165.2 ADDITION......................................................................................................................................................165.2 SUBTRACTION................................................................................................................................................185.3 OPERATION CHOICE AND SIGN DECISION.............................................................................................................185.4 MULTIPLICATION............................................................................................................................................19

7. STACK & KEY HOLDING REGISTER IMPLEMENTATION................................................................................21

8. DISPLAY................................................................................................................................................... 22

8.1 DISPLAY DRIVER.............................................................................................................................................22

9 SIMULATION RESULTS............................................................................................................................... 24

9.1 SIMULATION TEST BENCH: KEYBOARD.............................................................................................................249.2 SIMULATION TEST BENCH: FSM CONTROL.......................................................................................................259.3 SIMULATION TEST BENCH: ALU........................................................................................................................25

9.3.1 Simulation of addition........................................................................................................................259.3.2 Simulation of subtraction...................................................................................................................269.3.3 Simulation of multiplication................................................................................................................26

9.4 SIMULATION TEST BENCH: KEY HOLDING REGISTER.........................................................................................279.6 SIMULATION TEST BENCH: DISPLAY DRIVER.....................................................................................................27

10. PEGASUS BOARD IMPLEMENTATION...................................................................................................... 28

10.1 FPGA RESOURCE CONSUMPTION....................................................................................................................2810.1.1 Level1...............................................................................................................................................2810.1.2 Level 2..............................................................................................................................................28

10.2 WARNINGS..................................................................................................................................................29

10.3 FPGA SPEED...............................................................................................................................................30

11. CONCLUSION.......................................................................................................................................... 30

REFERENCES................................................................................................................................................. 31

APPENDIX.............................................................................................................................................................32

Page 3 of 33

Page 4: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

1 INTRODUCTION

The aim of this design is to build a reverse polish calculator with four significant decimal digits. Utilising a top down design approach the project is segregated into four main blocks to implement the Finite State Machine, Keyboard, ALU, and the State Registers. Each individual module is then developed with its set of parameters and user defined constraints.

1.1 Reverse Polish NotationReverse Polish Notation was first developed by Jan Lukasiewicz in 1920, when he introduced the concept of prefix notation that made arithmetic operations faster, simpler and significantly easier to adapt to. Reverse Polish Notation is implemented using a simple First-In-First-Out (FIFO) stack. This method was utilised by HP in 1972, to build the first hand held calculator with RPN Notation.

A simple example below demonstrates the working of an RPN Calculator, for the given

algebraic expression: The reverse polish expression is: MI: 2 ENTER 5 ENTER 4

+ *ENTER 3 ENTER 2 ENTER 1 + * /. RPN notation has a number of advantages over the conventional algebraic notation. With each operator entered, the user can check intermediary results and verify the sum of all the actions before calculating the final answer. This method also allows the user to define the priority of the operators, without the need to remember ‘BODMAS’ rules.

A Reverse Polish calculator built on this notation is best implemented using a stack. Each number entered is stored onto a stack, while an operator pops the stack and evaluates the expression. To achieve this, a multilevel stack and a Key Holding Register are used to design the calculator. A four level stack is used as a project guideline with which the above expression is evaluated as follows:

Even within RPN, there exist different ways to express the same equation.

Considering M1 and M2 presented below:MI: 2 ENTER 5 ENTER 4 + * 3 ENTER 2 ENTER 1 + * /M2: 2 ENTER 5 * 4 + 3 ENTER 2 * 1 +/

The result is the same for both operations but M2 saves ENTER Key strokes. If this were to be implemented using a four level Stack, ENTER PUSHES the operand onto the stack and an operator POPS the operand. If MI is used and the ENTER key is pressed too many times without an operation in between the operands, then a four level stack would overflow. M2 never allows the counter to progress to the fourth register (for this example) showing a more

Page 4 of 33

Entry KHRStack

Level 4Stack

Level 3Stack

Level 2Stack

Level 12 2 XX XX XX XX

ENTER 2 02 XX XX XX5 5 02 XX XX XX

ENTER 5 05 02 XX XX4 4 05 02 XX XX+ 9 02 XX XX XX* 18 XX XX XX XX

ENTER 18 18 XX XX XX3 3 18 XX XX XX

ENTER 3 03 18 XX XX2 2 03 18 XX XX

ENTER 2 02 03 18 XX1 1 02 03 18 XX+ 3 03 18 XX XX* 9 18 XX XX XX/ 0.5 XX XX XX XX

Page 5: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

efficient space utilization. This method is preferred implementation of the calculator design detailed in the following pages.

Page 5 of 33

Page 6: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

2 PROJECT DESIGN

The goal of this project is to build a four function calculator with a four level memory register. The calculator is designed based on the reverse polish notation, and performs signed decimal arithmetic.

Valid inputs to the calculator are numbers, operators and basic functions. Number inputs are limited to four decimals with leading or trailing zeros. Operations include addition, subtraction, multiplication and division. The calculator’s functions are responsible for clearing its memory contents and correcting its most recent entry. The calculator interprets the each entry as either an operator or with the press of the ENTER key as a value to be held in the 4-level stack register.

Illegal operations and operators including characters, leading zeros and other anomalies are considered as erroneous entries and discarded. As a result of the operations performed, if the answer is smaller than the display segment (too many leading zeros) or if the answer is bigger than the display segment the result is considered either as an underflow or an overflow condition, and the display defaults to an out of range value. For this project these conditions are detected, and displayed on the Display Driver as [-].

2.1 Design ApproachA finite state machine is used to model this system. Initially various approaches were considered, and the team came up with the following system design for the project. The top-down approach was taken to model the different sub-systems. The main subsystems of this project are detailed below.

The first RTL below is a description of the top level module, and shows the Serial Receiver reading in the ps2_data, which is sent to the decoder module to verify the scan codes generated. This is then sent to the RP Engine, the output of which is sent to the four seven segment display driver and the output of each display is refreshed at a rate set by the MUX.

The second RTL diagram describes the Reverse Polish Calculator Engine showing the ALU, the Key Holding Register; FSM which gives the parameters of (is operation).

Page 6 of 33

Page 7: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

Following the top level design, each sub-system was considered in detail to evaluate its requirements and constraints applying a bottom –up approach at each subsequent level of design to meet the projects top level requirements. Each module is then analysed through a dedicated test bench, and the problems confronted at each level are discussed along with the solution that the team came up with.

2.2 Equipment UtilisedXilinx ISE Webpack 9.2i installed on the Lab computers was used to design and simulate the modules to generate a working code. This code was transferred over to the Xilinx Spartan 2 XC2S50 – PQ 208 Pegasus Board from Digilent Technologies, Inc using a JTAG connection between the console and the board. The code was also tested on the Xilinx Spartan 3E -100 TQ 144, Basys Board. Input is transmitted to the board using an AT-Keyboard with a PS/2 connector.

2.3 Verilog Coding Style

Page 7 of 33

Page 8: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

Verilog coding followed in this project is aligned to that laid out in the course textbook, Wakerly and to that of the Lecture Slides. The code is broken down into modules as described above, and each module updates at the active or falling edge of the clock, depending on whether data is being written to the board or read from it. All the modules are synchronous modules and are divided into atleast two blocks, following FSM coding style. The first block is a sequential block that updates state values and the outputs, and the second block is a combinational logic block, that performs actions whenever the state variable is updated.

This coding aids in removing unnecessary glitches in the code and allows each module to be debugged independently without worrying about asynchronous updates from any of the previous blocks.

2.4 Design Trade-OffsSpeed, accuracy, memory constraints of the system had to be considered when designing the RP Calculator. The memory was the most design parameter, with a 50K-gate the Pegasus Board has limited amount of space available for design. Complying with synchronized coding styles for the report all outputs from the modules are updated at the active edge of the clock. This style of coding is limits the speed at which the output is generated, as the output value of each of the top level modules need to wait for the inputs to get updated at the active clock edge. Accuracy level of the results produced by the calculator is already set by the report guidelines to four significant digits. Hence the programmed code needs to be efficient in space utilisation, with each module updating at the rising or falling clock edge. The final output design traded speed for clearer coding practices.

2.5 Team Work DistributionThe work of the team was distributed evenly between the two project partners. The project could not start out at the date the project guidelines were set up, due to the unfortunate and unforseen quitting of one of the project partners halfway through the course, throwing the entire project onto a single person. The team then formed comprising of Vasanta and Nan and the work flow was re-organised.

Vasanta was in charge of the top-level design of the FSM, display and stack. Nan took over designing the keyboard interface and the addition and subtraction modules. Both the team members designed the Arithmetic and Logic Unit, and designed Level 2 implementation of the calculator. Both the team members contributed to the report.

Page 8 of 33

Page 9: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

3 KEYBOARD INTERFACE

The keyboard used for this project is the IBM PS/2 Keyboard developed in 1987. [1] This keyboard has 101 keys with a 6-pin mini-DIN connector. The keyboard has bi-directional serial protocol including 17 host-to-keyboard commands. The PS/2 interface is a bit serial interface with two signals Data and Clock. Both signals are bi-directional and logic 1 is electrically represented by 5 V and logic 0 is represented by 0 V (digital ground). Whenever the Data and Clock lines are not used, i.e. when they are idle, these lines are left floating, and both the host and device outputs are set to a high impedance value. On the PCB, this is achieved with resistors exceeding 5kΩ, used to pull the output high (HI).

The FPGA Pegasus/keyboard interface is shown in the figure below. When the FPGA reads in Data or Clock inputs both PS2Data_out and PS2Clk_out are kept low which puts the tri-state buffers in high impedance mode. When the FPGA sends data out, the PS2Data and PS2Clk are set to logic high.

Figure 3: FPGA/Keyboard Interface

3.1 The Keyboard’s ConnectorThe PC's AT Keyboard is connected to all external equipment using four wires. These wires are shown below for the 5 Pin DIN Male Plug & PS/2 Plug. For this project, the PS/2 pin connector is used, which allows bidirectional communication between the host (Pegasus Board) and the Keyboard Input.

Page 9 of 33

Page 10: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

Both the KBD Clock and KBD Data are Open Collector bi-directional I/O Lines. While most of the data communication is directed from the keyboard to the output, if desired, the Host can talk to the keyboard using these lines.

3.2 Receiving Data Data is received from the keyboard as illustrated in Figure below. A transfer may be initiated by the keyboard if the Clock line is high. The host (Pegasus Board in this case) may force the Clock low in order to prevent the keyboard from sending data – the host may inhibit communication. The PS2 clock used for communicating with the host is generated by the keyboard. Data is valid at least 5 us (t in figure) before the falling edge of the clock. The clock period is (T in figure) is 60 to 100 us.

Data from the keyboard comprises of 11bits for each packet. This is sent from the keyboard serially bit by bit. The first bit is always a start bit, logic 0. The following 8 bits represent the scan code of the corresponding key.

Figure: PS/2 timing

Figure: PS/2 Protocol

The scan code is always sent with the least significant bit first. The data is padded with an odd parity bit used for error detection. If the number of logic 1’s in the scan code and the odd parity add up to an odd number, then the scan code is considered to be sent without errors. When the 8 bits of the scan code and the odd parity bit are sent, the data line is pulled with a stop bit of logic 1 signaling the end of the data stream.

3.3 The Keyboard scan-codes

Page 10 of 33

Page 11: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

The keyboard sends scan codes to the host indicating which key has been pressed. When a key is pressed or held down, one byte code-word is transmitted. When the key is released a break code is transmitted. Every key is assigned a unique code followed by a break code, indicating to the host the duration and number of each key press. The scan codes conveys to the Keyboard Bios, which keys have been pressed or released. Take for example the '1' Key on the number pad. The ‘1' key sends a scan code of 69 (hex) down the serial line. If the key is held for longer than a set delay known as the Typematic delay, the scan code is resent. Once the key is released, the keyboard sends another scan code (F0) to indicate the end of that key. Thus for each key pressed, the keyboard sends in hexadecimal, the scan code, the break code followed by the scan code again.A handful of extended keys are represented with two hexadecimal scan codes, and are identified by the starting ‘E’ of their hexadecimal value. These keys will not be used in this project.

The project requires the numeric keys and the corresponding basic operations set. These are assigned as shown in the table below. Aside from this set, the enter key and two additional keys are chosen for their scan code values and are assigned to clear the stack (CLR) and clear the Key Holding Register (CLX).

KEY OPERATION SCAN CODE (HEX)0 0 701 1 692 2 723 3 7A4 4 6B5 5 736 6 747 7 6C8 8 759 9 7D. DECIMAL POINT 71+ ADD 79- SUBTRACT 7B* MULTIPLY 7C\ DIVIDE 5D

Backspace CLEAR 66ESC CLX 76

3.4 Keyboard ImplementationThe keyboard interface was designed using the code designed in the hardware labs. The following shows the block diagram of the keyboard. The keyboard is given the input of the 3.4.1 Finite State Machine of the keyboard

When keyboard sends signals to the receivers, there are 11 bits of binary numbers that contained in each period. The first bit is the “start-checking bit”. If it is “0”, the other bits

Page 11 of 33

Page 12: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

that after the start-checking bit will be continuously sent. The next 8 bits are the “scan code” of any signal button on the ps/2 keyboard. A 1 bit parity checking code will follow the scan code to send. The last bit is an “ending code”, whose value is usually 0, standing for “one sending signal period is end”. As the cycle next-state diagram shows, once the starting bit is confirmed, the rest 10 bits binary numbers will be sent incessantly, until another start-checking bit with a value of “1” is reached.

Scan codes transitions from one scancode to the next at a rate synchronised to the ps2_clk which is usually set to 10 KHz. This clock output can be skewed by the FPGA clock that runs at a speed 10 times that of the PS2 Keyboard Clock. To limit the slew of the PS2 clock, a synchronised clock is used to transition between the high and low values of the PS2 clock at the active edge of the FPGA clock.

3.5 Switch De-bouncingBouncing is a phenomenon that occurs when the the physical press of the key against its mechanical spring results in the key ‘bouncing’ for a certain period before it settles. This is usually a very negligible amount on present day keyboards, however on the old AT keyboards this value can be more pronounced. Bounce in the switch can cause the data to distort or be incorrectly read. This can occur if the key’s mechanical spring is loose enough to cause it for every press, or if the key is pressed repeatedly at a rate faster than the settling time of the key.

The scan codes one byte of data, is composed of random number of ones and zeros. The amount of time taken for the scan code to register all the bits sent in by the ps2_data serial line is limited only by the synchronised clock. When the scan code transitions to a new scan code, a sharp one can be neglected and the output would result in a very different scan

Page 12 of 33

Page 13: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

code. This transition period is of the order of a few nano – micro seconds and is too small to to offset the input. [4]

During testing, the keys produced correct output when the keys were pressed at the rate of 4 keypresses-per-seconds. Bouncing can be tackled both in hardware and software. Correcting the error is simpler using software. As such the simplest way to deal with bouncing would be to write a delay code before which the key is processed, ignoring values during which the key settles. Since Verilog is a HDL language, a hardware circuit could also be described like the SR-Latch presented in [4] to deal with bouncing switches. Another de-bounce logic involves, applying an exclusive OR to all the bits of the one byte scancode. Transitions from zero to one are then only recorded when the switch is properly de-bounced.

Since this was not an issue on our board, we decided not to implement a de-bouncing code to accommodate the memory constraints imposed by the Pegasus Board.

4. CONTROLLER

The representation of the input decides the coding style and the approach used to build the not only the ALU, but also the decoding involved when interfacing with the display driver.

The keyboard output is a five bit digit that stores the state of the scanned key. Valid inputs include numbers, operators and the CLX, CLEAR and ENTER keys. This output is decoded by the controller and valid input codes are sent from the Key Holding Register and the Stack.

The five bit hexadecimal code for each valid input is that comes from the scancode and decoder module is shifted into a 16 bit register number by number. The stack value of this implementation would result in:2: 00101: 0001 00103: 0011 0001 00107: 0111 0011 0001 0010

While this representation in binary would translate to 29458, this value in Binary Coded Decimal translates to 7312. Representing the input as a BCD code word simplifies the operations performed within the ALU and the shortens the case statements necessary to drive the display.

Using this representation of numbers, each number need only be represented by four bits including all the digits from 09 {0000 1001} and the values from 1010 through to 1111 are unused. While this technique does result in a certain amount of memory wastage, the resulting code is simpler and much more efficient. Take converting 12710 into binary and BCD as a simple example. In binary, this number evaluates to: 12710 = 26 + 25 + 24 + 23 + 22 + 21 + 20 = 11111112. While In BCD each digit has four bits of encoding and translates to: 110 = 00012, 210 = 00102 and 710 = 01112 0001 0010 0111BCD.In the controller, the only state that can start to read code is the “Idle” state; therefore, every time when the input data is fully read into controller, the next state should always become idle in order to keep getting new inputs. The next state table is shown below:

Page 13 of 33

Page 14: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

BCD Current State next state pushPopS isOp K_stack5'h00 Idle NUM 2'b00 2'bxx 2'b105'h01 Idle NUM 2'b00 2'bxx 2'b105'h02 Idle NUM 2'b00 2'bxx 2'b105'h03 Idle NUM 2'b00 2'bxx 2'b105'h04 Idle NUM 2'b00 2'bxx 2'b105'h05 Idle NUM 2'b00 2'bxx 2'b105'h06 Idle NUM 2'b00 2'bxx 2'b105'h07 Idle NUM 2'b00 2'bxx 2'b105'h08 Idle NUM 2'b00 2'bxx 2'b105'h09 Idle NUM 2'b00 2'bxx 2'b105'h0A Idle ENTER 2'b01 2'bxx 2'b015'h1A Idle CAL 2'b00 2'bxx 2'b005'h0B Idle CLX 2'b00 2'bxx 2'b005'h1B Idle CLR 2'b11 2'bxx 2'b005'h0C Idle CAL 2'b10 2'b00 2'b115'h1C Idle CAL 2'b10 2'b01 2'b11

Current State Next StateInput

Number Operator ENTER CLX CLR CHSIdle NUM CAL ENTER CLX CLR CHS

NUM Idle Idle Idle Idle Idle IdleCAL Idle Idle Idle Idle Idle Idle

ENTER Idle Idle Idle Idle Idle IdleCLX Idle Idle Idle Idle Idle IdleCLR Idle Idle Idle Idle Idle Idle

Page 14 of 33

Page 15: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

5 ARITHEMATIC & LOGIC UNIT (ALU)

The Arithmetic and Logic Unit (ALU) is the central part of the project and all the arithmetic and logical operations are performed in here. The ALU is implemented as a combinational circuit that performs micro-operations on the BCD operands from the Stack and KHR. The operations performed by the ALU are determined by the controller, and the Change Sign Logic Control implemented within the ALU.

5.1 ALU InputThe ALU input comes in from the Stack Module which stores the four levels of stacks, and the Key Holding register. This input is sent to the ALU, which then performs calculations on each digit of the BCD code word. When performing calculations it is possible for the resulting number to have a value larger than 9, say 11. This in binary is represented as 1011, however this is not a valid BCD output. To convert the output into a valid BCD code-word, a ‘carry-out’ is performed, wherein 10 is subtracted from the digit at hand, and a carry value of one is then parsed to the next digit in the code word. This process is described in the table below.

SUM S {4’b BCD1 , BCD2} Carry Correction0 ≤ S ≤ 9 N N10 ≤ S ≤ 15 Y (implement Correction) Y, add 616 ≤ S ≤ 18 Y(implement Correction again) Y, add 6

5.2 Addition Addition in the ALU was initially performed in the control module using binary input. Each updated binary value added onto its previous value. This approach suffered severe drawbacks as it could not cope with overflow, in that it was not distinguishable from two’s compliment. Since binary addition did not seem very feasible, the team switched over to Binary Coded Decimal [BCD] addition.

To implement this, the team developed a full adder module from two half adder blocks and passed four bit BCD value to the full adder. The full adder calculation returned at most a 5 bit output. This output was very often out of range, and the adder module was then redefined, to accommodate four temporary variables that added each digit in parallel. Each digit was then adjusted, and the carry over from each digit added on to the subsequent BCD value.The four bit full adder is then designed along the following schematic.

In the schematic, a half adder takes in two BCD values and produces the sum of these values along with a Carry-Out Value. Combining the two half adders to store the carry in and carry out values produce the full adder sum of the inputs A and B.

Page 15 of 33

Figure 1 Half Adder & Full Adder

Page 16: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

Using the full adder, addition of two four bit BCD numbers, results in a five bit BCD output. Thus similar signed inputs would result in an overflow condition. The overflow (fifth) bit is discarded if the number exceeds four significant decimal places.

Once implemented, the full adder code, took the same time to implement as the inbuilt addition (+) and subtraction (-) operators for bit vectors in Verilog. The full adder code needs to be instantiated every time the adder is called for the 4 BCD values, in addition to being called to add the carry-in values. In contrast, the in-built Verilog (+) and (-) operators are synthesized by the compiler to just one adder and and it then uses a multiplexer to selects its inputs.

Addition is performed by aligning inputs along the decimal point, and adding each column of input. When BCD addition is performed this way, the resultant value of two four bit binary numbers can result in a value greater than {1001} BCD representation of decimal number 9. When this occurs, the binary number is no longer a valid BCD code. To display the correct output a simple correction algorithm detailed in the following table is implemented.

Operation Term 1 [BCD] Term 2 [BCD] ResultBinary Input 0000 0000 10110

If input ≥ 10, subtract 10, and store it in

term 2 and incr. term 1 by one.

0001 1100

Term 2 is still ≥ 10, subtract 10, and

store it in term 2 and incr. term 1 by one.

0010 0010

Term 2 is 10, & Term 1 is 10. The

BCD output is generated.

0010 0010 0010 0010

Decimal Code Word 2 2 22

As an example, the addition between 10012 and 10002 can lead to an overflow case and give the wrong output value. Again, if we follow the basic binary addition algorithm, the answer will be 100012. The value of 100012 is 17, which is the correct answer to the addition 9 + 8, and is segregated according to the table presented above.

However, if the addition of the two numbers has a precision greater than four decimal places, the output is not displayed, and the overflow condition is triggered. Error-handling code within the module displays the overflow as a ‘[-]’.

5.2 Subtraction

Page 16 of 33

Page 17: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

Subtraction leads numbers of transitions between the input digits and their two’s complement in binary and 10’s complement. Again, same as the addition, for convenience, the pre-programmed symbol “−” is used in this project, and BCD is used to represent the input output numbers in the calculator.

The subtraction has the same invalid output error as addition, but the algorithm involved is slightly different from that of the addition. No overflow errors are detected in the subtraction module simply because only the absolute values are sent to the subtraction module. The change sign logic implemented for all four operations are detailed in section 5.5.

To avoid the invalid output error, the following simple steps will be undertaken. Starting from the rightmost 4-bit binary code, each BCD value of the first input is subtracted from its counterpart and stored in four temporary variables. If the result is less than 00002 or greater than or equal to 10012, the first value will have to borrow ‘1’ from the next digit and the add 10102, (10) to the 4 bit binary result in the second digit. This process ripples through to the fourth BCD. If the fourth digit is found lacking in carry-in value, a Change Sign is appended to the resulting output and sent to the Key Holding Register.

This concludes LEVEL 1 implementation for the RPN calculator. The addition and subtraction modules have been rigorously tested using test benches developed in Xilinx and the output thus generated is shown in Section 9. All the output values were accounted for, and both overflow and negative sign conditions tested.

5.3 Operation Choice and Sign DecisionOperation choice, based on the two inputs to the ALU and its Change Sign Value are described. Since the multiplication and division modules sign logic is not that different, their values are also included. Inputs to the ALU upon which the above operations are performed fall into the following categories: Input 1 = Positive; Input 2 = Positive Input 1 = Positive; Input 2 = Negative Input 1 = Negative; Input 2 = Positive Input 1 = Negative; Input 2 = Negative

When calculating, addition of numbers with opposite signs (negative and positive) is treated as a subtraction, while subtraction of like signs is treated as an addition.

In this project, due to the 4 7-segments limitation, the largest acceptable input to the calculator will be four digits, which translates to 16 bits of BCD code. To make the inputs more convenient to use, we add a 17th bit for each of the input to define whether it is a positive number (if the extra bit is 0) or a negative number (if the extra bit is 1).

The output sign of multiplication and division is fairly straightforward. If the two inputs have same sign, the output will be positive, and if the two inputs have opposing signs, the output will be negative. The output sign of addition and subtraction is also obvious, the same as the input which has a greater absolute value.

Page 17 of 33

Page 18: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

In summary, the following table has been derived with all possible cases of operators and operands. The calculation to be performed and its interpretation are also specified.

Input 1 Input 2 Input operator Operation Performed

Output

Positive Positive + + PositivePositive Negative + − Follow the

larger number’sNegative Positive + − Follow the

larger number’sNegative Negative + + NegativePositive Positive − − Follow the

larger number’sPositive Negative − + PositiveNegative Positive − + NegativeNegative Negative − − Follow the

larger number’sPositive Positive * * PositivePositive Negative * * NegativeNegative Positive * * NegativeNegative Negative * * PositivePositive Positive / / PositivePositive Negative / / NegativeNegative Positive / / NegativeNegative Negative / / Positive

5.4 Multiplication Level 2 of the project requires signed multiplication and division to be performed on fixed point decimal numbers. The team developed the logic for multiplication as well as division, however was only able to implement the multiplication module on the FPGA.

The BCD multiplication requires the use of binary multiplication as basic operation. The algorithm of multiplying two binary numbers is shown below:

Figure 1 Binary Multiplication [5]

First the partial product for each digit is worked out. Because each nibble is a binary code word, partial products are calculated for each digit of the two terms in parallel. From the above figure, the pipelined partial products are calculated as {B0A0, AOB1-A1BO, A2B1 - A1B1 ….and so on}. These partial products are combined taking care of the carry-ins involved. The multiplicand of each combinational term of multiplier is checked for its product

Page 18 of 33

Page 19: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

and 6 is recursively added to the result, if the number exceeds the maximum BCD word - 1001.

Figure 2 Multiplication Block Diagram

This is a form of carry and save addition is used to speed up the processing of the multiplication of the ALU. For an n digit multiplication the code requires (2*n-1) BCD multiplications and (n-1) BCD additions. Each of the (2*n -1) multiplications that produce partial terms, recursively add using a full adder described in section 5.1.

For the multiplication coding, four temporary parameters are used to store the multiplications of individual digits. Following this the code dealt with numbers was more complicated than addition. Addition would only occur carry out with value of 1, while in multiplication, the carry out was varying from 1 to 8 (i.e. 9 * 9 = 81, carry out = 8).

There were two methods to find out the carry out. First one was to create a loop. If the temp value was greater than 9, it was then subtracted by 1. By recursively checking the temp value and taking “1” each time from, the carry out value could be found as the times of repeating the procedures.

The output values generated for multiplication are shown in the test bench developed for the ALU, all the output values were accounted for, and the overflow conditions tested.

Page 19 of 33

Page 20: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

Page 20 of 33

Page 21: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

7. STACK & KEY HOLDING REGISTER IMPLEMENTATION

The stack implemented in the project has a depth of four and is used to store all the numbers entered from the keyboard followed by an ENTER key (refer table in INTRO). The stack is implemented as a four stage shift register. The stack can be cleared of all its contents using the CLEAR command.

Each level of the stack can accommodate a four digit BCD value, and hence functions as a 16bit shift register. The stack gets updated either with a ‘push’ or ‘pop’ command. The ‘push’ command, pushes all the values of the stack by one level, while a ‘pop’ raises the the stack and the outermost value of the stack is discarded. A CLEAR command clears the entire stack of its values.

The stack has four modes of operation, selected from a 2-bit input. At each clock cycle the stack will function in one of these modes. The stack is very similar to a bidirectional shift register, and one level stack output is as shown in the figure.

This is executed in the stack module as follows:

The Key Holding Register updates similarly, The stack updates when the variable strobing its output to push or pop is called. A push value, pushes each stack value a level lower and a ‘pop’ command

Page 21 of 33

Page 22: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

8. DISPLAY

The display utilizes the four seven-segment displays on the output, and assigns each value of the 15 bit register to the output. The working of the seven segment display is shown below:

From [3]Since each of the seven-segment displays shares the same cathode values, assigning the cathode values to each of the four seven segment displays, shows the same digit on all four displays. From the figure above obtained from the Pegasus manual, we find that each display is assigned an anode {a1, a2, a3 & a4}. Thus to show different digits on each of these outputs, the anode values are toggled, displaying one digit at a time. If this switching is done at the right speed, it is imperceptible to the human eye, and each digit appears distinct. To accomplish this, a switcher is used to take in the BCD input and pass just one digit and the corresponding anode value, to be displayed.

The anode values toggle at a rate faster than the flicker rate that the human eye can perceive in order for the display to show two different digits simultaneously. This is achieved by using a refresh rate of 50Hz the same frequency that drives the Pegasus FPGA.

8.1 Display DriverThe display driver used to light up the seven segments is shown below:

Page 22 of 33

Page 23: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

The seven segment display driver has a multiplexer that chooses the bits that get updated, and converts the 16 bit register into a four bit BCD value.

The SSD or the Seven Segment Display block then converts the BCD value into its corresponding seven segment value. The Modulo State Machine slows down the Clock timer to 50 Hz, and sends the clock input along with the corresponding BCD digit to be displayed to the 2:4 Decoder. The 2:4 Decoder employs a 2 bit delay value that toggles constantly between four states. Depending on the delay state four bits are assigned to the anode of the display driver.

Page 23 of 33

Page 24: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

9 SIMULATION RESULTS

9.1 Simulation Test Bench: KEYBOARDThe Verilog code for this module was simulated in ISE using a test bench. The Verilog test module simulates an 11 bit code word for each key pressed. Each key press is detected at the falling edge of the clock. Once the key press is detected, the keyboard interface cycles through the states in its finite state machine from {s0 – ss}. The state is synchronously updated also at the falling edge of the clock and each bit of the 8-bit scancode is updated sequentially as shown above.

The simulation test bench was quite tricky to implement as the output from the scancode gets updated at different values, and takes an arbitrary time to do so. Also all the ps2_values had to be synchronised almost exactly to the clock input and were sent in reverse to simulate actual data.

The first arrow in the simulation figure 1 shows the hexadecimal scancode for the number 1- h’69. This scancode value can be seen to be updated at the falling edge of the clock, and the corresponding number value is stored in digit. The following scancode h’F0 is the ‘key released’ scancode, and once this scancode is detected, the value of digit, is updated to ‘out’ which stores the output BCD value.

Page 24 of 33

Page 25: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

9.2 Simulation Test Bench: FSM CONTROL

The next state logic toggles between the states given as input (number, operator, function) and the idle state. Every time the BCD value gets updated, so does the output as shown by the arrows.

The output logic of the pushPop stack and the K_stack values only get updated at the press of the ENTER key denoted by the 5’h0A key press as shown above

9.3 Simulation Test Bench: ALU

9.3.1 Simulation of additionThe figure demonstrates the theoretical results of different combinations of input numbers. For the operator depicted by the first arrow, the input operator was stays at “+” (2’b00) during the simulation. The first calculation was “(−5) + 2”. In our project, when a negative input, a positive input and a “+” operator are detected by ALU, the actual operation performed is subtraction.

Page 25 of 33

Page 26: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

Therefore, the enable_add is set to 0 and the enable_sub set to 1 (shown by the second arrow). The following four calculations are tested “2 + 5 = 7”, which tests positive numbers addition; “1234 + 9876 = 0B110, alu_overflow = 1”, which tests for positive number addition overflows; “(−5) + (−2) = (−7)”, which tests the addition of two negative numbers; and finally the “(−1234) + (−9876) = (−B110), alu_overflow = 1” which tests negative number overflows. All the results were sent to alu_out at the positive edge of the clock.

9.3.2 Simulation of subtractionSubtraction is performed on the following inputs “(−5) − (−2) = −3”, “2 − (−5) = 7”, and “1234 − 9876 = −8642” testing the cases of negative, opposing polarities and positive number subtractions respectively. In this project, if subtraction needs to be performed on two numbers with different polarities the performed operation is an “addition”.

These results are reflected in the test bench shown above. Again, the results are updates at the positive edge of the clock.

9.3.3 Simulation of multiplication

The multiplications between two positive numbers, two negative numbers and two opposite sign numbers are tested as “2 * 3 = 6”, “(−5) *(−15) = 75” and “(−15) * 15 = −225”. Once the multiplication trigged (where the first arrow pointed), the tests were operated continuously. A four digit number multiplication “1234 * 5 = 6170” and an overflow case “1234 * 15 = 8510, alu_out = 1” were then tested to see whether the higher level registers work. Again, the results were sent to alu_out at the positive edge of clock as shown in the figure below.

Page 26 of 33

Page 27: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

9.4 Simulation Test Bench: KEY HOLDING REGISTERThe key holding register updates the value at the change of input, retains the same value when the enter key is pressed, and clears its value when CLX function is used.

9.6 Simulation Test Bench: DISPLAY DRIVERThe display driver has a constant refresh rate, and the simulation results are best shown with a working example of the code. As can be seen from the figure, the digits display distinct numbers and the display driver refreshes at the rate of an assigned ‘slow clock’ value.

Page 27 of 33

Page 28: Final Project Doc

10. PEGASUS BOARD IMPLEMENTATION

10.1 FPGA Resource Consumption10.1.1 Level1The number of slices used to generate level 1 is 49% of the total slices. This resource utilisation of the Slice Flip Flops and bonded IOBs is low compared to that of the Level 2 utilization.

Logic Utilisation Used Available Utilisation

Number of Slices 196 768 49%

Number of Slice Flip Flops 120 1536 8%

Number of 4 Unit Look Up Tables (LUTs) 455 1536 29%

Number of bonded IOBs 10 140 7%

Number of GCLKs 2 4 50%

10.1.2 Level 2The resource utilisation for level 2 is fairly intensive due to the multiplication algorithm. This can be seen in the large number of slices utilised and the number of slice flip flops.

Logic Utilisation Used Available Utilisation

Number of Slices 494 768 64%

Number of Slice Flip Flops 270 1536 17%

Number of 4 Unit Look Up Tables (LUTs) 894 1536 58%

Number of bonded IOBs 16 140 11%

Number of GCLKs 2 4 50%

The following table shows the advanced resource consumption of the module. The module shows an exceptionally high number of latches, however these latches are resolved when the generate programming file is implemented. This could be because the values parsed from the keyboard are not set until the bit file is generated.

Page 29: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

10.2 Warnings

When the Top Level Module is synthesized and Implemented Xilinx generates warnings as cautionary comments on the use of always blocks and sensitivity parameters. The use_dsp48 constraint allows the specification of technology resource for macro implementation.

WARNING:Xst:905 - "../TopLevel.v" line 36: The signals <KHR> are missing in the sensitivity list of always block. Module <Toplevel> is correct for synthesis.

WARNING:Xst:905 - "../serial_rcvrWorking.v" line 148: The signals <ps2_data, next_scancode, scancode, read, digit> are missing in the sensitivity list of always block. Module <serial_rcvr2> is correct for synthesis.

WARNING:Xst:905 - "../decoder1.v" line 40: The signals <rcvr_out> are missing in the sensitivity list of always block. Module <decoder1> is correct for synthesis.

WARNING:Xst:905 - "../fsm3.v" line 81: The signals <pre, BCD> are missing in the sensitivity list of always block. Module <fsm3> is correct for synthesis.

WARNING:Xst:905 - "../mux_dis2.v" line 53: The signals <in1, in2, in3, in4> are missing in the sensitivity list of always block.

Module <mux_Display2> is correct for synthesis.

WARNING:Xst:2734 - Property "use_dsp48" is not applicable for this technology

Page 29 of 33

Page 30: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

10.3 FPGA SpeedThe speed or the maximum frequency of a digital system is largely determined by the system delay. System delay is influenced by several factors other than the circuit logic alone: The propagation delay due to the internal structure of the gates, the loading of the output buffers (assigning net delays) and the circuit logic.

Propagation delay is the time difference between the issue of an input and the reflection of that input value in an output signal. These delays are a product of the physical gates in the system and the time it takes for them to respond to an output. These delays can be caused due to parasitic capacitances inside the gates, speed of light limitations of the circuit, and net delays (caused by wiring between the gates on the board).

The delay of the circuit can be measured using the Post Place and Route Simulation. This simulation helps determine the delay of the internal nodes of the circuit and a Critical Path can be determined from the timing diagram to show the path that limits the circuit speed.

11. CONCLUSION

The reverse polish calculator was developed and implemented as shown in the report. The report showed the fsm coding style taught in the course and emphasized on the need for efficient design. With more time, more operators can be implemented and a floating point digit added.

Page 30 of 33

Page 31: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

REFERENCES

1. http://www.computer-engineering.org/ps2keyboard/ 2. Digilent Basys Board Reference Manual. Xilinx Spartan 3E -100 TQ 144.3. Digilent Pegasus Board Reference Manual. Xilinx Spartan 2 XC2S50 – PQ 2084. http://research.microsoft.com/enus/um/people/gbell/

designing_computers_and_digital _systems/00000194.htm 5. http://www.willamette.edu/~fruehr/cs130/lab2.html 6. http://www.vocw.edu.vn/content/m10781/latest/ 7. http://www.eportfolio.lagcc.cuny.edu/scholars/doc_sp07/eP_sp07/suong.nguyen/

CIS295.html8. Digital Design, Principles and Practices. Fourth Edition. John F Wakerly

Page 31 of 33

Page 32: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

APPENDIX

Flow Chart describing the working of a reverse polish notation:

Page 32 of 33

Pop Stack, Operate on the

number and KHR, store in KHR

Store in Stack

Store in KHR

POP

Start

Read Input Data

ENTER

KEY

OPERATOR

NUMERIC DATA

YES

YES

YES

Page 33: Final Project Doc

Zhu, Chaganti ENGN 3213: Reverse Polish Calculator Project Report

Flow Chart describing the working of the Keyboard:

Page 33 of 33