三角波发生器用到了状态机的方法
`timescale 1ns/10ps//定义时间精度
module tri_gen(
clk,
res,
d_out
);
input clk,res;
output[8:0] d_out;
reg[8:0] d_out;
reg[1:0] state;//存放状态机的状态
reg[8:0] con;//三角波设置了一个平顶,con用于评定状态的计数
always@(posedge clk or negedge res) begin
if(~res) begin
state<=0;
d_out<=0;
con<=0;
end
else begin
case(state)
0:begin//状态0:三角波的上升过程
d_out<=d_out+1;
if(d_out==299) begin
state<=1;//d_out等于299后三角波到达顶端,进入下一状态
end
end
1:begin
if(con==200) begin
state<=2;//con计数至200时,跳转至状态2
con<=0;
end
else begin
con<=con+1;
end
end
2:begin//三角波的下降沿
d_out<=d_out-1;
if(d_out==1) begin
state<=0;
end
end
default begin
state<=0;
con<=0;
end
endcase
end
end
endmodule
//三角波的测试平台
module tri_gen_tb;
reg clk,res;
wire[8:0] d_out;
tri_gen U1(
.clk(clk),
.res(res),
.d_out(d_out)
);
initial begin//三角波发生器没什么输入,
clk<=0;res<=0;
#17 res<=1;
#20000 $stop;
end
always #5 clk<=~clk;
endmodule
仿真结果