// N-level triggered quantizer (like an ADC followed by a DAC)
//
// Version 1b, 17 July 03
//
// Ken Kundert
//
// Downloaded from The Designer's Guide (www.designers-guide.org).
// Post any questions to www.designers-guide.org/Forum

`include "disciplines.vams"

module quantizer (out, in, clk);

output out; voltage out;// output
input in; voltage in;	// input
input clk; voltage clk;	// clock input (edge triggered)
parameter integer levels=2 from [2:inf);// number of quantization levels
parameter real vh = +1;			// voltage of highest level
parameter real vl = -1 from (-inf:vh);	// voltage of lowest level
parameter real vth = (vh + vl)/2;	// threshold voltage of clock
parameter integer dir = +1 from [-1:+1] exclude 0;
			// if dir=+1, rising clock edge triggers
			// if dir=-1, falling clock edge triggers
parameter real td = 0 from [0:inf);	// output delay
parameter real tt = 0 from [0:inf);	// output transition time
real quantized, delta;
integer level;

analog begin
    @(cross(V(clk) - vth, dir) or initial_step) begin
	delta = (vh-vl)/(levels-1);
	level = (V(in)-vl)/delta;
	if (level < 0)
	    level = 0;
	else if (level >= levels)
	    level = levels-1;
	quantized = level * delta + vl;
    end
    V(out) <+ transition( quantized, td, tt );
end
endmodule