Skip to content

Instantly share code, notes, and snippets.

@liang799
Last active November 21, 2025 04:48
Show Gist options
  • Select an option

  • Save liang799/0edd5ea19f002af2eb1c120cd2e720d0 to your computer and use it in GitHub Desktop.

Select an option

Save liang799/0edd5ea19f002af2eb1c120cd2e720d0 to your computer and use it in GitHub Desktop.
Digital Logic SC1005 Final Exam
/*
Key Idea: next state, current state
use the observer pattern to do actions on state change
*/
module FSM_Q4b (
input CLK,
input RESET, // Asynchronous active high reset
input T,
output reg Y
);
// Define state encodings for readability
parameter STATE_A = 2'b00,
STATE_B = 2'b01,
STATE_C = 2'b11,
STATE_D = 2'b10;
// State registers
reg [1:0] current_state;
reg [1:0] next_state;
// --- State Transition Logic (Sequential Block) ---
// Updates current_state on CLK edge, handles asynchronous RESET
always @(posedge CLK or posedge RESET) begin
if (RESET) begin
// Asynchronous Reset to initial state A
current_state <= STATE_A;
end else begin
// Synchronous update on CLK
current_state <= next_state;
end
end
// --- Next State Logic (Combinational Block) ---
// Determines the next state based on current_state and input T
always @(*) begin
// Default next_state to current_state to avoid latch inference
next_state = current_state;
case (current_state)
STATE_A: begin
if (T == 1'b0)
next_state = STATE_A;
else // T == 1'b1
next_state = STATE_B;
end
STATE_B: begin
if (T == 1'b0)
next_state = STATE_A;
else // T == 1'b1
next_state = STATE_C;
end
STATE_C: begin
if (T == 1'b0)
next_state = STATE_B;
else // T == 1'b1
next_state = STATE_D;
end
STATE_D: begin
if (T == 1'b0)
next_state = STATE_C;
else // T == 1'b1
next_state = STATE_D;
end
default: begin
// Should not happen, but reset to a safe state
next_state = STATE_A;
end
endcase
end
// --- Output Logic (Combinational Block for Moore Machine) ---
// Output Y is solely determined by the current_state
always @(current_state) begin
case (current_state)
STATE_A, STATE_B: begin
// A (Y=0), B (Y=0)
Y = 1'b0;
end
STATE_C, STATE_D: begin
// C (Y=1), D (Y=1)
Y = 1'b1;
end
default: begin
Y = 1'b0; // Safe default
end
endcase
end
endmodule
@liang799
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment