verilog设计步进电机

要求:用100MHZ系统时钟设计四相单双八拍步进电机

verilog设计步进电机_第1张图片

 设计代码:

//四相单双八拍步进电机
module StepMotorPorts (
	input Clk,
	input Rst_n,
	input Turn,//Turn==1 为正向转动 Turn==0 为反向转动
	output reg [3:0]StepDrive
);
//实现250hz的计数
reg [18:0]cnt;//为步进电机提供250hz的频率 系统时钟100Mhz 计数值100000000/250=400000
always @(posedge Clk or negedge Rst_n)
	if(!Rst_n)
		cnt <= 0;
	else if( cnt == 19'd399999 )
		cnt <= 0;
	else 	
		cnt <= cnt + 1;

//250hz时钟使能
reg Clk_en;
always @(posedge Clk or negedge Rst_n)
	if(!Rst_n)
		Clk_en <= 0;
	else if( cnt == 19'd399999 )
		Clk_en <= 1;
	else 
		Clk_en <= 0;

//共八种状态 即八拍
reg [2:0]State;
always @(posedge Clk or negedge Rst_n)
	if(!Rst_n)begin
		State <= 3'b000;
		StepDrive <= 4'b0001;
	end
	else if(Clk_en)
		begin
			if(Turn)
				State <= State + 3'b1;
			else if( Turn == 0 )
				State <= State - 3'b1;
		end
	else case(State)
				3'b000: StepDrive <= 4'b0001;//A
				3'b001: StepDrive <= 4'b0011;//AB
				3'b010: StepDrive <= 4'b0010;//B
				3'b011: StepDrive <= 4'b0110;//BC
				3'b100: StepDrive <= 4'b0100;//C
				3'b101: StepDrive <= 4'b1100;//CD
				3'b110: StepDrive <= 4'b1000;//D
				3'b111: StepDrive <= 4'b1001;//DA
			endcase
endmodule

测试代码:我以Turn == 1 正向进行测试

`timescale 1ns / 1ns
module StepMoterPorts_tb();

reg Clk;
reg Rst_n;
reg Turn;
wire [3:0]StepDrive;

StepMotorPorts StepMotorPorts(
	.Clk(Clk),
	.Rst_n(Rst_n),
	.Turn(Turn),
	.StepDrive(StepDrive)
);

initial Clk = 1;
always #5 Clk = ~Clk; //产生时钟

initial begin
	Rst_n = 0;
	#201;
	Rst_n = 1;
	Turn = 1;
	#40000000;
	$stop;
end

endmodule

波形图:

verilog设计步进电机_第2张图片

你可能感兴趣的:(新手学习,fpga开发)