Создание 16-битного АЛУ из 16 1-битных АЛУ (структурный код)

Я создал структурный и поведенческий код для 1-битного АЛУ, а также схему управления. Схема управления определяет операцию, которая будет выполняться между двумя переменными: a, b.

Вот моя поведенческая часть кода:

 library ieee;
use ieee.std_logic_1164.all;
package erotima2 is

-- AND2 declaration
 component myAND2
        port (outnotA,outnotB: in std_logic; outAND: out std_logic);
 end component;


-- OR2 declaration
  component myOR2          
       port (outnotA,outnotB: in std_logic; outOR: out std_logic);
 end component;

-- XOR2 declaration
  component myXOR2          
       port (outnotA,outnotB: in std_logic; outXOR: out std_logic);
 end component;

--fulladder declaration
  component fulladder     
            port(CarryIn,outnotA,outnotB: in std_logic; sum,CarryOut: out std_logic);
  end component;

--Ainvert declaration
  component notA        
            port(a: in std_logic; signala: std_logic_vector(0 downto 0); outnotA: out std_logic);
  end component;    

--Binvert declaration
  component notB                
           port(b: in std_logic; signalb: std_logic_vector(0 downto 0); outnotB: out std_logic);
  end component;

    --ControlCircuit declaration--
component ControlCircuit
    port (
            opcode : in std_logic_vector (2 downto 0);
            signala,signalb : out std_logic_vector(0 downto 0);
            operation : out std_logic_vector (1 downto 0);
            CarryIn: out std_logic);

end component;

--mux4to1 declaration
    component mux4to1           
            port(outAND, outOR, sum, outXOR: in std_logic; operation: in std_logic_vector(1 downto 0); Result: out std_logic);
    end component;

end package erotima2;   


--2 input AND gate
library ieee;
use ieee.std_logic_1164.all;
 entity myAND2 is
     port (outnotA,outnotB: in std_logic; outAND: out std_logic);
 end myAND2;
 architecture model_conc of myAND2 is
 begin
    outAND<= outnotA and outnotB;
 end model_conc;


 -- 2 input OR gate  
library ieee;
use ieee.std_logic_1164.all;
  entity myOR2 is
        port (outnotA,outnotB: in std_logic; outOR: out std_logic);
 end myOR2;
 architecture model_conc2 of myOR2 is
  begin
        outOR <= outnotA or outnotB;
 end model_conc2;     


--2 input XOR gate
library ieee;
use ieee.std_logic_1164.all;
    entity myXOR2 is
        port(outnotA,outnotB: in std_logic; outXOR: out std_logic);
    end myXOR2;
    architecture model_conc3 of myXOR2 is
    begin 
    outXOR <= outnotA xor outnotB;
    end model_conc3;      

--3 input full adder      
library ieee;
use ieee.std_logic_1164.all;
    entity fulladder is
        port(CarryIn,outnotA,outnotB: in std_logic; sum,CarryOut: out std_logic);
    end fulladder;
    architecture model_conc4 of fulladder is
    begin
    CarryOut <= (outnotB and CarryIn) or (outnotA and CarryIn) or (outnotA and outnotB);
    sum <= (outnotA and not outnotB and not CarryIn) or (not outnotA and outnotB and not CarryIn) or (not outnotA and not outnotB and CarryIn) or (outnotA and outnotB and CarryIn);
    end model_conc4;

--1 input notA
library ieee;
use ieee.std_logic_1164.all;
    entity notA is
        port(a: in std_logic; signala:std_logic_vector(0 downto 0); outnotA: out std_logic);
    end notA;
    architecture model_conc6 of notA is
    begin
    with signala select
    outnotA <=  a when "0",
                        not a when others;
    end model_conc6;

--1 input notB    
library ieee;
use ieee.std_logic_1164.all;
    entity notB is
        port(b: in std_logic; signalb: std_logic_vector(0 downto 0); outnotB: out std_logic);
    end notB;
    architecture model_conc5 of notB is
    begin
    with signalb select
    outnotB <=  b when "0",
                        not b when others;
    end model_conc5;


