Re: im doing a 7-segment multiplexing code but i have error and bcd part is wrong
In this case, the frequency divider counts correctly because it uses "blocking" variable assignments. But it's bad design practice in several regards:
- it's bad to use variable instead of signals for the counter due to the timing of multiple assignments in one clock cycle. (In this special case, the construct can be considered as a useful behavioral description, functional equivalent to a counter using signals, better you don't even start to write RTL code this way though)
Oops, didn't even notice the variable used as a counter I only noticed the compares.
Here is a good reason why you don't want to use variables in a counter:
test1 - variable counter divide by 10 written like above code.
Code VHDL - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
| library ieee;
use ieee.std_logic_1164.all;
entity test is
port (
clk_10m : in std_logic;
clk_1m : out std_logic
);
end test;
architecture behave of test is
begin
clk_div: process(clk_10m)
variable c : integer range 0 to 10;
begin
if rising_edge(clk_10m) then
c := c + 1;
if (c = 10) then
clk_1m <='0';
c := 0;
elsif (c = 5) then
clk_1m <= '1';
elsif (c < 5) then
clk_1m <= '0';
end if;
end if;
end process clk_div;
end behave; |
Elaborated RTL circuit...
Synthesised circuit...
Take note of the number of cells used
test2 - signal counter divide by 10.
Code VHDL - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| library ieee;
use ieee.std_logic_1164.all;
entity test2 is
port (
clk_10m : in std_logic;
clk_1m : out std_logic
);
end test2;
architecture behave of test2 is
signal c : integer range 0 to 9;
begin
clk_div: process(clk_10m)
begin
if rising_edge(clk_10m) then
if (c < 9) then
c <= c + 1;
else
c <= 0;
end if;
if (c < 5) then
clk_1m <= '0';
else
clk_1m <= '1';
end if;
end if;
end process clk_div;
end behave; |
Elaborated RTL circuit...
Notice there are less layers of logic between flip-flops.
The synthesized circuit...
- - - Updated - - -
The take away here is that using variables for counters and other registered logic ends up with the flip-flops before a bunch of combinational logic (see first picture).
In the variable case the +1 operation occurs after the flip-flops and then feeds the compare operations. Both the counting and the compares are adding delay to the path.
In the signal case the +1 operation occurs before the flip-flops and the output of the flip-flops feed the compare operations, this reduces the logic on the output of the counter resulting in a higher Fmax.