Search code examples
vhdlswap

VHDL swap two values


I want to swap the value of input0 and input1, and output the smaller one. When I simulate my project in Modelsim, the waveform of signal output is red line. What is my mistake?

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity MF is
    port (clk : in std_logic;
          input0: in std_logic_vector(2 downto 0);
          input1: in std_logic_vector(2 downto 0));
end MF;

architecture Behavioral of MF is
    signal bubble0: std_logic_vector(2 downto 0);
    signal bubble1: std_logic_vector(2 downto 0);                               

begin
    bubble0 <= input0;               
    bubble1 <= input1;
    output <= bubble0;                        -- my output
    process(clk)
    begin
        if rising_edge(clk) then
             if bubble0 > bubble1 then        -- swap
             bubble1 <= bubble0;
             bubble0 <= bubble1;
             end if;                                        
        end if;
    end process;
end Behavioral;

Solution

  • I see several issues:

    1) You are assigning values to bubble0 and bubble1 both asynchronously and inside a process (this is a "bus fight" with more than one driver on each signal, which IS legal in VHDL, but you have to be aware of what you're doing...typically this is used to make tri-state buses, but both of your assignments are driving the signal constantly which likely results in the 'undefined' state when resolving the signal).

    2) You are not assigning values to bubble0 and bubble1 in all cases of your if statement inside the process.

    3) You cannot directly compare two std_logic_vector values for numeric magnitude, you first need to cast them to an appropriate numeric type (such as signed or unsigned).

    It is unclear exactly how you want your output to behave, but perhaps something like the following will get you farther along...this updates the bubble signals as appropriate at each rising edge of the clock:

    begin
        output <= bubble0;                        -- my output
        process(clk)
        begin
            if rising_edge(clk) then
                 if unsigned(input0) > unsigned(input1) then        -- swap
                     bubble1 <= input0;
                     bubble0 <= input1;
                 else
                     bubble0 <= input0;               
                     bubble1 <= input1;
                 end if;                                        
            end if;
        end process;
    end Behavioral;