/*
 AD9512 clock distribution chip serial port interface

 Copyright (c) 2008 Dimtel, Inc., All Rights Reserved

 $Id: ad9512.v,v 1.1 2009/08/29 19:55:33 dim Exp $
 $Date: 2009/08/29 19:55:33 $
 $Author: dim $
 $Revision: 1.1 $
 $Log: ad9512.v,v $
 Revision 1.1  2009/08/29 19:55:33  dim
 Moved from llrf/verilog to verilog_common

 Revision 1.1.1.1  2009/06/02 20:26:02  dim
 Initial import


*/

`include "bus_width.h"

module ad9512(
  // Local bus interface
  input			clk,	// local clock
  input			strobe,	// bus strobe
  input			ce,	// clock enable / module select
  input			rd,	// read/write
  output reg		ack,	// ack from the module
  input [6:0] 		addr,	// 7 bit register address
  input [7:0]		din,	// from the bus
  output [`IFACE-1:0]	dout,	// data to the bus

  // AD9512 control lines
  (* IOB = "FALSE" *)
  output reg		sclk,	// serial clock
  (* IOB = "FALSE" *)
  output reg		sdio,	// serial data
  (* IOB = "FALSE" *)
  output reg		csb	// load
);
  // Registers
  reg [23:0] sft_reg;
  parameter IDLE = 6'h3f; parameter START = 6'h00;
  parameter END = 6'h30;
  reg [5:0] state = IDLE;

  initial begin
    ack <= 1'b0;
    sclk <= 1'b0;
    sdio <= 1'b0;
    csb <= 1'b1;
  end

  // Bus clock is at 48 MHz. SCLK is then at 24 MHz - within the 25 MHz spec

  always @(posedge clk) begin
    if (strobe & ce & ~ack & (state == IDLE) & csb)
      if (~rd) begin
        // R/W, W[1:0], A[12:7], A[6:0], D[7:0]
        sft_reg <= {1'b0, 2'b0, 6'b0, addr, din[7:0]};
	state <= START;
	csb   <= 1'b0;
      end
      else
        ack <= 1'b1;
    if (ack) begin
      ack <= 1'b0;
    end
    if (state != IDLE)
      if (state == END) begin
        state  <= IDLE;
        sclk   <= 1'b0;
        csb    <= 1'b1;
        ack    <= 1'b1;
      end
      else begin
        state <= state + 6'b1;
        if (~state[0]) begin
          sdio <= sft_reg[23];
          sft_reg <= {sft_reg[22:0], 1'b0};
          sclk <= 1'b0;
        end
        else
          sclk <= 1'b1;
      end
  end

  assign dout = `IFACE'b0;
  
endmodule // ad9512
