2. 接收模塊 (uart_rx):
module uart_rx (
clk_40k, //clock signal, 40kHz
rst_n, //reset signal, active low
bit_in, //the input serial bit,
dout_vld,//the output valid signal, active high,the dout is valid when this signal is high.
dout //received data, 8 bit width
);
input bit_in;
input clk_40k;
input rst_n;
output reg dout_vld;
output reg [7:0] dout;
reg rx_flag;
reg [6:0] cnt;
reg [5:0] rx_cnt;
reg [7:0] dout_temp;
//rx_flag: 接收過程rx_flag始終拉高
always @ (posedge clk_40k)
begin
if(~rst_n)
rx_flag <= 1'b0;
else if(bit_in == 1'b0)
rx_flag <= 1'b1;
else if(rx_cnt == 6'd9)
rx_flag <= 1'b0;
end
//cnt: 接收數(shù)據(jù)計數(shù),clk_40k分頻至1k波特率對接收數(shù)據(jù)進行計數(shù)
always @ (posedge clk_40k)
begin
if(~rst_n)
cnt <= 7'b0;
else if(rx_flag == 1'b1 && cnt != 7'd39)
cnt <= cnt + 1'b1;
else if(rx_flag == 1'b0 || cnt == 7'd39)
cnt <= 7'b0;
end
always @ (posedge clk_40k)
begin
if(~rst_n)
rx_cnt <= 6'b0;
else if(rx_flag == 1'b1 && cnt == 7'd39)
rx_cnt <= rx_cnt + 1'b1;
else if(rx_flag == 1'b0)
rx_cnt <= 6'b0;
end
//dout_temp: 將串行接收數(shù)據(jù)轉換還原為8bit數(shù)據(jù)
always @ (posedge clk_40k)
begin
if(~rst_n)
dout_temp <= 8'b0;
else if(rx_flag == 1'b1 && cnt == 7'd39)
begin
dout_temp[7] <= bit_in;
dout_temp[6:0] <= dout_temp[7:1];
end
end
//dout_vld: 傳輸完成標識,8bit數(shù)據(jù)傳輸結束拉高
always @ (posedge clk_40k)
begin
if(~rst_n)
dout_vld <= 1'b0;
else if(rx_cnt == 6'd9 && cnt == 7'b0)
begin
dout <= dout_temp;
dout_vld <= 1'b1;
end
else
dout_vld <= 1'b0;
end
endmodule
3. Testbench(tb):
`timescale 1us/1us
module tb();
reg clk_40k;
reg rst_n;
reg [7:0] din;
reg send_start;
wire bit_out;
wire bit_in;
wire dout_vld;
wire [7:0] dout;
assign bit_in = bit_out;
uart_tx i_uart_tx(
.clk_40k (clk_40k ),
.rst_n (rst_n ),
.din (din ),
.send_start (send_start),
.bit_out (bit_out )
);
uart_rx i_uart_rx(
.clk_40k (clk_40k ),
.rst_n (rst_n ),
.bit_in (bit_in ),
.dout_vld (dout_vld ),
.dout (dout )
);
initial
begin
rst_n = 1'b0;
#10
rst_n = 1'b1;
end
initial
begin
clk_40k = 1'b0;
forever
#1
clk_40k = ~clk_40k;
end
initial
begin
send_start = 1'b0;
din = 8'd0;
forever
begin
#1000
din = $random()%256;
send_start = 1'b1;
#2
send_start = 1'b0;
end
end
endmodule
4. 仿真結果 :
按照testbench對UART收發(fā)端進行仿真,仿真結果如圖:
- 系統(tǒng)時鐘和傳輸速率通常不一致,clk_40k為高頻系統(tǒng)時鐘,利用計數(shù)器分頻實現(xiàn)1k波特率;
- 復位信號rst_n低電平有效,正常傳輸時始終處于高電平。
- 開始傳輸時send_start信號拉高,傳輸結束時dout_vld信號拉高;
- 輸入數(shù)據(jù)din在傳輸結束后在輸出數(shù)據(jù)dout體現(xiàn)出來,傳輸時延為1個數(shù)據(jù)長度。
04
UART的優(yōu)缺點
4.1 UART協(xié)議優(yōu)點
- 通信只需要兩條數(shù)據(jù)線;
- 無需時鐘信號;
- 有奇偶校驗位,方便通信的差錯檢查;
- 只需要接收端和發(fā)送端設置好數(shù)據(jù)包結構,即可穩(wěn)定通信。
4.2 UART協(xié)議缺點
- 數(shù)據(jù)幀最大支持9位數(shù)據(jù);
- 不支持多主機或多從機的主從系統(tǒng)。
-
串行
+關注
關注
0文章
237瀏覽量
33769 -
uart
+關注
關注
22文章
1219瀏覽量
101120 -
通訊接口
+關注
關注
2文章
80瀏覽量
16164
發(fā)布評論請先 登錄
相關推薦
評論