# Why am I getting weird behavior when building 4-bit down counter?

I'm attempting to build a 4-bit modulo-10 down-counter (i.e 9,8,7...,1,0,9,8,7...0). Here is my code so far:

LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.NUMERIC_STD.ALL;

ENTITY downcounter is
PORT (
enable  : in std_logic;
reset   : in std_logic;
clk     : in std_logic;
count   : out std_logic_vector(3 downto 0));
END downcounter;

ARCHITECTURE Behavior OF downcounter IS

COMPONENT Tflipflop
PORT (
clk   : in std_logic;
T     : in std_logic;
Q     : out std_logic);
ENDCOMPONENT;

SIGNAL Q0 : std_logic := '1';
SIGNAL Q1 : std_logic := '0';
SIGNAL Q2 : std_logic := '0';
SIGNAL Q3 : std_logic := '1';

SIGNAL TFF2IN : std_logic;
SIGNAL TFF3IN : std_logic;
SIGNAL TFF4IN : std_logic;

BEGIN

TFF1: Tflipflop PORT MAP (clk, enable, Q0);

TFF2IN <= (NOT Q0) AND enable;

TFF2: Tflipflop PORT MAP (clk, TFF2IN, Q1);

TFF3IN <= (NOT Q1) AND TFF2IN;

TFF3: Tflipflop PORT MAP (clk, TFF3IN, Q2);

TFF4IN <= (NOT Q2) AND TFF3IN;

TFF4: Tflipflop PORT MAP (clk, TFF4IN, Q3);

PROCESS (clk)
BEGIN
IF FALLING_EDGE(clk) THEN
IF reset = '0' OR (Q3='1' AND Q1='1') OR (Q3='1' AND Q2='1') THEN
count <= "1001";
ELSE
count <= Q3 & Q2 & Q1 & Q0;
END IF;
END IF;
END PROCESS;

END Behavior;


I'm currently testing it in model-sim, but I'm getting this weird behavior: The counter works from 9 to 0, but then when it reaches 9 again, it just stops there. Then after the same amount of time each time, it begins to work again!

I've tried my best to figure it out but I just can't. Any help is appreciated!

Edit: if a schematic helps, I'm basically doing this: except the enable is connected and AND-ed with each input of each T Flip Flop.

• To debug a circuit like this, you can't just look at the top-level signals. You have to go down into the hierarchy and add internal signals to your waveform. Then you can see what is all happening. – Oldfart Apr 13 '20 at 7:21
• It's doing what you asked it. – user_1818839 Apr 13 '20 at 10:43
• @BrianDrummond After your remark I suddenly noticed the error. – Oldfart Apr 13 '20 at 12:15
• @BrianDrummond how? – Sami Jr Apr 13 '20 at 22:10
• You're asking the counter (Q3..Q0) to keep counting until it rolls over at 15, while holding the output (confusingly, called "count") at 9. – user_1818839 Apr 13 '20 at 22:21