See also: Serial receiver and datapath
We want to add parity checking to the serial receiver. Parity checking adds one extra bit after each data byte. We will use odd parity, where the number of 1s in the 9 bits received must be odd. For example, 101001011 satisfies odd parity (there are 5 1s), but 001001011 does not.
Change your FSM and datapath to perform odd parity checking. Assert the done signal only if a byte is correctly received and its parity check passes. Like the serial receiver FSM, this FSM needs to identify the start bit, wait for all 9 (data and parity) bits, then verify that the stop bit was correct. If the stop bit does not appear when expected, the FSM must wait until it finds a stop bit before attempting to receive the next byte.
You are provided with the following module that can be used to calculate the parity of the input stream (It's a TFF with reset). The intended use is that it should be given the input bit stream, and reset at appropriate times so it counts the number of 1 bits in each byte.
module parity ( input clk, input reset, input in, output reg odd); always @(posedge clk) if (reset) odd <= 0; else if (in) odd <= ~odd; endmodule
Note that the serial protocol sends the least significant bit first, and the parity bit after the 8 data bits.
- module top_module(
- input clk,
- input in,
- input reset, // Synchronous reset
- output [7:0] out_byte,
- output done
- ); //
- reg [3:0] state,next;
- reg odd;
- //0:还没接到起始位,1:接到起始位,...,9:接到最后一个数据位,10:接到奇偶校验位,11:接到终止位,12:没接到终止位
- wire res;
- always@(*) begin
- case(state)
- 0:next<=in?0:1;
- 1:next<=2;
- 2:next<=3;
- 3:next<=4;
- 4:next<=5;
- 5:next<=6;
- 6:next<=7;
- 7:next<=8;
- 8:next<=9;
- 9:next<=10;
- 10:next<=in?11:12;
- 11:next<=in?0:1;
- //接到终止位后接到0即开始位,那就直接跳到1
- 12:next<=in?0:12;
- //判断是否接到终止位。这里是设置了两种终止位状态来判断是否done
- endcase
- end
-
- always@(posedge clk) begin
- if(reset)
- state<=0;
- else
- state<=next;
- end
-
- parity p1(clk, res, in, odd);
-
- assign done=(state==11&&(!odd));
- // Use FSM from Fsm_serial
- always@(posedge clk) begin
- case(state)
- 1:out_byte[0]<=in;
- 2:out_byte[1]<=in;
- 3:out_byte[2]<=in;
- 4:out_byte[3]<=in;
- 5:out_byte[4]<=in;
- 6:out_byte[5]<=in;
- 7:out_byte[6]<=in;
- 8:out_byte[7]<=in;
- endcase
- end
-
- always@(*) begin
- if(state==11||state==0)
- res<=1;
- else
- res<=0;
- end
-
- endmodule