上代码:
module led(
input clk, // 50MHz 输入时钟
output reg led // led 输出(低电平有效)
);
//--------------------------------------------------------
// 生成一个延迟,在一段时间内维持led输出一个不变的占空比
`define MAX_DELAY_CNT 500000
reg myclk;
reg [23:0] delay_cnt;
always@(posedge clk)
begin
if(delay_cnt < `MAX_DELAY_CNT)
delay_cnt <= delay_cnt + 1'b1;
else
begin
delay_cnt <= 24'd1;
myclk <= ~myclk;
end
end
//--------------------------------------------------------
// 占空比分为0~100个级别
// 0的时候,占空比最小,这个时候直接完全输出低电平,led灯最亮
// 100的时候,占空比最大,这个时候直接完全输出高电平,led等熄灭
`define CYCLE_NUMBER 100
reg [7:0] current_cycle;
reg flag;
always@(posedge myclk)
begin
if(flag == 0)
begin // 占空比递增
if(current_cycle < `CYCLE_NUMBER)
current_cycle <= current_cycle + 1'b1;
else
//current_cycle <= 1'b0;
flag <= ~flag;
end
else
begin // 占空比递减
if(current_cycle > 0)
current_cycle <= current_cycle - 1'b1;
else
flag <= ~flag;
end
end
//--------------------------------------------------------
// 轮询 0~100个级别的占空比
reg [7:0] cycle;
always@(posedge clk)
begin
if(cycle < `CYCLE_NUMBER)
cycle <= cycle + 1'b1;
else
cycle <= 1'b1;
end
//--------------------------------------------------------
// cycle小于current_cycle的时候是高电平
// cycle大于current_cycle并且小于CYCLE_NUMBER的时候是低电平
always@(posedge clk)
begin
if((cycle == `CYCLE_NUMBER) && (current_cycle != 0))
led <= 1'b1;
else if(cycle < current_cycle)
led <= 1'b1;
else
led <= 1'b0;
end
endmodule
verilog 呼吸灯