0
0
VhdlHow-ToBeginner · 3 min read

VHDL Code for Half Adder: Syntax and Example

A half adder in VHDL adds two single-bit inputs and produces a sum and carry output. Use xor for sum and and for carry in the architecture block.
📐

Syntax

The half adder uses two inputs and two outputs. The entity defines the interface with inputs A and B, and outputs Sum and Carry. The architecture block describes the logic: Sum is the XOR of inputs, and Carry is the AND of inputs.

vhdl
entity HalfAdder is
    Port (
        A : in std_logic;
        B : in std_logic;
        Sum : out std_logic;
        Carry : out std_logic
    );
end HalfAdder;

architecture Behavioral of HalfAdder is
begin
    Sum <= A xor B;
    Carry <= A and B;
end Behavioral;
💻

Example

This example shows a complete half adder design in VHDL. It adds two bits and outputs the sum and carry. You can simulate this to see how inputs affect outputs.

vhdl
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity HalfAdder is
    Port (
        A : in std_logic;
        B : in std_logic;
        Sum : out std_logic;
        Carry : out std_logic
    );
end HalfAdder;

architecture Behavioral of HalfAdder is
begin
    Sum <= A xor B;
    Carry <= A and B;
end Behavioral;
Output
When A=0, B=0: Sum=0, Carry=0 When A=0, B=1: Sum=1, Carry=0 When A=1, B=0: Sum=1, Carry=0 When A=1, B=1: Sum=0, Carry=1
⚠️

Common Pitfalls

Common mistakes include mixing up and and xor operators, or forgetting to declare ports correctly. Also, ensure you use std_logic type for signals, not bit, for better compatibility.

Another error is missing the library IEEE; and use IEEE.STD_LOGIC_1164.ALL; lines, which are needed for std_logic types.

vhdl
Wrong:
Sum <= A and B;  -- This is carry logic, not sum

Right:
Sum <= A xor B;  -- Correct sum logic
📊

Quick Reference

TermDescription
entityDefines inputs and outputs of the half adder
architectureDescribes the logic behavior
xorUsed for sum output (A xor B)
andUsed for carry output (A and B)
std_logicSignal type for inputs and outputs

Key Takeaways

Use XOR for sum and AND for carry in half adder logic.
Declare inputs and outputs clearly in the entity block.
Include IEEE library for std_logic signal types.
Avoid mixing logic operators to prevent incorrect outputs.
Simulate your design to verify correct sum and carry outputs.