Saturday, 23 January 2016

Difference between rising_edge(clk) and (clk'event and clk='1') in VHDL


In VHDL there are two ways to find an edge transition of any signal (generally clock).

  1. rising_edge(clk)
  2. clk'event and clk = '1' 
So in this article I will explain the difference between rising_edge or falling_edge function and clk'event based edge detection. 

Example 1:
library ieee;
use ieee.std_logic_1164.all;
entity core1 is
end entity;
architecture core1 of core1 is
constant clk_period : time := 2 ns;
signal clk : std_logic := '0';
signal a : std_logic := '0';
signal b : std_logic := '0';
begin
process
begin
clk <= '0';
wait for clk_period/2; --for 1 ns signal is '0'.
clk <= '1';
wait for clk_period/2; --for next 1 ns signal is '1'.
end process;
process (clk)
begin
if (rising_edge(clk)) then
a <= not a;
end if;
if (clk'event and clk='1') then
b <= not b;
end if;
end process;
process
begin
wait for 10 ns; --run the simulation for this duration
assert false
report "simulation ended"
severity failure;
end process;
end core1;


Result of Example 1:
 

Example 2:
library ieee;
use ieee.std_logic_1164.all;
entity core1 is
end entity;
architecture core1 of core1 is
constant clk_period : time := 2 ns;
signal clk : std_logic := '0';
signal a : std_logic := '0';
signal b : std_logic := '0';
begin
process
begin
clk <= 'Z';
wait for clk_period/2; --for 1 ns signal is '0'.
clk <= '1';
wait for clk_period/2; --for next 1 ns signal is '1'.
end process;
process (clk)
begin
if (rising_edge(clk)) then
a <= not a;
end if;
if (clk'event and clk='1') then
b <= not b;
end if;
end process;
process
begin
wait for 10 ns; --run the simulation for this duration
assert false
report "simulation ended"
severity failure;
end process;
end core1;
Result of Example 2:

To get a clear view look at the rising_edge function as implemented in std_logic_1164 library:

FUNCTION rising_edge (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
RETURN (s'EVENT AND (To_X01(s) = '1') AND
(To_X01(s'LAST_VALUE) = '0'));
END;

As you can see the function returns a value "TRUE" only when the present value is '1' and the last value is '0'.If the past value is something like 'Z','U' etc. then it will return a "FALSE" value.This makes the code, bug free, beacuse the function returns only valid clock transitions,that means '0' to '1'.All the rules and examples said above equally apply to falling_edge() function also. 

But the statement (clk'event and clk='1') results TRUE when the present value is '1' and there is an edge transition in the clk.It doesnt see whether the previous value is '0' or not.



No comments:

Post a Comment