串口发送模块:
TX为串口输出端口;
rdy为空闲标志,字节发送时rdy为高;
data_in为准备发送的字节;
en_data_in为字节发送使能端口,高使能;发送波特率4800,系统时钟频率24MHz。
状态规划:
Verilog代码:
`timescale 1ns/10ps
module UART_TXer(
clk,
res,
data_in,
en_data_in,
TX,
rdy
);
input clk;
input res;
input[7:0] data_in;//准备发送的数据;
input en_data_in;//发送使能;
output TX;//串口输出
output rdy;//空闲标志,0表示空闲;
reg[3:0] state;//主状态机;
//发送寄存器;右移这个寄存器,串口发送;起始位0,结束位1,中间八位数据,共10位;
reg[9:0] send_buf;
assign TX=send_buf[0];//连接TX;
reg[9:0] send_flag;//用于判断右移结束;
reg[12:0] con;//用于计算波特周期
reg rdy;
always@(posedge clk or negedge res)
if(~res)begin
state<=0;con<=0;rdy<=0;
send_buf<=1; //最低位接TX,应该是1
send_flag<=10'b10_0000_0000; //可以每四个打一个_
end
else begin
case(state)
0://等待使能信号;
begin
if(en_data_in)begin
send_buf={1'b1,data_in,1'b0};
send_flag<=10'b10_0000_0000;
rdy<=1;//要发送数据,此时不空闲
state<=1;
end
end
1://串口发送,寄存器右移;
begin
if(con==5000-1)begin
con<=0;
end
else begin
con<=con+1;
end
if(con==0)begin
send_buf[8:0]<=send_buf[9:1];//右移
send_flag[8:0]<=send_flag[9:1];
end
//数据右移的时候,标志位跟着右移,数据移动结束,标志位最低位位1;
if(send_flag[0]==1)begin
rdy<=0;//发送数据结束,空闲状态
state<=0;
end
end
endcase
end
endmodule
测试代码testbench
/*--------testbench of UART_TXer----*/
module UART_TXer_tb;
reg clk,res;
reg[7:0] data_in;
reg en_data_in;
wire TX;
wire rdy;
//同名例化
UART_TXer UART_TXer(
clk,
res,
data_in,
en_data_in,
TX,
rdy
);
initial begin
clk<=0;res<=0;data_in<=8'h0a;en_data_in<=0;
#17 res=1;
#30 en_data_in<=1;
#10 en_data_in<=0;
#1000 $stop;
end
always #5 clk<=~clk;
endmodule
运行结果: