Quartus_blink/blink.v

103 lines
3.4 KiB
Verilog

module blink #(
// Input clock frequency in Hz
parameter integer F_CLK = 50_000_000 // 50 MHz
)(
input wire clk,
output wire led,
output wire pin,
output wire pin_10
);
//---------------------------------------------------------
// Step duration:
// - for 0 Hz : 8 s
// - for others : 4 s
//---------------------------------------------------------
localparam integer STEP_4SEC_MAX = (F_CLK * 4) - 1;
localparam integer STEP_8SEC_MAX = (F_CLK * 8) - 1;
// Step timer counter
reg [31:0] step_cnt = 32'd0;
// Frequency index: 0..5 → 0,10,20,30,40,50 Hz
reg [2:0] freq_idx = 3'd0;
// Half-period counter and current half-period length in clock cycles
reg [31:0] blink_cnt = 32'd0;
reg [31:0] max_count = 32'd0;
// Base LED signal (before output inversions)
reg led_base = 1'b0;
//---------------------------------------------------------
// Function to calculate half-period in clock cycles
//---------------------------------------------------------
function [31:0] calc_max_count;
input [2:0] idx;
integer f;
begin
// Frequency in Hz: 0, 10, 20, 30, 40, 50
f = idx * 10;
if (f == 0) begin
// Special case: 0 Hz → no blinking
calc_max_count = 32'd0;
end else begin
// Half-period: F_CLK / (2 * f)
calc_max_count = (F_CLK / (2 * f)) - 1;
end
end
endfunction
//---------------------------------------------------------
// Main process: step timing, frequency selection,
// blink generation
//---------------------------------------------------------
always @(posedge clk) begin
//-----------------------------------------------------
// Step timer: change frequency every 4 or 8 seconds
//-----------------------------------------------------
if (step_cnt >= (freq_idx == 3'd0 ? STEP_8SEC_MAX : STEP_4SEC_MAX)) begin
step_cnt <= 32'd0;
// Cycle through 0→1→2→3→4→5→0...
if (freq_idx == 3'd5)
freq_idx <= 3'd0;
else
freq_idx <= freq_idx + 3'd1;
end else begin
step_cnt <= step_cnt + 32'd1;
end
//-----------------------------------------------------
// Recalculate half-period for current frequency
//-----------------------------------------------------
max_count <= calc_max_count(freq_idx);
//-----------------------------------------------------
// Blink generation
//-----------------------------------------------------
if (max_count == 32'd0) begin
// 0 Hz: hold current state, no blinking
blink_cnt <= 32'd0;
// led_base keeps its last value
end else begin
if (blink_cnt >= max_count) begin
blink_cnt <= 32'd0;
led_base <= ~led_base;
end else begin
blink_cnt <= blink_cnt + 32'd1;
end
end
end
//---------------------------------------------------------
// Outputs:
// led = inverted base signal
// pin = same as led
// pin_10 = inverted pin
//---------------------------------------------------------
assign led = ~led_base;
assign pin = led;
assign pin_10 = ~pin;
endmodule