#include <kd_sfrs.h>
#include "lcd.h"

/******************************************************************************
;  DeclaraciĆ³ de constants del display
;******************************************************************************
;conexionat:
;	p1.4..p1.7 = D4..D7
;	p1.0 = RS
;	p1.2 = E
;	0 = R/W  siempre escribimos
*/

#define LCD_INS	0xfe
#define LCD_DAT 0x01
#define LCD_ENA	0x04

#define LCD_LINEA2 0xC0
#define LCD_LINEA1 0x80
#define LCD_CLRSCR 0x01			/* RETARD DE 1.64 ms */

void WRITE_LCD_4BITS();

void INICIALITZA_LCD()
{
/*
;0      X000 0000B = 00H   ->              IOPORT1
;1      X000 0001B = 01H
;15     X000 1111B = 0FH
*/ 

  DELAY_10mS();
  DELAY_10mS();

  wsr=0;
  ioport1=0x30 & LCD_INS;
  WRITE_LCD_4BITS();
  DELAY_10mS();

  wsr=0;
  ioport1=0x30 & LCD_INS;
  WRITE_LCD_4BITS();
  DELAY_10mS();

  wsr=0;
  ioport1=0x30 & LCD_INS;
  WRITE_LCD_4BITS();
  DELAY_10mS();

  wsr=0;
  ioport1=0x20 & LCD_INS; /* interface de 4 bits */
  WRITE_LCD_4BITS();
  DELAY_10mS();

/*AHORA YA PODEMOS USAR LA FUNCION DE INSTRUCION LCD*/
/*FUNCTION SET- 4 bits dades, 2 lines, caracter font*/

  INSTRUCCIO_LCD(0x28);

  /*DISPLAY ON/OFF-DISPLAY ON, CURSOR OFF, CURSOR NO BLINK*/
  INSTRUCCIO_LCD(0x0C);

  INSTRUCCIO_LCD(0x06);  /*ENTRY MODE SET-INCREMENT CURSOR, CURSOR MOVEMENT*/

  INSTRUCCIO_LCD(0x01);  /*CLEAR DISPLAY*/
  DELAY_10mS();                     
  /*ESTE RETARDO DEBERIA DE SER DE 1.64mS*/
}

void WRITE_LCD_4BITS()
{
/*AQUESTA FUNCIO ES NOMES PER US INTERN DE LA LLIBRERIA DEL DISPLAY*/

  asm{NOP;NOP;}
  wsr=0;
  ioport1 = ioport1 ^ LCD_ENA; /*XORB IOPORT1,#LCD_ENA*/

  asm{  
  NOP;NOP;NOP;NOP;NOP;
  NOP;NOP;NOP;NOP;NOP;
  }

  wsr=0;
  ioport1 = ioport1 ^ LCD_ENA; /*XORB IOPORT1,#LCD_ENA*/
  asm{NOP;}
}  


void INSTRUCCIO_LCD(unsigned char inst)
{ 
  wsr=0;
  ioport1=0xF0 & inst & LCD_INS ;                 /* RS=0 */
  WRITE_LCD_4BITS();
  inst<<=4;
  asm{
  NOP;NOP;
  NOP;NOP;NOP;
  }
  wsr=0;
  ioport1 =0xF0 & inst & LCD_INS;
  WRITE_LCD_4BITS();
  DELAY_40uS();
}

void DADA_LCD(unsigned char dato)
{  
  wsr=0;
  ioport1=0xF0 & dato; /*parte alta primero*/
  ioport1=ioport1|LCD_DAT;   /*RS=1*/
  WRITE_LCD_4BITS();
  dato<<=4;
  asm{
  NOP;NOP;
  NOP;NOP;NOP;
  }
  wsr=0;
  ioport1=0x0F0 & dato;
  ioport1=ioport1|LCD_DAT;
  WRITE_LCD_4BITS();
  DELAY_40uS();
}

void CLRSCR_LCD()
{
  INSTRUCCIO_LCD(LCD_CLRSCR);
  DELAY_10mS();
}

void DELAY_10mS()
{
  unsigned int TIMER_LCD;

  TIMER_LCD=2000;
  while(TIMER_LCD!=0)
  {
     TIMER_LCD--;
  }
}  

void DELAY_40uS()
{
  unsigned int TIMER_LCD;

  TIMER_LCD=40;
  while(TIMER_LCD!=0)
  {
   TIMER_LCD--;
  }
}

void GOTOXY(unsigned char x, unsigned char y)
/*   1<=x<=16  ,  1<=Y<=2 */
{
   unsigned char gotopos;
   gotopos=0x80 | ((y-1)*0x40) | (x-1);
   INSTRUCCIO_LCD(gotopos);
}