--4 input MUX 
library ieee;
use ieee.std_logic_1164.all;
    entity mux4to1 is
        port(outAND, outOR, sum, outXOR: in std_logic; operation: in std_logic_vector(1 downto 0); Result: out std_logic);
    end mux4to1;
    architecture model_conc7 of mux4to1 is
    begin
    with operation select
        Result<= outAND when "00",
                 outOR  when "01",
              sum    when "10",
                   outXOR when OTHERS;
    end model_conc7 ; 

Поведенческая часть определяет логические элементы AND, OR, XOR, полный сумматор для числового сложения и вычитания. Он также содержит мультиплексор 4-к-1, который выбирает (в зависимости от значения переменной «operation»), какую операцию будет выполнять alu. Наконец, есть функция, которая инвертирует переменные, чтобы повысить эффективность использования нашего логического вентиля (используя теорему Де Моргана, поэтому нам не нужно создавать вентиль ИЛИ-НЕ). Блок управления инициализирует переменные входы, а также переменную переноса полного сумматора в зависимости от переменной «opcode». Плата со всеми возможными комбинациями Далее идет часть кода, посвященная цепи управления, которая реализует предыдущая доска.

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


entity ControlCircuit is 
    port (
            opcode      :in std_logic_vector (2 downto 0);
            signala, signalb : out  std_logic_vector(0 downto 0);
            operation : out std_logic_vector(1 downto 0);
            CarryIn : out std_logic);               
end ControlCircuit;

architecture model_conc9 of ControlCircuit is   
--signal outAND,outOR,outXOR,sum,outnotA,outnotB : std_logic;
--signal operation : out std_logic_vector(1 downto 0);  
begin
 process(opcode)
 begin

case opcode is 

    --AND--
    when "000"=>
        operation <= "00";
        signala   <= "0";
        signalb      <= "0";
        CarryIn  <= '0';

    --OR--
    when "001" =>
        operation <= "01";
        signala   <= "0";
        signalb      <= "0";
        CarryIn  <= '0';

    --ADD--         
    when "011" =>
        operation <= "10";
        signala   <= "0";
        signalb      <= "0";
        CarryIn  <= '0';

    --SUB--
    when "010" =>
        operation <= "10";
        signala   <= "0";
        signalb      <="1";
        CarryIn  <= '1';

    --NOR--
    when "101"=>
        operation <= "00";
        signala   <= "1";
        signalb      <= "1";
        CarryIn  <= '0';

    --xor
    when "100" =>
        operation <= "11";
        signala   <= "0";
        signalb      <= "0";
        CarryIn  <= '0';

    --Adiafores times--
when others =>
        operation <= "00";
        signala   <= "0";
        signalb      <= "0";
        CarryIn  <= '0';
    end case;
    end process;
