// 时钟信号发生,这里采用的方法是直接从主时钟产生,也可以选择一级一级由不同时钟产生 always @(posedge clk ornegedge rstn) begin if (!rstn) begin duty_clk_counter <= 0; duty_clk <= 0; end elsebegin if (duty_clk_counter == (DUTY_DIV - 1'b1)) begin duty_clk <= ~duty_clk; duty_clk_counter <= 0; end elsebegin duty_clk_counter <= duty_clk_counter + 1'b1; end end end
always @(posedge clk ornegedge rstn) begin if (!rstn) begin breath_clk_conter <=0; breath_clk <= 1; end elsebegin if (breath_clk_conter == (BREATH_DIV - 1'b1)) begin breath_clk <= ~breath_clk; breath_clk_conter <= 0; end elsebegin breath_clk_conter <= breath_clk_conter + 1'b1; end end end // 占空比信号控制 always @(posedge duty_clk ornegedge rstn) begin if (!rstn) begin // reset duty_counter <= 0; end elsebegin // flag为0,表示在呼,占空比增加 if (duty_flag == 0) begin duty_counter <= duty_counter + 1'b1; end // flag为1,表示在吸,占空比减少 elseif (duty_flag == 1) begin duty_counter <= duty_counter - 1'b1; end elsebegin duty_counter <= duty_counter; end end end
always @(posedge duty_clk ornegedge rstn) begin if (!rstn) begin // reset duty_flag <= 0; last_duty_flag <= 0; end elsebegin if (duty_counter == (MAX_PWM_COUNT - 1'b1) && last_duty_flag == 1'b0) begin duty_flag <= 1'b1; last_duty_flag <= duty_flag; end elseif (duty_counter == 1'b1 && last_duty_flag == 1'b1) begin duty_flag <= 1'b0; last_duty_flag <= duty_flag; end elsebegin last_duty_flag <= duty_flag; duty_flag <= duty_flag; end end end // 呼吸灯控制计数器,每加一就换一个LED always @(posedge breath_clk ornegedge rstn) begin if (!rstn) begin led_counter <= 0; end elsebegin if (led_counter == (MAX_LED_COUNT - 1'b1)) led_counter <= 0; elsebegin led_counter <= led_counter + 1'b1; end end end
// PWM信号产生 always @(posedge clk ornegedge rstn) begin if (!rstn) begin pwm <= 0; pwm_counter <= 0; end elseif (pwm_counter == (MAX_PWM_COUNT - 1'b1)) begin pwm_counter <= 0; end elseif (pwm_counter <= duty_counter) begin pwm <= 1'b1; pwm_counter <= pwm_counter + 1'b1; end elsebegin pwm <= 1'b0; pwm_counter <= pwm_counter + 1'b1; end end