Skip to content

Instantly share code, notes, and snippets.

@mcgodfrey
Last active April 23, 2020 18:19
Show Gist options
  • Save mcgodfrey/93a5d3f97f327f570346 to your computer and use it in GitHub Desktop.
Save mcgodfrey/93a5d3f97f327f570346 to your computer and use it in GitHub Desktop.
Up-down counter (8-bit) in verilog for servo control example
/*
8 bit up-down counter.
Based on code from Mojo tutorial
https://embeddedmicro.com/tutorials/mojo/pulse-width-modulation
/\ /\
/ \ / \
/ \/ \
The CRT_LEN determines the period of the resulting counter
*/
module counter #(parameter CTR_LEN = 27) (
input wire clk,
input wire rst,
output reg [7:0] value
);
reg[CTR_LEN-1:0] ctr_d, ctr_q; //flip flop registers
//Create the up-down counter
//the MSB (ctr_q[CRT_LEN-1]) determines the ramp direction (up/down)
//The next 8 bighest bits are the counter value
//If we are ramping down, invert the bits to count down instead of up
always @(ctr_q) begin
ctr_d = ctr_q + 1'b1;
if (ctr_q[CTR_LEN-1] == 1)
value = ~ctr_q[CTR_LEN-2:CTR_LEN-9];
else
value = ctr_q[CTR_LEN-2:CTR_LEN-9];
end
//set the output (ctr_q) to the input (ctr_d) on each rising clock edge.
always @(posedge clk) begin
if (rst == 1) begin
ctr_q <= 'b0;
end else begin
ctr_q <= ctr_d;
end
end
endmodule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment