Professional Documents
Culture Documents
Now that we have a firm handle on Boolean operators and signal buses, we are in
a position to implement one of computing s
basic functions-- adding two numbers together.
9.1 Binary addition using Boolean operators
You don t have to, but as a learning exercise it is worthwhile to implement binary
addition using simple operators.
To do so we have to make use of our first equivalent of a local variable-- a sig
nal that is used only within the Switches_LEDs
entity.
We will need four of these local signals. To declare them, the definition of the
signal is added between the "architecture" and
"begin" lines:
...
architecture Behavioral of Switches_LEDs is
signal x : STD_LOGIC_VECTOR(3 downto 0);
signal y : STD_LOGIC_VECTOR(3 downto 0);
signal carry : STD_LOGIC_VECTOR(3 downto 0);
signal result : STD_LOGIC_VECTOR(4 downto 0);
begin
...
The size of result may look a little odd, but we are going to add two four-bit num
bers on the switches, which gives a five-bit
result (as 15+15 = 30). Let s wire the LEDs up to the "result" signal, and set the
unused LEDs to 0.
LEDs <= "000" & result;
We will also assign the values of X and Y to be the first and second group of fo
ur switches.
x <= switches(3 downto 0);
y <= switches(7 downto 4);
Here is the code for adding the first bit:
result(0) <= x(0) XOR y(0);
carry(0) <= x(0) AND y(0);
Not too hard. This is a half adder-- it s called this as it does not have a carry
in only a carry out.
Now here s the second bit, which is a full adder-- it is a lot more complex as it
has to deal with an x bit, a y bit and the carry bit
from adding bit zero:
Introducing the Spartan 3E FPGA and
VHDL
32 / 122
result(1) <= x(1) XOR y(1) XOR carry(0);
carry(1) <= (x(1) AND y(1)) OR (carry(0) AND X(1)) OR (carry(0) AND Y(1));
It is a lot easier to understand the carry expression if you think of it as "are
any two bits set?".
So here s the code up till now:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity Switches_LEDs is
Port ( switches : in STD_LOGIC_VECTOR(7 downto 0);
LEDs : out STD_LOGIC_VECTOR(7 downto 0)
);
end Switches_LEDs;
architecture Behavioral of Switches_LEDs is
signal x : STD_LOGIC_VECTOR(3 downto 0);
signal y : STD_LOGIC_VECTOR(3 downto 0);
signal carry : STD_LOGIC_VECTOR(3 downto 0);
signal result : STD_LOGIC_VECTOR(4 downto 0);
begin
LEDs <= "000" & result;