Verilog Code for Edge Detector: Syntax and Example
An edge detector in
Verilog detects changes in a signal by comparing its current and previous values using a register. You can implement a rising edge detector by storing the previous signal state and checking when the signal changes from 0 to 1 using always @(posedge clk) blocks.Syntax
An edge detector typically uses a clocked process to store the previous value of the input signal and compares it with the current value to detect edges.
reg prev_signal;: Stores the previous state of the input.always @(posedge clk): Runs the block on the rising edge of the clock.prev_signal <= signal;: Updates the previous signal value.wire rising_edge = signal && !prev_signal;: Detects rising edge when signal changes from 0 to 1.
verilog
reg prev_signal;
wire rising_edge;
always @(posedge clk) begin
prev_signal <= signal;
end
assign rising_edge = signal & ~prev_signal;Example
This example shows a simple rising edge detector module. It outputs a high pulse for one clock cycle when the input signal rises from 0 to 1.
verilog
module edge_detector(
input wire clk,
input wire signal,
output wire rising_edge
);
reg prev_signal;
always @(posedge clk) begin
prev_signal <= signal;
end
assign rising_edge = signal & ~prev_signal;
endmoduleCommon Pitfalls
Common mistakes when writing edge detectors include:
- Not using a clocked process to store the previous signal, which causes incorrect edge detection.
- Using combinational logic only, which can cause glitches or multiple pulses.
- Forgetting to initialize the previous signal register, which may cause unpredictable output at start.
Always use a clocked always @(posedge clk) block to update the previous signal and detect edges reliably.
verilog
/* Wrong way: combinational edge detection causes glitches */ assign rising_edge_wrong = signal & ~prev_signal; // prev_signal not updated in clocked block /* Right way: clocked update of prev_signal */ always @(posedge clk) begin prev_signal <= signal; end assign rising_edge = signal & ~prev_signal;
Quick Reference
Tips for writing edge detectors in Verilog:
- Use a register to hold the previous input value.
- Update this register only on the clock's rising edge.
- Detect rising edge with
signal && !prev_signal. - Detect falling edge with
!signal && prev_signal. - Initialize registers to avoid unknown states.
Key Takeaways
Use a clocked register to store the previous signal value for reliable edge detection.
Detect rising edges by checking when the signal changes from 0 to 1 using current and previous values.
Avoid combinational edge detection to prevent glitches and multiple pulses.
Initialize registers to known states to ensure predictable behavior at startup.