Jim:
I pulled your code from above and built a simple simulation. It appeared to be just fine. I surmised that you were using
clock directly from a 6502, which means that the
load signal would be asserted when
clock goes low and deassert when
clock returns high. Therefore, I complemented the polarity of
sck, and the clock edges used in your code because I suspect that you may be having a race condition on your
load pulse. The figure below is a simulation of your code with those simple changes. It shows a
load pulse with a pulse width equal to 1/2 clock, and the transmission of two bytes: 0xA5 and 0xC3. In the simulation, I wired
miso to be the complement of
mosi. After transmission, the
q register correctly shows the expected receive values: 0x5A and 0x3C. I've also attached the code for the module as I modified it and the corresponding simulation. Hope this helps.
Attachment:
File comment: Simulation of simple SPI module.
brain_spi.JPG [ 82.73 KiB | Viewed 1240 times ]
Code:
`timescale 1ns / 1ps
module spi(
input reset,
input clock,
input load,
input [7:0] d,
output ss,
output sck,
output mosi,
input miso,
output reg [7:0] q
);
reg in;
reg [3:0] i;
wire run;
assign ss = !(run);
assign mosi = q[7];
assign run = (!i[3]);
assign sck = ~clock & !ss;
always @(negedge clock)
begin
in <= #1 miso;
end
always @(posedge clock or posedge reset)
begin
if(reset) begin
q <= #1 0;
i <= #1 8;
end else if(load) begin
q <= #1 d;
i <= #1 0;
end else if(run) begin
i <= #1 i + 1;
q <= #1 {q[6:0], in};
end
end
endmodule
Code:
`timescale 1ns / 1ps
////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 08:13:54 02/20/2016
// Design Name: spi
// Module Name: C:/XProjects/ISE10.1i/Work/Src/tb_brain_spi.v
// Project Name: Work
// Target Device:
// Tool versions:
// Description:
//
// Verilog Test Fixture created by ISE for module: spi
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
////////////////////////////////////////////////////////////////////////////////
module tb_brain_spi;
// Inputs
reg reset;
reg clock;
reg load;
reg [7:0] d;
wire miso;
// Outputs
wire ss;
wire sck;
wire mosi;
wire [7:0] q;
// Instantiate the Unit Under Test (UUT)
spi uut (
.reset(reset),
.clock(clock),
.load(load),
.d(d),
.ss(ss),
.sck(sck),
.mosi(mosi),
.miso(miso),
.q(q)
);
initial begin
// Initialize Inputs
reset = 1;
clock = 1;
load = 0;
d = 0;
// miso = 0;
// Wait 100 ns for global reset to finish
#101 reset = 0;
// Add stimulus here
@(negedge clock) #1;
@(negedge clock) #1;
@(negedge clock) #1 load = 1; d = 8'hA5;
@(posedge clock) #1 load = 0; d = 8'h00;
@(posedge ss);
@(negedge clock) #1;
@(negedge clock) #1;
@(negedge clock) #1 load = 1; d = 8'hC3;
@(posedge clock) #1 load = 0; d = 8'h00;
end
always #5 clock = ~clock;
assign miso = ~q[7];
endmodule