一、 程序说明
FPGA通过串口定时发送数据,每秒发送1字节,数据不断自增
参考小梅哥教程
二、 uart_tx.v
`timescale 1ns / 1ps
module uart_tx(
input wire sclk,
input wire rst_n,
output reg uart_tx
);
parameter CLK_FREQ = 50000000; //时钟频率50M
parameter UART_BAUD = 115200; //时钟频率50M
parameter MAX_BIT_COUNT = 9; //时钟频率50M
localparam MAX_BAUD_CNT = CLK_FREQ / UART_BAUD;//434
reg [7:0] write_data; //发送数据
//运行计数器
reg [31:0] run_cnt; //波特率计数器
always @(posedge sclk or negedge rst_n)
begin
if(rst_n == 1'b0)
run_cnt <= 32'd0;
else if(run_cnt == CLK_FREQ)
run_cnt <= 0;
else
run_cnt <= run_cnt + 1;
end
//波特率计数器
reg [8:0] baud_cnt; //波特率计数器
reg en_baud_cnt; //波特率计数器开关
always @(posedge sclk or negedge rst_n)
begin
if(rst_n == 1'b0)
baud_cnt <= 8'd0;
else if(en_baud_cnt == 1'b1) begin
if(baud_cnt == MAX_BAUD_CNT)
baud_cnt <= 8'd0;
else
baud_cnt <= baud_cnt + 1;
end
else
baud_cnt <= baud_cnt;
end
//发送位计数器
reg [4:0] bit_cnt = 0; //波特率计数器
always @(posedge sclk or negedge rst_n)
begin
if(rst_n == 1'b0)
bit_cnt <= 4'd0;
else if(baud_cnt == MAX_BAUD_CNT)
begin
if(bit_cnt == MAX_BIT_COUNT)
bit_cnt <= 4'd0;
else
bit_cnt <= bit_cnt + 1;
end
else
bit_cnt <= bit_cnt;
end
//位发送逻辑
always @(posedge sclk or negedge rst_n)
begin
if(rst_n == 1'b0)
uart_tx <= 1'b0;
else if(baud_cnt == MAX_BAUD_CNT/2)
begin
if(bit_cnt == 0)
uart_tx <= 1'b0;
else if(bit_cnt == MAX_BIT_COUNT)
uart_tx <= 1'b1;
else
begin
case(bit_cnt)
1:uart_tx <= write_data[0];
2:uart_tx <= write_data[1];
3:uart_tx <= write_data[2];
4:uart_tx <= write_data[3];
5:uart_tx <= write_data[4];
6:uart_tx <= write_data[5];
7:uart_tx <= write_data[6];
8:uart_tx <= write_data[7];
default:uart_tx <= uart_tx;
endcase
end
//uart_tx <= write_data[bit_cnt-1];
end
else
uart_tx <= uart_tx;
end
always @(posedge sclk or negedge rst_n)
begin
if(rst_n == 1'b0)
en_baud_cnt <= 1'b0;
else if(run_cnt == 0) begin
en_baud_cnt <= 1'b1;
end
else if(bit_cnt == MAX_BIT_COUNT && baud_cnt == MAX_BAUD_CNT)
en_baud_cnt <= 1'b0;
else
en_baud_cnt <= en_baud_cnt;
end
always @(posedge sclk or negedge rst_n)
begin
if(rst_n == 1'b0)
write_data <= 8'd0;
else if(run_cnt == 0)
write_data <= write_data + 1;
else
write_data <= write_data;
end
endmodule