end model_conc9;

        `

Наконец, вот код, который использует все предыдущие части и и диаграмму RTL, которая показывает результат кода< /а>

  library IEEE;
use ieee.std_logic_1164.all;
use work.erotima2.all;

entity structural is 
    port (a,b: in std_logic;
            opcode : in std_logic_vector ( 2 downto 0);
            Result,CarryOut : out std_logic);
end structural;

architecture alu of structural is 
    signal outAND,outOR,outXOR,sum,outnotA,outnotB,CarryIn : std_logic;
    signal signala,signalb : std_logic_vector (0 downto 0);
    signal operation : std_logic_vector (1 downto 0);
begin 

u0 : myAND2 port map (outnotA,outnotB,outAND);
u1 : myOR2 port map (outnotA,outnotB,outOR);
u2 : myXOR2 port map (outnotA,outnotB,outXOR);
u3 : fulladder port map (CarryIn,outnotA,outnotB,sum,CarryOut);
u4 : notA port map (a,signala,outnotA);
u5 : notB port map (b,signalb,outnotB);
u6 : mux4to1 port map (outAND, outOR,sum, outXOR, operation, Result );
u8 : ControlCircuit port map(opcode,signala,signalb,operation,CarryIn);
end alu; 

Теперь самое сложное: мне нужно использовать 1-битное АЛУ 16 раз в качестве компонента, чтобы создать 16-битное АЛУ. Важно, чтобы схема управления была независимой от остального кода. Я пытался использовать std_logic_vector (от 15 до 0), но это не сработало, и я хотел бы использовать предыдущие сегменты кода в качестве компонента. Может ли кто-нибудь дать какие-либо советы или идеи, которые помогут подключить 16 1-битных ALU к полному 16-битному ALU? Заранее спасибо тем, кто прочитает эту огромную стену текста.


person SteliosA    schedule 10.05.2018    source источник
comment
добро пожаловать в переполнение стека. Прочтите это. Вы публикуете так много кода, не давая четкого описания проблемы. Кажется, ваш единственный вопрос: может ли кто-нибудь дать какие-либо советы или идеи, которые помогут подключить 16 1-битных ALU к полному 16-битному ALU? Остальное вроде не нужно. Что вы уже пробовали, и где это не удалось?   -  person JHBonarius    schedule 10.05.2018
comment
p.s. в коде много ошибок.... ты его вообще проверял? Или просто методом проб и ошибок?   -  person JHBonarius    schedule 10.05.2018
comment
Привет, спасибо за ответ и извините за публикацию слишком большого количества кода. Я протестировал код, и он работал так, как предполагалось для части 1-битных вычислений (я новичок в этом языке, поэтому я не знаю, сколько ошибок в моем коде). Чтобы более четко сформулировать мой вопрос, я пытаюсь использовать уже созданный 1-битный ALU для создания 16-битного ALU, который выполняет вычисления между двумя 16-битными переменными. То, что я пытался сделать, это использовать std_logic_vector (от 15 до 0) для всех элементов кода, кроме схемы управления, которой требуется только одно использование для определения расчета между переменными (И, ИЛИ, ДОБАВИТЬ и т. д.)   -  person SteliosA    schedule 11.05.2018
comment
Это не сработало, что, я считаю, является ошибкой присоединения кода схемы управления к той части, которую мне нужно повторить. Итак, я пытаюсь понять, был ли способ, которым я пытался реализовать решение, правильным, но выполнение было неправильным, или это было совершенно неправильно с самого начала. Еще раз спасибо за ваше время!   -  person SteliosA    schedule 11.05.2018
comment
Возможный дубликат Создание 16-битного ALU с использованием 1-битных ALU, Создание 4-битного ALU из несколько 1-битных АЛУ и многие другие, найденные с помощью поиска   -  person scary_jeff    schedule 11.05.2018
comment
Ну и одна из проблем уже есть: как ты собираешься подключать CarryOut к следующему structural? Ваш код довольно странный. Инвертирование всех сигналов перед их подключением к следующему логическому элементу. Это для курса VHDL? В таком случае я предлагаю вам поискать примеры ALU в Интернете, потому что вашему профессору этот код не понравится...   -  person JHBonarius    schedule 11.05.2018
comment
Да, я понимаю, что мой код странный, но нам было поручено инвертировать входные данные в соответствии с !этой диаграммой. Что касается дублирующихся постов, я проверял перед публикацией и они были реализованы только структурно, а в моем случае нужно написать еще и поведенческую часть.   -  person SteliosA    schedule 11.05.2018
comment
Может быть, вы должны предоставить все инструкции, которые вам дали. Диаграмма RTL не соответствует предоставленной вам 1-битной алюминиевой диаграмме (нет переноса, который используется в LSB для добавления 1 для вычитания, добавлены элементы управления инверсией). Создайте структурную единицу, соответствующую 1-битной алюминиевой диаграмме, и используйте ее в качестве основы. Не используйте значения length1 std_logic_vector. Вы обнаружите, что управление естественным образом выходит за пределы и может использоваться для алюминия любого размера. Включите эту диаграмму в свой вопрос.   -  person    schedule 12.05.2018


Ответы (1)


Ваш недавний комментарий

Да, я понимаю, что мой код странный, но нам было поручено инвертировать входные данные в соответствии с этой диаграммой. Что касается дублирующихся постов, я проверял перед публикацией и они были реализованы только структурно, а в моем случае нужно написать еще и поведенческую часть.

1-битная алюминиевая диаграмма

Объясняет проблему, за исключением опечаток. Вы заметите, что ваша архитектура структуры структуры объекта не соответствует сигналам, показанным на приведенной выше 1-битной диаграмме alu, которая не содержит созданного экземпляра ControlCircuit.

Если бы вы предоставили модуль проектирования, соответствующий приведенной выше диаграмме, вы можете подключить 1-битную цепочку переноса alu, получая перенос для младшего бита из блока управления, который обеспечивает + 1 и инверсию для вычитания:

library ieee;
use ieee.std_logic_1164.all;

entity alu_16_bit is
    port (
        a:          in  std_logic_vector (15 downto 0);
        b:          in  std_logic_vector (15 downto 0);
        opcode:     in  std_logic_vector (2 downto 0);
        result:     out std_logic_vector (15 downto 0);
        carryout:   out std_logic
    );
end entity;

architecture foo of alu_16_bit is
    component alu_1_bit is
        port (
            a:          in  std_logic;
            b:          in  std_logic;
            ainvert:    in  std_logic;
            binvert:    in  std_logic;
            carryin:    in  std_logic;
            operation:  in  std_logic_vector (1 downto 0);
            result:     out std_logic;
            carryout:   out std_logic
        );
    end component;
    component controlcircuit is
        port (
            opcode:     in  std_logic_vector(2 downto 0);
            ainvert:    out std_logic;
            binvert:    out std_logic;
            operation:  out std_logic_vector(1 downto 0);
            carryin:    out std_logic  -- invert a or b, add + 1 for subtract
        );
    end component;

    signal ainvert:     std_logic;
    signal binvert:     std_logic;
    signal operation:   std_logic_vector (1 downto 0);
    signal carry:       std_logic_vector (16 downto 0);
begin

CONTROL_CIRCUIT:
    controlcircuit
        port map (
            opcode => opcode,
            ainvert => ainvert,
            binvert => binvert,
            operation => operation,
            carryin => carry(0)   -- for + 1 durring subtract
        );

GEN_ALU:
    for i in 0 to 15 generate
ALU:
        alu_1_bit
            port map (
                a => a(i),
                b => b(i),
                ainvert => ainvert,
                binvert => binvert,
                carryin => carry(i),
                operation => operation,
                result => result(i),
                carryout => carry(i + 1) 
            );
    end generate;

    carryout <= carry(16) when operation = "10" else '0';

end architecture;

Это представляет собой удаление ControlCircuit из структурного — требуется только одна копия, переименование структурного alu

library ieee;
use ieee.std_logic_1164.all;

entity alu_16_bit is
    port (
        a:          in  std_logic_vector (15 downto 0);
        b:          in  std_logic_vector (15 downto 0);
        opcode:     in  std_logic_vector (2 downto 0);
        result:     out std_logic_vector (15 downto 0);
        carryout:   out std_logic
    );
end entity;

architecture foo of alu_16_bit is
    component alu_1_bit is
        port (
            a:          in  std_logic;
            b:          in  std_logic;
            ainvert:    in  std_logic;
            binvert:    in  std_logic;
            carryin:    in  std_logic;
            operation:  in  std_logic_vector (1 downto 0);
            result:     out std_logic;
            carryout:   out std_logic
        );
    end component;
    component controlcircuit is
        port (
            opcode:     in  std_logic_vector(2 downto 0);
            ainvert:    out std_logic;
            binvert:    out std_logic;
            operation:  out std_logic_vector(1 downto 0);
            carryin:    out std_logic  -- invert a or b, add + 1 for subtract
        );
    end component;

    signal ainvert:     std_logic;
    signal binvert:     std_logic;
    signal operation:   std_logic_vector (1 downto 0);
    signal carry:       std_logic_vector (16 downto 0);
begin

CONTROL_CIRCUIT:
    controlcircuit
        port map (
            opcode => opcode,
            ainvert => ainvert,
            binvert => binvert,
            operation => operation,
            carryin => carry(0)   -- for + 1 durring subtract
        );

GEN_ALU:
    for i in 0 to 15 generate
ALU:
        alu_1_bit
            port map (
                a => a(i),
                b => b(i),
                ainvert => ainvert,
                binvert => binvert,
                carryin => carry(i),
                operation => operation,
                result => result(i),
                carryout => carry(i + 1) 
            );
    end generate;

    carryout <= carry(16) when operation = "10" else '0';

end architecture;
bit и согласование портов.

Существует новый верхний уровень alu_16_bit, содержащий один экземпляр ControlCircuit, а также шестнадцать экземпляров alu

library ieee;
use ieee.std_logic_1164.all;

entity alu_16_bit is
    port (
        a:          in  std_logic_vector (15 downto 0);
        b:          in  std_logic_vector (15 downto 0);
        opcode:     in  std_logic_vector (2 downto 0);
        result:     out std_logic_vector (15 downto 0);
        carryout:   out std_logic
    );
end entity;

architecture foo of alu_16_bit is
    component alu_1_bit is
        port (
            a:          in  std_logic;
            b:          in  std_logic;
            ainvert:    in  std_logic;
            binvert:    in  std_logic;
            carryin:    in  std_logic;
            operation:  in  std_logic_vector (1 downto 0);
            result:     out std_logic;
            carryout:   out std_logic
        );
    end component;
    component controlcircuit is
        port (
            opcode:     in  std_logic_vector(2 downto 0);
            ainvert:    out std_logic;
            binvert:    out std_logic;
            operation:  out std_logic_vector(1 downto 0);
            carryin:    out std_logic  -- invert a or b, add + 1 for subtract
        );
    end component;

    signal ainvert:     std_logic;
    signal binvert:     std_logic;
    signal operation:   std_logic_vector (1 downto 0);
    signal carry:       std_logic_vector (16 downto 0);
begin

CONTROL_CIRCUIT:
    controlcircuit
        port map (
            opcode => opcode,
            ainvert => ainvert,
            binvert => binvert,
            operation => operation,
            carryin => carry(0)   -- for + 1 durring subtract
        );

GEN_ALU:
    for i in 0 to 15 generate
ALU:
        alu_1_bit
            port map (
                a => a(i),
                b => b(i),
                ainvert => ainvert,
                binvert => binvert,
                carryin => carry(i),
                operation => operation,
                result => result(i),
                carryout => carry(i + 1) 
            );
    end generate;

    carryout <= carry(16) when operation = "10" else '0';

end architecture;
bit, разработанных на основе оператора generate с использованием параметра generate i для индексации значений массивов для соединений.

Этот дизайн был поведенчески реализован независимо с использованием таблицы кодов операций, на которую вы предоставили ссылку:

Таблица опкодов

а также независимый полный сумматор, используемый в alu

library ieee;
use ieee.std_logic_1164.all;

entity alu_16_bit is
    port (
        a:          in  std_logic_vector (15 downto 0);
        b:          in  std_logic_vector (15 downto 0);
        opcode:     in  std_logic_vector (2 downto 0);
        result:     out std_logic_vector (15 downto 0);
        carryout:   out std_logic
    );
end entity;

architecture foo of alu_16_bit is
    component alu_1_bit is
        port (
            a:          in  std_logic;
            b:          in  std_logic;
            ainvert:    in  std_logic;
            binvert:    in  std_logic;
            carryin:    in  std_logic;
            operation:  in  std_logic_vector (1 downto 0);
            result:     out std_logic;
            carryout:   out std_logic
        );
    end component;
    component controlcircuit is
        port (
            opcode:     in  std_logic_vector(2 downto 0);
            ainvert:    out std_logic;
            binvert:    out std_logic;
            operation:  out std_logic_vector(1 downto 0);
            carryin:    out std_logic  -- invert a or b, add + 1 for subtract
        );
    end component;

    signal ainvert:     std_logic;
    signal binvert:     std_logic;
    signal operation:   std_logic_vector (1 downto 0);
    signal carry:       std_logic_vector (16 downto 0);
begin

CONTROL_CIRCUIT:
    controlcircuit
        port map (
            opcode => opcode,
            ainvert => ainvert,
            binvert => binvert,
            operation => operation,
            carryin => carry(0)   -- for + 1 durring subtract
        );

GEN_ALU:
    for i in 0 to 15 generate
ALU:
        alu_1_bit
            port map (
                a => a(i),
                b => b(i),
                ainvert => ainvert,
                binvert => binvert,
                carryin => carry(i),
                operation => operation,
                result => result(i),
                carryout => carry(i + 1) 
            );
    end generate;

    carryout <= carry(16) when operation = "10" else '0';

end architecture;
bit и кажется функциональным.

Это означает, что ваши проектные единицы не были проверены.

person Community    schedule 12.05.2018
comment
Спасибо за этот очень подробный ответ! Я полностью понял, что я делал неправильно все это время. Большое тебе спасибо! - person SteliosA; 13.05.2018