*********提取有效数据位并按串行通讯格式装载数据********
always@ (posedge nclk or posedge rst) begin
if(rst)
begin
state<=0;
counter<=0;
tag1=0;
tag="0";
indata_buf<=8'bz;
dout_buf<=10'bz;
bitpos="7";
cnt3<=0;
end
else case(state)
s0:begin
tag="0";//表示数据没有装好
if(din)
begin
counter<=counter+1;
state<=s0;
if(counter==15)//如果检测到16个1则转入s1状态检测接下来的是不是0
begin
state<=s1;
counter<=0;
end
end
else begin
counter<=0;
state<=s0;
end
end
s1:if(!din)//如果是0的话,转入s2状态,提取八位有效数据
state<=s2;
else //否则转到s0状态重新检测
state<=s0;
s2:if(cnt3==3)//是否采集四次数据
begin
cnt2<=0;
indata_buf[bitpos]<=din; //先进来的是高位数据
bitpos="bitpos-1";
if(bitpos==-1)
begin
bitpos=7;state<=s3;end
end
else cnt3<=cnt3+1;
s3:begin
tag1=tag;
tag=1'b1; //标志输入寄存器满。表明已把有用数据装入寄存器
if(tag&&~tag1)&&txdone) //检测到tag的上升沿以及txdone为高才把输入缓冲数据放到输出缓冲去
dout_buf<={1'b1,indata_buf[7:0],1'b0};//停止位,高位,低位,起始位
state<=s0;
end
endcase
end
//***********发送数据模块
reg[3:0] state_tx=0;
always@(posedge txclk or posedge rst)
begin
if(rst)
begin
dout_ser<=1'bz;
state_tx<=0;
txdone=1;
end
else
case(state_tx)