//产生echo控制信号250*8000*50ns,echo高电平持续12.5us,即250个时钟周期
always@(posedge iclk)
begin
if(cnt == 249)
cnt <= 1'b0;
else
cnt <= cnt +1;
end
always@(posedge iclk)
begin
if(cnt == 249)
if(cnt1 == 7999)
begin
trig <= 1'b1;
cnt1 <= 1'b0;
end
else
begin
trig <= 1'b0;
cnt1 <= cnt1 + 1'b1;
end
end
//捕捉trig上升沿与下降沿,并产生标志位
always@(posedge iclk)
begin
echo_buf <= echo;
echo_rising <= echo & (~echo_buf);
echo_falling <= (~echo) & echo_buf;
end
always@(posedge iclk)
begin
if(echo_rising == 1'b1)
begin
flag1 = 1'b1; //echo已经变为高电平
end
else if(echo_falling == 1'b1)
begin
flag1 = 1'b0; //echo已经变为低电平
end
end
//在flag1 = 1 期间计时,即对时钟进行计数。(4m的距离会是25ms,1mm是125个时钟周期)
always@(posedge iclk)
begin
if(flag1 == 1'b1)
begin
if(cnt3 == 124) //1mm
cnt3 <= 1'b0;
else
cnt3 <= cnt3 + 1'b1;
end
else if(echo_rising == 1'b1)
cnt3 <= 1'b0;
end
always@(posedge iclk)
begin
if(flag1 == 1'b1)
begin
if(cnt3 == 124)
if(data1 == 9) //1cm
data1 <= 4'd0;
else
data1 <= data1 + 1'b1;
end
else if(echo_rising == 1'b1)
data1 <= 1'b0;
end
always@(posedge iclk)
begin
if(flag1 == 1'b1)
begin
if(data1 == 9 && cnt3 == 124)
if(data2 == 9) //1dm
data2 <= 1'b0;
else
data2 <= data2 + 1'b1;
end
else if(echo_rising == 1'b1)
data2 <= 1'b0;
end
always@(posedge iclk)
begin
if(flag1 == 1'b1)
begin
if(data2 == 9 && data1 == 9 && cnt3 == 124)
if(data3 == 9) //1m
data3 <= 1'b0;
else
data3 <= data3 + 1'b1;
end
else if(echo_rising == 1'b1)
data3 <= 1'b0;
end
//产生显示用的时钟信号
always@(posedge iclk)
begin
if(cnt5 == 5)
begin
clk = ~clk;
cnt5 = 1'b0;
end
else
cnt5 = cnt5 + 1'b1;
end
//00-11为一个周期,每个周期点亮一个数码管
always@(posedge clk)
begin
cnt4 = cnt4 + 1'b1;
end
//我的板上共有6个数码管,让其中4个数码管显示四位数字,单位是毫米。
always@(posedge clk)
begin
if(flag1 == 1'b0)
case(cnt4)
2'b00:
begin
data7 = dis[data1];
data6 = 6'b111110;
end
2'b01:
begin
data7 = dis[data2];
data6 = 6'b111101;
end
2'b10:
begin
data7 = dis[data3];
data6 = 6'b111011;
end
2'b11:
begin
data7 = dis[data4];
data6 = 6'b110111;
end
default: ;
endcase
else
begin
data7 = dis[0];
data6 = 6'b110000;
end
end