module SRF_Control(sys_clk,sys_rst_n,echo,Distance,Trig);//《基于FPGA的数字系统设计与研究》
input sys_clk;
input sys_rst_n;
input echo;
output[13:0] Distance;
output Trig;
reg Trig;
reg[31:0] Distance_r;
assign Distance = Distance_r/2941;//calculate and output ultrasonic obstacle distance value
reg[3:0] State;
reg[31:0] Trig_cnt;
reg[31:0] Timeout_cnt;
reg[31:0] echo_cnt;
reg echo_r;
always@(posedge sys_clk or negedge sys_rst_n)
begin
if(!sys_rst_n)
echo_r <= 1'b0;
else
echo_r <= echo;
end
always@(posedge sys_clk or negedge sys_rst_n)
begin
if(!sys_rst_n)
begin
State <= 4'd0 ;
Trig <= 1'b0;
Trig_cnt <= 32'd0 ;
echo_cnt <= 32'd0 ;
Distance_r <= 32'd0 ;
Timeout_cnt <= 32'd0;
end
else
begin
case(State)
4'd0: begin
Trig <= 1'b0;
Trig_cnt <= 32'd0;
echo_cnt <= 32'd0;
Timeout_cnt <= 32'd0;
State <= 4'd1;
end
4'd1: begin
Trig <= 1'b1;
if(Trig_cnt==32'd500000)begin
Trig_cnt <= 32'd0;
State <= 4'd2;
end
else begin
Trig_cnt <= Trig_cnt+1;
State <= 4'd1;
end
end
4'd2: begin
Trig <= 1'b0;
if(Trig_cnt == 32'd500)begin
Trig_cnt <= 32'd0;
State <= 4'd3;
end
else begin
Trig_cnt <= Trig_cnt+1;
State <= 4'd2;
end
end
4'd3: begin
if(!echo_r)
State <= 4'd4;
else
State <= 4'd3;
end
4'd4: begin
if(!echo_r) State <= 4'd5;
else if(Timeout_cnt == 32'd50000000)begin
Timeout_cnt <= 0;
State <= 4'd0; end
else begin
Timeout_cnt <= Timeout_cnt+1;
State <= 4'd4; end
end
4'd5: begin
if(!echo_r) State <= 4'd6;
else begin
echo_cnt <= echo_cnt+1;
State <= 4'd5;
end
end
4'd6: begin
Distance_r <= echo_cnt;
if(Timeout_cnt == 32'd50000000) begin
Timeout_cnt <= 0;
State <= 4'd0; end
else begin Timeout_cnt <= Timeout_cnt+1;
State <= 4'd6; end
State <= 4'd0;
end
default: State <= 4'd0;
endcase
end
end
endmodule |