Skip to content

Instantly share code, notes, and snippets.

@jschoch
Created February 18, 2024 17:16
Show Gist options
  • Save jschoch/6d395c63a26c02fbc08156e46aaacc8d to your computer and use it in GitHub Desktop.
Save jschoch/6d395c63a26c02fbc08156e46aaacc8d to your computer and use it in GitHub Desktop.
encoder in verilog
module quad(clk, A, B, Z, count, revolutions);
input clk, A, B,Z;
output [63:0] count;
output [8:0] revolutions;
localparam [11:0] ppr = 80;
reg [2:0] quadA_delayed, quadB_delayed;
always @(posedge clk) quadA_delayed <= {quadA_delayed[1:0], A};
always @(posedge clk) quadB_delayed <= {quadB_delayed[1:0], B};
wire count_enable = quadA_delayed[1] ^ quadA_delayed[2] ^ quadB_delayed[1] ^ quadB_delayed[2];
wire count_direction = quadA_delayed[1] ^ quadB_delayed[2];
reg [63:0] count;
reg [7:0] revolutions;
always @(posedge clk)
begin
if(count_enable)
begin
if(count_direction) begin
count<=count+1;
if(Z) revolutions <= revolutions + 1;
end else begin
count<=count-1;
if(Z) revolutions <= revolutions - 1;
end
end
end
endmodule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment