今天偶尔发现了一个异常简洁且工整的计数器,同时也犯了一个很典型的错误,于是记录下来。
library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
entity time_out is
port( clk,rst_n,en:in std_logic;
num_in0,num_in1,num_in2,num_in3,num_in4,num_in5:in std_logic_vector(3 downto 0);
num0,num1,num2,num3,num4,num5:out std_logic_vector(3 downto 0));
end time_out;
architecture behav of time_out is
signal tempnum_0,tempnum_1,tempnum_2,tempnum_3,tempnum_4,tempnum_5:std_logic_vector(3 downto 0);
begin
process(clk)
variable count_1s:integer range 0 to 50000000 := 0;
begin
if clk'event and clk='1' then
if count_1s=49999999 THEN
count_1s:=0;
IF tempnum_0="1001" THEN
tempnum_0<="0000";
IF tempnum_1="0101" THEN
tempnum_1<="0000";
IF tempnum_2="1001" THEN
tempnum_2<="0000";
IF tempnum_3="0101" THEN
tempnum_3<="0000";
IF tempnum_4="0011" THEN
tempnum_4<="0000";
IF tempnum_5="0010" THEN
tempnum_5<="0000";
ELSE
tempnum_5<= tempnum_5+ '1';
END IF;
ELSE
tempnum_4<= tempnum_4+ '1';
END IF;
ELSE
tempnum_3<=tempnum_3+ '1';
END IF;
ELSE
tempnum_2<=tempnum_2+ '1';
END IF;
ELSE
tempnum_1<= tempnum_1+ '1';
END IF;
ELSE
tempnum_0<=tempnum_0+ '1';
END IF;
ELSE
count_1s := count_1s + 1;
END IF;
end if;
END PROCESS;
process(en)
begin
if en'event and en='1' then
tempnum_0<=num_in0;
tempnum_1<=num_in1;
tempnum_2<=num_in2;
tempnum_3<=num_in3;
tempnum_4<=num_in4;
tempnum_5<=num_in5;
end if;
end process;
num0<=tempnum_0;
num1<=tempnum_1;
num2<=tempnum_2;
num3<=tempnum_3;
num4<=tempnum_4;
num5<=tempnum_5;
end behav;
上面第一个process就是一个简洁的计数器,自带分频,非常巧妙。上面代码典型的错误是在多个进程里对一个信号赋值,由于进程的并行性,这种操作是不允许的,会报错:
Error (10028): Can't resolve multiple constant drivers for net……
顺便提一下if与elsif语句,一般格式是
if 条件一 then 语句一
elsif 条件二 then 语句二
elsif 条件三 then 语句三
else 语句四
end if
编译时先判断是否满足条件一,若满足执行语句一,若不满足则判断是否满足条件二,若满足则执行语句二……层层推进。特别要注意的是,clk’event之后不能再接elsif,因为这样会判断为多边沿触发,报错提示
Error (10818): Can't infer register for …… at…… because it does not hold its value outside the clock edge