// this module configures the DRV8353,
// leaving the PWM for a different module
// if the fault pin is triggered
// it will read the fault status registers
// and assert the appropriate output wire
// it also allows disabling/enabling
// the MOSFETs using the coast/brake pins
// in the driver control register
module drv8353r_driver(
  input clk,
  input rst,
  input en,

  input drv_fault_n,
  output drv_en,

  output drv_cs_n,
  output drv_sck,
  output drv_sdi,
  output drv_sdo,

  // assert stop with the coast_nbrake
  // bit to disable the gate drivers
  input stop,
  input coast_nbrake,
  input clear_fault,

  output rdy,
  output fault_a,
  output fault_b,
  output fault_c,
  );

wire [15:0] driver_control;
wire [15:0] hs_control;
wire [15:0] ls_control;
wire [15:0] ocp_control;
wire [15:0] csa_control;

assign driver_control = {
  4'b0010, // address = 0x02
  1'b1, // write
  1'b0, // OCP_ACT, shutdown affected half bridge on fault
  1'b0, // DIS_GDUV, undervoltage enabled
  1'b0, // DIS_GDF, gate drive fault enabled
  1'b0, // OTW_REP, overtemp not reported
  2'b01, // PWM_MODE, 3x PWM mode
  1'b0, // 1PWM_COM, 1x PWM uses synchronous rectifier
  1'b0, // 1PWM_DIR, default
  1'b0, // COAST, disabled
  1'b0, // BRAKE, disabled
  1'b0, // CLR_FLT, no clear
};
// TODO actually calculate HS/LS gate drive
// requirements
assign hs_control = {
  4'b0011, // address = 0x03
  1'b1, // write
  3'b000, // LOCK, don't lock or unlock
  4'b0100, // IDRIVEP_HS, 300 mA
  4'b0010, // IDRIVEN_HS, 200 mA
};
assign ls_control = {
  4'b0100, // address = 0x04
  1'b1, // write
  1'b1, // CBC, OCP conditions reset when PWM is provided
  2'b11, // TDRIVE = 4000 ns gate-current drive time
  4'b0100, // IDRIVEP_LS, 300 mA
  4'b0010, // IDRIVEN_LS, 200 mA
};
assign ocp_control = {
  4'b0101, // address = 0x05
  1'b1, // write
  1'b0, // TRETRY, VDS_OCP/SEN_OCP retry time is 8ms
  2'b01, // DEAD_TIME, 100 ns deadtime
  2'b01, // OCP_MODE, overcurrent causes automatic retry
  2'b10, // OCP_DEG, 4us overcurrent deglitch
  4'b1101, // VDS_LVL, 1V
};
assign csa_control = {
  4'b0110, // address = 0x06
  1'b1, // write
  1'b0, // CSA_FET = SPx
  1'b0, // VREF_DIV, unidirectional
  1'b0, // LS_REF, VDS_OCP is measured from SHx to SNx
  2'b10, // CSA_GAIN, 20V/V
  1'b0, // DIS_SEN overcurrent fault enabled
  1'b0, // CSA_CAL_A, normal operation
  1'b0, // CSA_CAL_B, normal operation
  1'b0, // CSA_CAL_C, normal operation
  2'b11, // SEN_LVL, OCP 1 V
};

reg [3:0] cur_bit;
wire [4:0] config_bits;
wire config_bit;

assign config_bits[0] = driver_control[cur_bit];
assign config_bits[1] = hs_control[cur_bit];
assign config_bits[2] = ls_control[cur_bit];
assign config_bits[3] =
  ocp_control[cur_bit];
assign config_bits[4] =
  csa_control[cur_bit];

endmodule