FPGA :PWN-呼吸灯
本帖最后由 划句顾 于 2023-2-5 22:24 编辑一、呼吸灯
/*
Time:2022/12/3
author:LaoGu
function:呼吸灯
*/
module pwm(rst,clk,led);
input rst,clk;
output reg led;
parameter cnt_1us_max = 6'd49;
parameter cnt_1ms_max = 10'd999;
parameter cnt_1s_max= 10'd999;
reg cnt_1us;
reg cnt_1ms;
reg cnt_1s;
reg cnt_en;//标志
//1μs
always @(posedge clk,negedge rst) begin
if(rst == 1'b0)
cnt_1us <= 6'd0;
else if(cnt_1us==cnt_1us_max)
cnt_1us <= 6'd0;
else
cnt_1us <= cnt_1us + 6'd1;
end
//1ms
always @(posedge clk,negedge rst) begin
if(rst == 1'b0)
cnt_1ms <= 10'd0;
else if( (cnt_1ms==cnt_1ms_max)&& (cnt_1us==cnt_1us_max) )
cnt_1ms <= 10'd0;
else if(cnt_1us==cnt_1us_max)
cnt_1ms <= cnt_1ms + 10'd1;
else
cnt_1ms <= cnt_1ms;
end
//1s
always @(posedge clk,negedge rst) begin
if(rst == 1'b0)
cnt_1s <= 10'd0;
else if( (cnt_1s==cnt_1s_max)&& (cnt_1ms==cnt_1ms_max)&& (cnt_1us==cnt_1us_max) )
cnt_1s <= 10'd0;
else if( (cnt_1ms==cnt_1ms_max)&& (cnt_1us==cnt_1us_max) )
cnt_1s <= cnt_1s + 10'd1;
else
cnt_1s <= cnt_1s ;
end
//转换标志cnt_en
always @(posedge clk,negedge rst) begin
if(rst == 1'b0)
cnt_en <= 1'b0;
else if( (cnt_1s==cnt_1s_max)&& (cnt_1ms==cnt_1ms_max)&& (cnt_1us==cnt_1us_max) )
cnt_en <= ~cnt_en ;
else
cnt_en <= cnt_en ;
end
//呼吸灯
always @(posedge clk,negedge rst) begin
if(rst == 1'b0)
led<= 4'b0;
else if(( (cnt_en==1'b1) && (cnt_1ms<cnt_1s) )
||( (cnt_en==1'b0) && (cnt_1ms>cnt_1s) ) )
led <= 4'b1111;
else
led <= 4'b0;
end
endmodule
二、按键修改呼吸灯的方向
/*
Time:2022/12/3
author:LaoGu
function:通过按键修改呼吸灯的方向
*/
module pwm(rst,clk,led,key);
input rst,clk;
input key;
output reg led;
//例化函数
second t1(clk,rst,5000,msec); //定时0.1ms
second t2(clk,rst,50_000_000,sec); //定时1s
key_scan k1(clk,rst,key,DIR); //按键修改呼吸灯的变换方向
reg cnt;
reg zkb;
reg flag_en;
always @(posedge clk,negedge rst) begin
if(rst == 1'b0)
cnt <= 4'd0;
else if(msec)begin
if(cnt==4'd9)//1ms
cnt <= 4'd0;
else
cnt <= cnt + 4'd1;
end
end
//占空比
always @(posedge clk,negedge rst) begin
if(rst == 1'b0)
zkb <= 4'd0;
else if(sec)begin
if(zkb == 4'd9 )
zkb <= 4'd0;
else
zkb <= zkb + 4'd1;
end
end
//标志
always @(posedge clk,negedge rst) begin
if(rst == 1'b0)
flag_en <= 1'b0;
else if(DIR)
flag_en = ~flag_en;
else
flag_en = flag_en;
end
//产生PWM信号
always @(posedge clk,negedge rst) begin
if(rst == 1'b0)
led <= 4'b0;
else if(( (flag_en==1'b0) && (cnt<zkb) )
||( (flag_en==1'b1) && (cnt>zkb) ) )
led <= 4'b1111;
else
led <= 4'b0;
end
endmodule
{:10_275:} {:7_146:} {:7_146:} {:10_256:} {:10_256:}{:10_256:}{:10_256:} {:7_146:} {:10_249:} {:7_146:} 感谢分享! {:5_108:} {:7_146:} 好 {:10_245:} 顶起来 白嫖鱼币{:5_109:} {:5_102:} 1molHF 发表于 2023-2-6 09:43
{:5_90:} sfqxx 发表于 2023-2-5 22:25
{:5_102:} weiliao 发表于 2023-2-8 15:21
顶起来
{:5_102:}