// File name	: oneshot.v
// Written by	: Jianjian Song, Nov. 2000
// One shot circuit to debounce the falling edge of signal IN
// and generate on negative pulse of one clock period.
// Note: The simualation does not show correct behaviour when procedural assignments are non-blocking (<=).
module oneshot(BUFFER_IN,BUFFER_OUT,CLK);
input		CLK;
input		BUFFER_IN;	// input signal
output		BUFFER_OUT;	// debounced output signal
// decimal digits
reg		BUFFER_OUT;
reg	[2:0]	counter;	// delay counter
parameter	DELAY_CYLCES = 4;
reg	[1:0]	CurrentState, NextState;
// state codes
parameter	START = 2'b00, PULSE = 2'b01, FALLING_EDGE_DELAY=2'b10, WAIT =2'b11;
// State registers
always @ (CurrentState)
	if (CurrentState==PULSE)
		BUFFER_OUT = 0;
	else
		BUFFER_OUT = 1;
//
always @ (posedge CLK)
begin
	CurrentState = NextState;
// Next state and output logic
	case (CurrentState)
	START:
		begin
		counter = DELAY_CYLCES;
		if (BUFFER_IN == 1)
			NextState = START;
		else 
			NextState = PULSE;
		end
	FALLING_EDGE_DELAY:
		if (counter!=0)	// add delay to debounce input
		begin
			counter = counter -1;
			NextState = FALLING_EDGE_DELAY;
		end
		else
			NextState = PULSE;
	PULSE:
		begin
			NextState = WAIT;
			counter = DELAY_CYLCES;
		end
	WAIT:		// wait for the current input to go HIGH
		if (BUFFER_IN == 0)
			NextState = WAIT;
		else if (counter != 0)
		begin		// add delay to debounce rising edge on input
			counter = counter - 1;
			NextState = WAIT;
		end
		else
			NextState = START;
	endcase
end
endmodule