`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
//	Tony Kim
//	6.111 Lab2
//
// Module name: SirenGenerator
// Description: Produces a warbling tone between 800 and 1000Hz. The two tones 
//					 alternate every 0.25 second.
//
//////////////////////////////////////////////////////////////////////////////////

module SirenGenerator(clock_27mhz, siren_in, siren_out);
    input clock_27mhz;
    input siren_in;
    output siren_out;

	parameter STATE_800HZ  = 1'b0;
	parameter STATE_1000HZ = 1'b1;

	//----------------------------------------------------------------------
	// The following periods are computed with a 27MHz base clock
	// The frequency of state toggling is 2Hz
	//----------------------------------------------------------------------
	parameter STATE_TOGGLE_PERIOD = 25'd6750000; 
	parameter PERIOD_800HZ  = 25'd33750; 
	parameter PERIOD_1000HZ = 25'd27000;

	reg state = STATE_800HZ;
	reg [25:0] state_count  = 25'b0; 
	reg siren_out = 1;

	reg [25:0] siren_count  = 25'b0;

	always @ (posedge clock_27mhz)
	begin
		if(siren_in)
		begin
			state_count <= state_count + 1;
			// We first check toggle between the 800Hz and the 1000Hz sounds
			if(state_count > STATE_TOGGLE_PERIOD)
			begin
				case(state)
					STATE_800HZ:  state <= STATE_1000HZ;
					STATE_1000HZ: state <= STATE_800HZ;
				endcase
				state_count <= 25'b0;
			end
			// Otherwise we produce the sound at the current frequency;
			else 
			begin
				case(state)
					STATE_800HZ:
					begin
						if(siren_count > PERIOD_800HZ)
						begin
							siren_out   <= ~siren_out;
							siren_count <= 25'b0;
						end
						else
							siren_count <= siren_count + 1;
					end
					STATE_1000HZ:
					begin
						if(siren_count > PERIOD_1000HZ)
						begin
							siren_out   <= ~siren_out;
							siren_count <= 25'b0;
						end
						else
							siren_count <= siren_count + 1;
					end
				endcase
			end
		end
	end
endmodule
