module buzzer(tri_time,tri_uart,data_uart,clk,clk_buzzer,stop,out);
input tri_time,tri_uart,clk,clk_buzzer;
input[231:0] data_uart;
output stop,out;
localparam size = 29;
localparam IDLE = 2'b00;
localparam LOAD_1 = 2'b01;
localparam LOAD_2 = 2'b10;
localparam MAIN = 2'b11;
reg stop,out;
reg[3:0] tone;
reg[5:0] num;
reg[15:0] time_end;
reg[17:0] time_cnt;
reg[size*8-1:0] music;
reg[1:0] state;
reg flag_1,flag_2;
reg[2:0] judge;
reg[23:0] num_delay;
initial
    begin
	 stop = 1;
	 music = 0;
	 flag_1 = 0;
	 flag_2 = 0;
	 num = size-1;
	 time_cnt = 0;
	 state = 2'b00;
	 end
always @(posedge clk_buzzer)
    begin
	 case(state)
	     IDLE:
		  begin
		  music = 0;
		  case(judge)
		      2'b01:state = LOAD_1;
				2'b10:state = LOAD_2;
				default:state = IDLE;
		  endcase
		  end
	     LOAD_1:
		  begin
		  music = 120'h080809090a0a0b0b0c0c0d0d0e0e00;
		  num = 14;
		  state = MAIN;
		  end
		  LOAD_2:
		  begin
		  music = data_uart;
		  num = 28;
		  state = MAIN;
		  stop = 0;
		  end
		  MAIN:
		  begin
		  
	     if(num == 0)
		      begin
	         num <= 0;
				state <= IDLE;
				stop <= 1; 
				end
		  else
		      begin
		      tone <= music[num*8+:8];
	         num <= num - 1;
				end
		  end
		  default:state = IDLE;
    endcase
	 end
always @(posedge clk)
    begin
	 case(tone)
	     5'd1:	time_end =	16'd22935;	//L1,01
		  5'd2:	time_end =	16'd20428;	//L2,02
		  5'd3:	time_end =	16'd18203;	//L3,03
		  5'd4:	time_end =	16'd17181;	//L4,04
		  5'd5:	time_end =	16'd15305;	//L5,05
		  5'd6:	time_end =	16'd13635;	//L6,06
		  5'd7:	time_end =	16'd12147;	//L7,07
		  5'd8:	time_end =	16'd11464;	//M1,08
		  5'd9:	time_end =	16'd10215;	//M2,09
		  5'd10:	time_end =	16'd9100;	//M3,0a
		  5'd11:	time_end =	16'd8589;	//M4,0b
		  5'd12:	time_end =	16'd7652;	//M5,0c
		  5'd13:	time_end =	16'd6817;	//M6,0d
		  5'd14:	time_end =	16'd6073;	//M7,0e
		  5'd15:	time_end =	16'd5740;	//H1,0f
		  5'd16:	time_end =	16'd5107;	//H2,11
		  5'd17:	time_end =	16'd4549;	//H3,12
		  5'd18:	time_end =	16'd4294;	//H4,13
		  5'd19:	time_end =	16'd3825;	//H5,14
		  5'd20:	time_end =	16'd3408;	//H6,15
		  5'd21:	time_end =	16'd3036;	//H7,16
		  default: time_end = 16'd0;
	 endcase
	 if(time_end == 0||num == 0)
	     out <= 0;
	 else if(time_cnt >= time_end)
	     begin
		  out <= ~out;
		  time_cnt <= 0;
		  end
	 else
	     time_cnt <= time_cnt + 1;
	 end
always @(posedge clk)
    begin
	 if(num_delay != 0)
	     begin
		  num_delay = num_delay - 1;
		  end
	 else
	     begin
		  judge[0] = tri_time;
		  judge[1] = tri_uart;
		  if(judge != 0)
		      num_delay = 7000000;
		  else
		      num_delay = 0;
		  end
    end
endmodule