串口接收模块 5倍速率采样

`timescale 1ns / 1ps


// Company: 
// Engineer:
//
// Create Date:   18:27:37 05/06/2015
// Design Name:   uartRxDemo
// Module Name:   E:/Xilinx/lesson4/uart_tb.v
// Project Name:  lesson4
// Target Device:  
// Tool versions:  
// Description: 
//
// Verilog Test Fixture created by ISE for module: uartRxDemo
//
// Dependencies:
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 


module uart_tb;

	// Inputs
	reg clk5x;
	reg rst;
	reg Rx;

	// Outputs
	wire en;
	wire [7:0] data;

	// Instantiate the Unit Under Test (UUT)
	uartRxDemo uut (
		.clk5x(clk5x), 
		.rst(rst), 
		.Rx(Rx), 
		.en(en), 
		.data(data)
	);

	initial begin
		// Initialize Inputs
		clk5x = 0;
		rst = 1;
		

		// Wait 100 ns for global reset to finish
		#100;
        
		// Add stimulus here
		
		#10;
		rst=0;
		forever #1 clk5x=~clk5x;

	end
	
	
	
	initial
      begin
		Rx = 1;
		#110;
		Rx=0;
		#10;
		Rx=1;
		#20;
		Rx=0;
		#20;
		Rx=1;
		#10;
		Rx=0;
		#10;
		Rx=1;
		#20;
		
		#10;//停止位
		Rx=0;
		
		#10;//起始位
		Rx=1;//1101 0001
		
		#20;
		Rx=0;
		#10;
		Rx=1;
		#10;
		Rx=0;
		#30;
		Rx=1;
		#10;
		Rx=1;
		#20;
		end
		
		initial
		begin
		#400 $finish;
		end
endmodule


module uartRxDemo(
input clk5x,
input rst,
input Rx,
output reg en,
output reg [7:0]data

);

parameter s_sniffer=0,s_receive=1;

reg state,nextState;
reg receiving,finishing;
reg [3:0] highSpeedShifter;
reg [6:0] lowSpeedShifter;
reg [2:0] sampleCounter,nextSampleCounter;
reg [2:0] bitCounter,nextBitCounter;

always@(posedge clk5x)
begin
	if(rst==1'b1)
	begin
		state<=s_sniffer;
		sampleCounter<=3'b0;
		bitCounter<=3'b0;
		highSpeedShifter<=4'b1111;
		lowSpeedShifter<=7'b0;
		en<=1'b0;
		data<=8'b0;
	end
	else
	begin
		state<=nextState;
		sampleCounter<=nextSampleCounter;
		bitCounter<=nextBitCounter;
		highSpeedShifter<={highSpeedShifter[2:0],Rx};
		if(receiving==1'b1&&sampleCounter==3'd4)
		begin
			lowSpeedShifter<={lowSpeedShifter[5:0],highSpeedShifter[1]};
		end
		
		en<=finishing;
		
		if(finishing==1'b1)
		begin
			data<={lowSpeedShifter,highSpeedShifter[1]};
		end
	end
end

always@(state,highSpeedShifter,sampleCounter,bitCounter)
begin
	nextSampleCounter=3'b0;
	nextBitCounter=3'b0;
	receiving=1'b0;
	finishing=1'b0;
	case(state)
	s_sniffer:
	begin
		if(highSpeedShifter==4'b0)
		begin
			nextState=s_receive;
		end
		else
		begin
			nextState=s_sniffer;
		end
	end
	
	s_receive:
	begin
		receiving=1'b1;
		if(sampleCounter==3'd4)
		begin
			nextSampleCounter=3'b0;
			nextBitCounter=bitCounter+1'b1;
		end
		else
		begin
			nextSampleCounter=sampleCounter+1'b1;
			nextBitCounter=bitCounter;
		end
		
		
		if(bitCounter==3'd7&&sampleCounter==3'd4)
		begin
			finishing=1'b1;
			nextState=s_sniffer;
		end
		else
		begin
			nextState=s_receive;
		end
	end
	
	default:
	begin
		nextState=s_sniffer;
	end
  endcase
end

endmodule


你可能感兴趣的:(FPGA)