// ER_bidir.vams - basic Verilog-AMS connection module for electrical
// and discrete wreal bidirectional conversion
// last revised:  08/29/06, jhou
//
// REVISION HISTORY:
// Created:  08/29/06, jhou

`include "disciplines.vams"
`timescale 1ns / 100ps

connectmodule ER_bidir (Din, Aout);
inout Din;
wreal Din;         //inout wreal
\logic Din;        //discrete domain
inout Aout;
electrical Aout;   //inout electrical

  parameter real vdelta=1.8/64   from (0:inf); // voltage delta
  parameter real vtol=vdelta/4   from (0:vdelta); // voltage tolerance
  parameter real ttol=10p        from (0:1m];     // time tolerance
  parameter real tr=10p          from (0:1m);  // risetime
  parameter real tf=tr           from (0:1m);  // falltime
  parameter real tdelay=0        from [0:1m);  // delay time of analog output
  parameter real rout=200        from (0:inf); // output resistance
  parameter real rz=10M          from (0:inf); // open resistance

  real Dreg;       //real register for A to D wreal conversion
  real Vstate;     //real register for D wreal to A conversion
  real Rout;       //output resistance

  initial begin
        Vstate = Din;
        if ($driver_count(Din) == 0)
            Rout = rz;
        else
            Rout = rout;
  end

  always @(Din) begin
      //filter out digital noise within +/-vdelta
      if (Din-Vstate>=vdelta || Vstate-Din>=vdelta) begin
          Vstate = Din;
      end
  end

  //discretize V(Aout) triggered by absdelta function
  always @(absdelta(V(Aout), vdelta, ttol, vtol))
	Dreg = V(Aout);

  assign Din = Dreg;

  analog begin
        I(Aout) <+ (V(Aout) - transition(Vstate, tdelay, tr, tf))/Rout;
  end

endmodule
