module uart_tx( input clk, input rst_n, output reg tx, input [7:0] data, input tx_en, output tx_done, input [3:0] DataLen_wire, input isParity_wire, input ParityMode_wire ); reg busy; //线路状态指示,高为线路忙,低为线路空闲 reg send; reg wrsigbuf; reg wrsigrise; reg presult; reg [7:0] cnt; reg [3:0] DataLen = 4'd8; reg isParity = 1'b0; reg paritymode = 1'b0; reg [3:0] dataN_send = 4'd0; //记录当前将要发送的数据(亦即已发送的数据位个数) always @(negedge rst_n) begin //在rst拉低时配置数据位长度、是否使用校验位、奇偶校验 DataLen <= DataLen_wire; isParity <= isParity_wire; paritymode <= ParityMode_wire; end //检测上升沿 always @(posedge clk) begin wrsigbuf <= tx_en; wrsigrise <= (~wrsigbuf) & tx_en; end //发送结束信号 assign tx_done = ~busy; //启动串口发送程序 always @(posedge clk) begin if(wrsigrise && (~busy)) begin //当发送命令有效且线路为空闲时,启动新的数据发送 send <= 1'b1; end else if(cnt==((DataLen+2+isParity)<<4)-4) begin send <= 1'b0; end end //串口发送程序,16个时钟发送一个bit always @(posedge clk or negedge rst_n) begin if(!rst_n) begin tx <= 1'b1; busy <= 1'b0; cnt <= 8'd0; presult <= 1'b0; dataN_send <= 4'd0; end else if(send==1'b1) begin if(cnt==8'd0) begin tx <= 1'b0; //产生起始位 dataN_send <= 4'd0; presult <= paritymode; busy <= 1'b1; cnt <= cnt + 8'd1; end else if(cnt==(dataN_send+1)<<4 && dataN_send<DataLen) begin tx <= data[dataN_send]; //发送数据位 小端 presult <= data[dataN_send]^presult; busy <= 1'b1; cnt <= cnt + 8'd1; dataN_send <= dataN_send+1; end else if(cnt==(DataLen+1)<<4) begin if(isParity)begin tx <= presult; //发送奇偶校验位 busy <= 1'b1; cnt <= cnt + 8'd1; end else begin tx <= 1'b1; //发送停止位 busy <= 1'b1; cnt <= cnt + 8'd1; end end else if(cnt==((DataLen+2)<<4)-4) begin if(isParity) begin tx <= 1'b1; //发送停止位 busy <= 1'b1; cnt <= cnt + 8'd1; end else begin tx <= 1'b1; busy <= 1'b0; cnt <= cnt + 8'd1; end end else if(cnt==((DataLen+3)<<4)-4) begin tx <= 1'b1; busy <= 1'b0; cnt <= cnt + 8'd1; end else begin cnt <= cnt + 8'd1; end end else begin tx <= 1'b1; cnt <= 8'd0; busy <= 1'b0; end end endmodule
时间: 2024-02-26 09:51:44 浏览: 16
这是一个串口发送模块的Verilog代码,它可以将输入的数据通过串口发送出去。它支持配置数据位长度、是否使用校验位、奇偶校验等功能。该模块的工作原理是在clk的上升沿检测发送命令信号tx_en,如果该信号为有效且线路为空闲,就启动新的数据发送。在发送过程中,每16个时钟发送一个bit,包括起始位、数据位、校验位和停止位。发送完毕后,会发出tx_done信号。