/* 
This confidential and proprietary software may be used
only as authorized by a licensing agreement from
DIC LAB, NCKU
In the event of publication, the following notice is
applicable:

(C) COPYRIGHT 2012 DIC LAB, NCKU
ALL RIGHTS RESERVED

The entire notice above must be reproduced on all
authorized copies

FILE     : VGA.v
Author   : Ping-Hsuan, Lai
Date     : 2012.08.28
Version  : 1
Abstract :
This is a testing program for CIC MorFPGA+ Platform, version 0.9
The testing devices include onboard clk, reset, VGA

Modification Histroy :
2012.08.28, Ping-Hsuan, Lai, version 1, Original
2012.09.13, Chia-Hao, Li, version 2, revise the FILE and Author of the header
*/
module VGA(clk, rst, VGA_HS, VGA_VS , VGA_R, VGA_G, VGA_B, VGA_CLK, VGA_BLANK_N, VGA_SYNC_N );

input clk, rst;		//clk 50MHz
output  VGA_CLK, VGA_BLANK_N, VGA_SYNC_N;
output reg VGA_HS, VGA_VS;
output reg [7:0] VGA_R, VGA_G, VGA_B;

reg[10:0] counterHS;
reg[9:0] counterVS;
reg valid;

reg clk25M;
reg [10:0] X,Y;
// Horizontal Parameter
parameter H_FRONT = 16;
parameter H_SYNC  = 96;
parameter H_BACK  = 48;
parameter H_ACT   = 640;
parameter H_BLANK = H_FRONT + H_SYNC + H_BACK;
parameter H_TOTAL = H_FRONT + H_SYNC + H_BACK + H_ACT;

// Vertical Parameter
parameter V_FRONT = 11;
parameter V_SYNC  = 2;
parameter V_BACK  = 32;
parameter V_ACT   = 480;
parameter V_BLANK = V_FRONT + V_SYNC + V_BACK;
parameter V_TOTAL = V_FRONT + V_SYNC + V_BACK + V_ACT;

assign VGA_SYNC_N=1'b0;
assign VGA_BLANK_N=~((counterHS<H_BLANK)||(counterVS<V_BLANK));
assign VGA_CLK=~clk25M;

always@(posedge clk)
	clk25M = ~clk25M;


always@(posedge clk25M)
begin
	if(!rst) 
		counterHS <= 0;
	else if(counterHS == H_TOTAL) 
		counterHS <= 0;
	else 
		counterHS <= counterHS + 1'b1;
		
	// Horizontal Sync
   if(counterHS == H_FRONT-1) // Front porch end
      VGA_HS <= 1'b0;
     
   if(counterHS == H_FRONT + H_SYNC -1) // Sync pulse end
      VGA_HS <= 1'b1;
 
	
	if(counterHS >= H_BLANK)
      X <= counterHS-H_BLANK;
   else
      X <= 0;
end

always@(posedge clk25M)
begin
	if(!rst) 
		counterVS <= 0;
	else if(counterVS == V_TOTAL) 
		counterVS <= 0;
	else if(counterHS == H_TOTAL) 
		counterVS <= counterVS + 1'b1;
		
	if (counterVS == V_FRONT-1) // Front porch end
      VGA_VS <= 1'b0;  
		
   if (counterVS == V_FRONT + V_SYNC-1) // Sync pulse end
      VGA_VS <= 1'b1;      
	
	if(counterVS >= V_BLANK)
      Y <= counterVS-V_BLANK;
   else
      Y <= 0;
end

always@(posedge clk25M)
begin
	if (!rst) 
	begin
		VGA_R <= 0;
		VGA_G <= 0;
		VGA_B <= 0;
   end
	else 
	begin
		
		if(X < 320)
		begin
			VGA_R <= 0;
			VGA_G <= 8'd255;
			VGA_B <= 0;
		end
		else
		begin
			VGA_R <= 0;
			VGA_G <= 8'd255;
			VGA_B <= 8'd255;
		end
		
   end
end

endmodule
