module moto_test(clock,key,duty_cycle,pwm_en,pwm_in,motoa,motob,led);
input clock; //系统时钟(48MHz)
input[2:0] key; //按键输入(KEY1~KEY3)
output[3:0]duty_cycle; //PWM占空比控制输出
output pwm_en; //PWM控制使能端
input pwm_in; //产生的PWM波输入
output motoa; //PWM波输出
output motob; //PWM波输出
output[4:0] led;
//I/O寄存器
reg[3:0]duty_cycle;
reg pwm_en;
//内部寄存器
reg[16:0]count; //时钟分频计数器
reg[2:0] dout1,dout2,dout3,buff; //消抖寄存器
reg moto_dir; //电机正反转
reg div_clk; //分频时钟
wire[2:0] key_edge; //按键消抖输出
assign led = ~{pwm_en,duty_cycle}; //LED输出状态指示
//时钟分频部分
always @(posedge clock)
begin
if (count < 17'd120000)
begin
count <= count + 1'b1;
div_clk <= 1'b0;
end
else
begin
count <= 17'd0;
div_clk <= 1'b1;
end
end
//按键消抖部分
always @(posedge clock)
begin
if(div_clk)
begin
dout1 <= key;
dout2 <= dout1;
dout3 <= dout2;
end
end
//按键边沿检测部分
always @(posedge clock)
begin
buff <= dout1 | dout2 | dout3;
end
assign key_edge = ~(dout1 | dout2 | dout3) & buff;
always @(posedge clock) //按键1,控制电动机速度
begin
if(key_edge[0])
duty_cycle <= duty_cycle + 1'b1;
end
always @(posedge clock) //按键2,控制电动机启动、停止
begin
if(key_edge[1])
pwm_en <= ~pwm_en;
end
always @(posedge clock) //按键3,控制电动机正/反转
begin
if(key_edge[2])
moto_dir <= ~moto_dir;
end
assign motoa = moto_dir ? pwm_in : 1'b0;
assign motob = moto_dir ? 1'b0 : pwm_in;
endmodule