Files
CGA-bench/data/myproject/spi_controller_clean.jsonl

2 lines
8.7 KiB
Plaintext
Raw Normal View History

2026-05-22 10:02:42 +08:00
{"task_id": "spi_controller", "task_number": 1, "description": "Single-byte SPI master controller. On start, latch data_in, assert busy, idle spi_clk at cpol, shift out MSB-first on mosi, and shift in miso into data_out. When cpha=0, sample on the first active edge; when cpha=1, sample on the second edge. After 8 bits, deassert busy and return to IDLE with spi_clk back at cpol. If start is asserted while a transfer is already in progress, enter a recoverable ERROR state and then return to IDLE.", "header": "module spi_controller (\n input clk,\n input rst_n,\n input [7:0] data_in,\n input start,\n input cpol,\n input cpha,\n output reg [7:0] data_out,\n output reg busy,\n output reg spi_clk,\n output reg mosi,\n input miso\n);", "module_code": "`timescale 1ns/1ps\n\nmodule spi_controller (\n input clk,\n input rst_n,\n input [7:0] data_in,\n input start,\n input cpol,\n input cpha,\n output reg [7:0] data_out,\n output reg busy,\n output reg spi_clk,\n output reg mosi,\n input miso\n);\n localparam IDLE = 3'd0;\n localparam LOAD = 3'd1;\n localparam LEAD = 3'd2;\n localparam SAMPLE = 3'd3;\n localparam SHIFT = 3'd4;\n localparam DONE = 3'd5;\n localparam ERROR = 3'd6;\n\n reg [2:0] state;\n reg [2:0] bit_count;\n reg [7:0] tx_shift;\n reg [7:0] rx_shift;\n\n always @(posedge clk or negedge rst_n) begin\n if (!rst_n) begin\n state <= IDLE;\n bit_count <= 3'd0;\n tx_shift <= 8'd0;\n rx_shift <= 8'd0;\n data_out <= 8'd0;\n busy <= 1'b0;\n spi_clk <= 1'b0;\n mosi <= 1'b0;\n end else begin\n case (state)\n IDLE: begin\n busy <= 1'b0;\n spi_clk <= cpol;\n mosi <= 1'b0;\n if (start) begin\n busy <= 1'b1;\n bit_count <= 3'd7;\n tx_shift <= data_in;\n rx_shift <= 8'd0;\n state <= LOAD;\n end\n end\n\n LOAD: begin\n busy <= 1'b1;\n spi_clk <= cpol;\n mosi <= tx_shift[7];\n if (start) begin\n state <= ERROR;\n end else begin\n state <= LEAD;\n end\n end\n\n LEAD: begin\n busy <= 1'b1;\n spi_clk <= ~cpol;\n if (start) begin\n state <= ERROR;\n end else if (!cpha) begin\n rx_shift <= {rx_shift[6:0], miso};\n if (bit_count == 3'd0) begin\n data_out <= {rx_shift[6:0], miso};\n state <= DONE;\n end else begin\n state <= SHIFT;\n end\n end else begin\n state <= SAMPLE;\n end\n end\n\n SAMPLE: begin\n busy <= 1'b1;\n spi_clk <= ~cpol;\n if (start) begin\n state <= ERROR;\n end else begin\n rx_shift <= {rx_shift[6:0], miso};\n if (bit_count == 3'd0) begin\n data_out <= {rx_shift[6:0], miso};\n state <= DONE;\n end else begin\n state <= SHIFT;\n end\n end\n end\n\n SHIFT: begin\n busy <= 1'b1;\n spi_clk <= cpol;\n tx_shift <= {tx_shift[6:0], 1'b0};\n bit_count <= bit_count - 1'b1;\n mosi <= tx_shift[6];\n