There have been a few questions about this lately. The following code receives a character over an RS-232 connection. It's been tested and verified using Xilinx PFGA. For those who have this as an assignment, no cheating and just copying my code! But I'll be happy to discuss it and how/why it works. Use the following settings in your terminal program:
Baud : 9600
Data Bits : 8
Parity : None
Stop Bits : 1
Flow Control : None
Code:
Baud : 9600
Data Bits : 8
Parity : None
Stop Bits : 1
Flow Control : None
Code:
Code:
module loopback
(clock,
reset,
RS232_DCE_RXD,
RS232_DCE_TXD,
receive_data);
input clock;
input reset;
input RS232_DCE_RXD;
output RS232_DCE_TXD;
output [7:0] receive_data;
parameter rcv_bit_per = 5208; //102.4uS
parameter half_rcv_bit_per = 2604; //51.2uS
//--State Definitions--
parameter ready = 2'b00;
parameter start_bit = 2'b01;
parameter data_bits = 2'b10;
parameter stop_bit = 2'b11;
reg [12:0] counter, n_counter; //9765.625Hz
reg [3:0] data_bit_count, n_data_bit_count;
reg [7:0] rcv_sr, n_rcv_sr;
reg [1:0] state, n_state;
assign RS232_DCE_TXD = RS232_DCE_RXD;
assign receive_data = rcv_sr;
always @(state, RS232_DCE_RXD, counter, data_bit_count) begin
n_rcv_sr <= rcv_sr;
n_counter <= counter;
n_state <= state;
n_data_bit_count <= data_bit_count;
case (state)
ready: begin
if(RS232_DCE_RXD == 0) begin
n_state <= start_bit;
n_counter <= counter + 1;
end
else begin
n_state <= ready;
n_counter <= 0;
n_data_bit_count <= 0;
end
end
start_bit: begin
if(counter == half_rcv_bit_per) begin
n_state <= data_bits;
n_data_bit_count <= data_bit_count + 1;
n_counter <= 0;
end
else begin
n_state <= start_bit;
n_counter <= counter + 1;
end
end
data_bits: begin
if(counter == rcv_bit_per) begin
//n_rcv_sr <= {rcv_sr[6:0], RS232_DCE_RXD};
n_rcv_sr <= {RS232_DCE_RXD,rcv_sr[7:1]};
n_data_bit_count <= data_bit_count + 1;
n_counter <= 0;
if(data_bit_count == 8)
n_state <= stop_bit;
end
else
n_counter <= counter + 1;
end
stop_bit: begin
n_counter <= counter + 1;
if(counter == rcv_bit_per) //should be 1/2 stop_bit period
n_state <= ready;
end
endcase
end //always
//clock proc
always @(posedge clock or posedge reset) begin
if(reset == 1) begin
state <= ready;
rcv_sr <= 0;
counter <= 0;
data_bit_count <= 0;
end
else begin
state <= n_state;
rcv_sr <= n_rcv_sr;
counter <= n_counter;
data_bit_count <= n_data_bit_count;
end
end
endmodule