Verilog Coding
Can you develop HDL code for a 3-state FSM (IDLE, READ, WRITE), with transitions based on the "op" input signal and a 4-clock-cycle return to IDLE?
Design Verification Engineer
Apple
Meta
Xilinx
Samsung
ByteDance
Oracle
Answers
Anonymous
6 months ago
module fsm (
input wire clk, // Clock signal
input wire reset_n, // Active low reset
input wire op, // Operation signal: 0 for READ, 1 for WRITE
output reg [1:0] state // Current state of the FSM
);
// Define states using parameters
localparam [1:0] IDLE = 2'b00,
READ = 2'b01,
WRITE = 2'b10;
reg [1:0] next_state; // Next state logic
reg [2:0] cycle_count; // Counter for clock cycles (3-bit to count up to 4)
// State transition logic (sequential logic)
always @(posedge clk or negedge reset_n) begin
if (!reset_n) begin
state <= IDLE; // Reset to IDLE state
cycle_count <= 3'b000; // Reset cycle counter
end
else begin
state <= next_state; // Update current state to next state
if (state == READ || state == WRITE) begin
cycle_count <= cycle_count + 1'b1; // Increment counter in READ/WRITE
end
else begin
cycle_count <= 3'b000; // Reset counter in IDLE state
end
end
end
// Next state logic (combinational logic)
always @(*) begin
case (state)
IDLE: begin
if (op == 1'b0)
next_state = READ; // Go to READ state if op is 0
else
next_state = WRITE; // Go to WRITE state if op is 1
end
READ: begin
if (cycle_count == 3'd3)
next_state = IDLE; // After 4 clock cycles, go back to IDLE
else
next_state = READ; // Remain in READ state until 4 cycles
end
WRITE: begin
if (cycle_count == 3'd3)
next_state = IDLE; // After 4 clock cycles, go back to IDLE
else
next_state = WRITE; // Remain in WRITE state until 4 cycles
end
default: next_state = IDLE; // Default case to handle any invalid state
endcase
end
endmodule
Interview question asked to Design Verification Engineers interviewing at Samsung, Huawei, Autodesk and others: Can you develop HDL code for a 3-state FSM (IDLE, READ, WRITE), with transitions based on the "op" input signal and a 4-clock-cycle return to IDLE?.