04_led_water_flow_v0

流水灯和跑马灯都是一种常见的LED灯效,它们在灯光的变化方式上有所不同。

流水灯是一种灯效模式,LED灯在一定的时间间隔内依次点亮或熄灭,形成像水流一样的效果。而跑马灯则是LED灯在一定的时间间隔内依次从左向右或从右向左依次点亮或熄灭,形成像跑马一样的效果,每个时刻只有一个灯亮,其他灯都熄灭。

更新

使用dip开关控制跑马灯的速度和方向

知识点:

  • 非循环移位寄存器的使用
  • 两种不同的组合逻辑赋值风格(assign, always(*))
  • 灵活利用参数设计可复用模块(模块级参数,局部参数)

module led_water_flow #(
    parameter LED_ON = 1'b0,  //led active low
    parameter CLK_FREQ  = 50*1000*1000  //frequency of input clock
)(
    input  clk,  
    input  rst_n, 

    input wire [5:0] dip_u6,
    output reg [5:0] led
);

//
//Local parameter, same as const in c/c++
//For 50Mhz clock, 
//one second count to 50*1000*1000 
//one millisecond count to 50*1000 
//
localparam ONE_MSECOND = CLK_FREQ / 1000;

//-------------------------------------------
//control the running speed and direction 
//according to the status of dip keys
wire [1:0] speed = dip_u6[1:0];
wire direct = dip_u6[5];

//First style of assignment for combinational logic, (not for sequential logic)
//Note: left value must be wire type, here 'wire [31:0] count_max;'
wire [31:0] count_max;  
assign count_max =  (speed == 0) ? ONE_MSECOND * 2000 :
                    (speed == 1) ? ONE_MSECOND * 1000 :
                    (speed == 2) ? ONE_MSECOND * 500 : ONE_MSECOND * 200;
/*
//another style of assignment of combinational logic
//Note: left value must be reg type, here 'reg [31:0] count_max;'
reg [31:0] count_max;  
always @(*) begin
    count_max =     (speed == 0) ? ONE_MSECOND * 2000 :
                    (speed == 1) ? ONE_MSECOND * 1000 :
                    (speed == 2) ? ONE_MSECOND * 500  : ONE_MSECOND * 200;
end
*/

//---------------------------------------------------------
//water flow will light leds one by one, and then set off all leds,
//then light leds one by one, and then turn off all,recycle 
reg [31:0] count; 
wire time_on = (count == count_max-1);

always @(posedge clk) begin
    if(~rst_n) count <= 0;
    else if(time_on) count <= 0;
    else count <= count + 1;
end

wire [5:0] all_led_on = (LED_ON == 1'b1) ?  6'b111111 : 6'b000000;
wire [5:0] all_led_off = ~all_led_on;

always @(posedge clk) begin
    if(~rst_n) led <= all_led_off;
    else if(time_on) begin
        if(led == all_led_on) led <= all_led_off;
        else begin
            if(direct == 1'b1) led <= {led[4:0], LED_ON} ; //shift left
            else led <= {LED_ON,led[5:1]} ;                 //shift right
        end
    end
    //else led <= led;
end
endmodule

扩展思维

了解呼吸灯的效果,思考如何用Verilog设计实现。

05-06 07:51