Skip to content

Instantly share code, notes, and snippets.

@wdevore
Created September 4, 2019 01:42
Show Gist options
  • Save wdevore/49dbe8aaaefc5034a51b7df42455e37f to your computer and use it in GitHub Desktop.
Save wdevore/49dbe8aaaefc5034a51b7df42455e37f to your computer and use it in GitHub Desktop.
Verilog 4bit up-counter using Icestorm framework and targeting the tinyFPGA-B2 board
// 4bit up counter - top.v
// This is expects a pcf specific to the tinyFPGA-B2 board
module top (
pin1_usb_dp, // USB pull-up enable, set low to disable
pin2_usb_dn,
pin3_clk_16mhz, // 16 MHz on-board clock
pin13, // Reset, active high, synchonous reset input
pin12, // Enable, active high on counter
pin11, // MSB output pin
pin10,
pin9,
pin8 // LSB output pin
);
// Clock driver
reg [22:0] clk_1hz_counter = 23'b0; // 1 Hz clock generation counter
reg clk_hz = 1'b0; // 1 Hz clock
localparam FREQUENCY = 23'd4;
// -----------------------------------------------------------------
// Ports
// -----------------------------------------------------------------
// ---------- Input ports -----------------------
input pin3_clk_16mhz; // 16 MHz on-board clock
input pin13; // Reset, active high, synchonous reset input
input pin12; // Enable, active high on counter
// ---------- Output ports -----------------------
output pin1_usb_dp; // USB pull-up enable, set low to disable
output pin2_usb_dn;
output pin11;
output pin10;
output pin9;
output pin8;
// -----------------------------------------------------------------
// Data types
// -----------------------------------------------------------------
// ---------- Input types -----------------------
wire pin3_clk_16mhz; // 16 MHz on-board clock
wire pin13; // Reset, active high, synchonous reset input
wire pin12; // Enable, active high on counter
// ---------- Output types -----------------------
wire pin1_usb_dp; // USB pull-up enable, set low to disable
wire pin2_usb_dn;
wire pin11;
wire pin10;
wire pin9;
wire pin8;
reg[3:0] counter_out = 0; // counter_out, 4 bit vector output
// Core Clock Scaler
always @(posedge pin3_clk_16mhz) begin
if (clk_1hz_counter < 23'd7_999_999)
clk_1hz_counter <= clk_1hz_counter + FREQUENCY;
else begin
clk_1hz_counter <= 23'b0;
clk_hz <= ~clk_hz;
end
end
// Application clock
always @(posedge clk_hz) begin
// At every rising edge of clock we check if reset is active
// If active, we load the counter output with 4'b0000
if (pin13 == 1'b1) begin
counter_out <= #1 4'b0000;
end
// If enable is active, then we increment the counter
else if (pin12 == 1'b1) begin
counter_out <= #1 counter_out + 1;
end
end
assign pin11 = counter_out[3];
assign pin10 = counter_out[2];
assign pin9 = counter_out[1];
assign pin8 = counter_out[0];
assign pin1_usb_dp = 1'b0;
assign pin2_usb_dn = 1'b0;
endmodule // top
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment