Verilog-并转串(2017兆易创新)

1、原题

 

 2、代码

`timescale 1ns / 1ps

module my_transmitter(
    input clk, //Clock
    input rst_n, //Asynchronous reset(active low)
    input [1:0] gap, //the stop interval lasts (gap+1)cycles
    input [3:0] din, //4-bit parallel dada input
    output dout //Serial data output
    );
parameter START = 2'b01;
parameter TRANS = 2'b10;
parameter STOP = 2'b11;

reg [1:0] state;
reg [1:0] next_state;

reg dout_reg;
reg [1:0] bit_count;


wire [2:0] stop_interval;
reg [2:0] stop_count;
 
always @(posedge clk or negedge rst_n) begin
    if(!rst_n) state <= START;
    else state <= next_state;
end

always @(*) begin
    case(state)
        START:next_state=TRANS;
        TRANS:
        begin
            if(bit_count == 2'd3) next_state = STOP;
            else next_state = TRANS;
        end
        STOP:
        begin
            if(stop_count == stop_interval) next_state = START;
            else next_state = STOP;
        end
        default: next_state = START;
    
    endcase
end

always @(*) begin
    case(state)
        START:dout_reg = 1'b0;
        TRANS:dout_reg = din[bit_count];
        STOP:dout_reg = 1'b1;
        default:dout_reg = 1'b0;
    endcase
end
assign dout = dout_reg;

always @(posedge clk or negedge rst_n) begin
    if(!rst_n) bit_count <= 2'd0;
    else begin
        if(state == TRANS) bit_count <= bit_count + 1'b1;
        else if(state == STOP) bit_count <= 2'd0;
        else bit_count <= bit_count;
    end
end

assign stop_interval = gap;

always @(posedge clk or negedge rst_n) begin
    if(!rst_n) stop_count <= 3'd0;
    else begin
        if(state == STOP) stop_count <= stop_count + 1'b1;
        else if(state == START) stop_count <= 3'd0;
        else stop_count <= stop_count;
    end
end

endmodule

3、测试

(1)激励

  

`timescale 1ns / 1ps

module my_transmitter_tb;

    // Inputs
    reg clk;
    reg rst_n;
    reg [1:0] gap;
    reg [3:0] din;

    // Outputs
    wire dout;
    
    integer i;

    // Instantiate the Unit Under Test (UUT)
    my_transmitter uut (
        .clk(clk), 
        .rst_n(rst_n), 
        .gap(gap), 
        .din(din), 
        .dout(dout)
    );

    initial begin
        // Initialize Inputs
        clk = 0;
        rst_n = 0;
        gap = 0;
        din = 0;
        i = 0;

        // Wait 100 ns for global reset to finish
        #100;
        @(negedge clk);
        rst_n = 1;
        din = 4'b1001;
        gap = 3;
        
        for(i=0;i<(5+gap+1);i=i+1) begin
            @(posedge clk);
        end
        
        @(negedge clk);
        din = 4'd1010;
        gap = 1;

        for(i=0;i<(5+gap+1);i=i+1) begin
            @(posedge clk);
        end    

        @(negedge clk);
        din = 4'd0110;
        gap = 2;
        
        
        // Add stimulus here

    end
    
    always #20 clk = ~clk;
      
endmodule

  (2)波形

  

原文地址:https://www.cnblogs.com/wt-seu/p/12500517.html