// Module based on module from https://www.fpga4fun.com/TextLCDmodule.html
//
// By John Monahan (www.S100Computers.com)


module LCD1602(clk, Activate_LCD, rs, rw, en,dat, MUX_Switch);
 
 input clk, Activate_LCD;  
 output [7:0] dat; 
 output  rs,rw,en; 
 output MUX_Switch;
 

 reg e; 
 reg [7:0] dat; 
 reg rs;   
 reg [15:0] counter; 
 reg  [4:0] current,next; 
 reg clkr; 
 reg [1:0] cnt; 
 reg MUX_Switch;
 
 parameter  set0=4'h0;       // Parameters to initilize the HD44780 LCD display
 parameter  set1=4'h1; 
 parameter  set2=4'h2; 
 parameter  set3=4'h3; 
 parameter  set4=4'h4; 
 parameter  set5=4'h5; 
 parameter  set6=4'h6; 
 parameter  set7=4'h7; 
 parameter  set8=4'h8; 
 parameter  set9=4'hA; 
 parameter  set10=4'hB; 
 parameter  set11=4'hC; 
 parameter  set12=4'hD; 
 parameter  set13=4'hE; 
 parameter  set14=4'hF; 
 parameter  set15=5'h10; 
 parameter  set16=5'h11; 
 parameter  set17=5'h12; 
 parameter  set18=5'h13; 

 
  
always @(posedge clk)   		// Pulse to generate Enable signal   
 begin 
  counter=counter+1; 
  if(counter==16'h0008)  
       clkr=~clkr; 
end 



always @(posedge clkr) 

 if (Activate_LCD) begin 
  
  current=next; 
		
  case(current) 
    set0:   begin  rs<=0; dat<=8'h38; MUX_Switch<=1; next<=set1; end  	//8 bit mode
    set1:   begin  rs<=0; dat<=8'h0F; MUX_Switch<=1; next<=set2; end  	//Display On, Cursor on 
    set2:   begin  rs<=0; dat<=8'h8F; MUX_Switch<=1; next<=set3; end    //Position cursor on RHS.
    set3:   begin  rs<=0; dat<=8'h07; MUX_Switch<=1; next<=set4; end    //Shift left after each character addition 
 
    set4:   begin  rs<=1; dat<=8'h33;  MUX_Switch<=1; next<=set5; end    // lets demo a line of characters from the FPGA before 
    set5:   begin  rs<=1; dat<=8'h34;  MUX_Switch<=1; next<=set6; end    // tansferring control over to the S100 bus! 
    set6:   begin  rs<=1; dat<=8'h35;  MUX_Switch<=1; next<=set7; end    
    set7:   begin  rs<=1; dat<=8'h36;  MUX_Switch<=1; next<=set8; end    
    set8:   begin  rs<=1; dat<=8'h37;  MUX_Switch<=1; next<=set9; end    
    set9:   begin  rs<=1; dat<=8'h38;  MUX_Switch<=1; next<=set10; end    
    set10:   begin  rs<=1; dat<=8'h41;  MUX_Switch<=1; next<=set11; end    
    set11:   begin  rs<=1; dat<=8'h42;  MUX_Switch<=1; next<=set12; end    
    set12:   begin  rs<=1; dat<=8'h43;  MUX_Switch<=1; next<=set13; end    
    set13:   begin  rs<=1; dat<=8'h44;  MUX_Switch<=1; next<=set14; end    
    set14:   begin  rs<=1; dat<=8'h45;  MUX_Switch<=1; next<=set15; end    
    set15:   begin  rs<=1; dat<=8'h46;  MUX_Switch<=1; next<=set16; end    
    set16:   begin  rs<=1; dat<=8'h47;  MUX_Switch<=1; next<=set17; end    
    set17:   begin  rs<=1; dat<=8'h48;  MUX_Switch<=1; next<=set18; end    
    set18:   begin  rs<=1; dat<=8'h0 ;  MUX_Switch<=0; end               // Switch over to the S100 Bus Port 68H for Character Input 
	endcase 
	
 end 
 
assign en=clkr; 
assign rw=0; 
endmodule  