module clock(hour_a,hour_d,min_a,min_d,clk_1ms,clk_500ms,hour_out,min_out,t_i_u);
input hour_a,hour_d,min_a,min_d,clk_1ms,clk_500ms;
output[6:0] hour_out,min_out;
output t_i_u;
reg t_i_u;
reg[6:0] hour_out,min_out;
reg[6:0] hour_mem,min_mem,hour_set,min_set;
reg[15:0] second;
initial
    begin
	 hour_mem = 0;
	 hour_set = 0;
	 hour_out = 0;
	 min_mem = 0;
	 min_set = 0;
	 min_out = 0;
	 second = 0;
	 t_i_u = 0;
	 end

always @(posedge clk_500ms)//检测按键状态，改变寄存器中保存的时间值
    begin
	 if(hour_a == 0&&hour_d == 0&&min_a == 0&&min_d == 0)
	     begin
		  hour_set = 0;
		  min_set = 0;
		  end
	 else if(hour_a == 0)//时位加1
	     begin
		  hour_set = hour_out;
		  min_set = min_out;
	     hour_set = hour_set+1;
		  end
	 else if(hour_d == 0)//时位减1
	     begin
		  hour_set = hour_out;
		  min_set = min_out;
	     hour_set = hour_set-1;
		  end
	 else if(min_a == 0)//分位加1
	     begin
		  hour_set = hour_out;
		  min_set = min_out;
	     min_set = min_set+1;
		  end
	 else if(min_d == 0)//分位减1
	     begin
		  hour_set = hour_out;
		  min_set = min_out;
	     min_set = min_set-1;
		  end
	 if(hour_set == 24)
	     hour_set = 0;
	 if(hour_set > 24)
	     hour_set = 23;
	 if(min_set == 60)
	     min_set = 0;
	 if(min_set > 60)
	     min_set = 59;
	 end
	 
always @(posedge clk_1ms)//高频时钟（周期为1ms）用于计时，并查看设置的时间是否有更新
    begin
	 if(t_i_u == 1)
	     t_i_u = 0;
	 if(hour_set != hour_mem || min_set != min_mem)
		  begin
        hour_mem = hour_set;
        min_mem = min_set;
        hour_out = hour_set;
        min_out = min_set;
        end
    else
        begin
		  if(second < 60000)//1分钟
		      second = second+1;//计时
		  else
		      begin
				min_out = min_out+1;
				second = 0;
				if(min_out == 60)
				    begin
					 hour_out = hour_out+1;
					 min_out = 0;
					 t_i_u = 1;//时间到达整点，输出一个脉冲
					 if(hour_out == 24)
					     begin
						  hour_out = 0;
						  end
					 end
				end
		  end  
	 end
endmodule