Fine tuning SPI.
authorNicolas 'Pixel' Noble <nicolas@nobis-crew.org>
Sun, 14 Oct 2018 06:57:09 +0000 (23:57 -0700)
committerNicolas 'Pixel' Noble <nicolas@nobis-crew.org>
Sun, 14 Oct 2018 06:57:09 +0000 (23:57 -0700)
spi.v

diff --git a/spi.v b/spi.v
index 2c7b9bee5bf841397ef65dd3bae6bc218618a601..9a0b4e8bb82ddd0b669cc54d7823fae34b608b03 100644 (file)
--- a/spi.v
+++ b/spi.v
@@ -1,3 +1,5 @@
+`timescale 1us / 10ns
+
 module master_spi
 #(
   parameter WIDTH = 8,
@@ -33,7 +35,7 @@ input miso;
 output reg ssel = 1;
 input [WIDTH-1:0] din;
 output [WIDTH-1:0] dout;
-output reg done;
+output reg done = 0;
 input r;
 input s;
 
@@ -41,7 +43,8 @@ reg started = 0;
 reg [log2(WIDTH):0] counter;
 reg [WIDTH-1:0] sp_in = 0;
 reg [WIDTH-1:0] sp_out = 0;
-reg [1:0] cooldown = CPHA;
+reg cooldown = CPHA;
+reg delay = CPHA;
 
 assign dout = sp_out;
 assign mosi = sp_in[LITTLE_ENDIAN ? 0 : WIDTH-1];
@@ -53,24 +56,28 @@ always @(posedge clk) begin
     done <= 0;
     sclk <= CPOL;
     ssel <= 1;
+    delay <= CPHA;
   end else if (started) begin
     if (counter == 0) begin
       if (sclk != CPOL) sclk <= ~sclk;
-      if (cooldown == 3) begin
+      if (cooldown) begin
         done <= 1;
+        ssel <= 1;
       end else begin
-        cooldown <= cooldown + 1;
-        if (cooldown == 2) ssel <= 1;
+        cooldown <= 1;
       end
-    end else if (sclk == (CPOL ^ CPHA)) begin // read cycle
+    end else if (!delay && sclk == (CPOL ^ CPHA)) begin // read cycle
       if (LITTLE_ENDIAN) sp_out <= { miso, sp_out[WIDTH-1:1] };
       else sp_out <= (sp_out << 1) | miso;
       counter <= counter - 1;
       sclk <= ~sclk;
-    end else begin // write cycle
+    end else if (!delay) begin // write cycle
       if (LITTLE_ENDIAN) sp_in <= sp_in >> 1;
       else sp_in <= sp_in << 1;
       sclk <= ~sclk;
+    end else if (delay) begin
+      delay <= delay - 1;
+      sclk <= ~sclk;
     end
   end else if (s) begin
     sp_in <= din;