# Square Wave Generation Verilog Code | How To Generate Square Wave Of Different Duty Cycle In Verilog

#### Square Wave Generation Verilog Code

How to Generate Square Wave of Different Duty Cycle in Verilog.

In this post we are sharing the Verilog code to generate square wave of different duty cycle.

```///////////////////////////////////////
//Verilog Code for Square Wave Generation
//////////////////////////////////////

`timescale 10ns / 1ps

module square_wave(
input clock,reset,
input &nbsp;[3:0] m,
input &nbsp;[3:0] n,
output reg square,
output reg clkby2=1'b0
);
reg [3:0] M;
reg [3:0] N;

reg [3:0] &nbsp;count1;
reg [3:0] &nbsp;count2;
reg state;
reg flag;
reg flag1;

reg int_flag;
parameter s0=1'b0, s1=1'b1;

always @(posedge clock)
begin
clkby2=~clkby2;
if(reset==1)
begin
int_flag=0;
count1=0;
count2=0;
state=0;
flag=0;
flag1=0;
square=0;
M=4'b0000;
N=4'b0000;
end

if(reset==0)
begin
if(int_flag==0)
begin
M=m;
N=n;
end

int_flag=1'b1;

case(state)

s0:
begin
if(flag==1'b0)
count1=M;

if(count1>4'b0000)
begin
square=1'b1;
flag=1'b1;
count1=count1-4'b0001;
if(count1==4'b0000)
begin &nbsp;
flag1=0;
state=s1;
end
else
&nbsp;              &nbsp;state=s0;
end
end

s1: begin
if(flag1==1'b0) count2=N;
if(count2>4'b0000)
begin
square=1'b0;
count2=count2-4'b0001;
flag1=1;
if(count2==4'b0000)
begin &nbsp;
flag=0; state=s0;
end
else
state=s1;
end
end
endcase
end
end
endmodule```