module PWM(clk,up,down,clk_count);
input clk, up, down;
output clk_count;
wire up;
wire down;
reg [7:0] clk_count;
reg clk_tick;
parameter clk_ding = 195; //50000000/1000/256 精度不是很够!!! 195.3125
always @(posedge clk) clk_tick <= (clk_count == clk_ding-1 );
always @(posedge clk)
begin
if (clk_tick)
clk_count <= 0;
else
clk_count = clk_count+1;
end
reg [12:0] pulse_count;
reg [9:0] pulse ;
reg R_pulse;
always @(posedge clk)
begin
if (pulse_count == 5120) // 20*256
pulse_count <= 0;
else if(clk_tick)
pulse_count = pulse_count+1; //all crycl
end
initial pulse = 400; // 尝试建立最小单位看看如何
always @(posedge clk)
begin
if (up)
pulse = pulse +20;
else if(down)
pulse = pulse -20;
end
always @(posedge clk)
begin
if(pulse_count == 0)
R_pulse <= 1;
else if (pulse_count > pulse)
R_pulse <= 0;
end
endmodule