#include "lcd1602.h"
/*
unsigned char LCD1602State()
{
	unsigned char r;
	LCD1602_CLR_RS();
	LCD1602_SET_RW();
	LCD1602_SET_E();
	__delay_us(1);
	r=LCD1602_rBus();
	LCD1602_CLR_E();
	return r;
}

unsigned char LCD1602Read()
{
	unsigned char r;
	//等待lcd1602空闲
	//while(LCD1602State() & 0x7F);
	__delay_ms(1);
    
	LCD1602_SET_RS();
	LCD1602_SET_RW();
	LCD1602_SET_E();
	__delay_us(1);
	r=LCD1602_rBus();
	LCD1602_CLR_E();
	return r;
}
*/

void LCD1602WriteCmd(unsigned char cmd)
{
    LCD1602_CLR_E();
    
	//等待lcd1602空闲
	//while(LCD1602State() & 0x7F);
	delay_ms(1);
    
	LCD1602_CLR_RS();
	LCD1602_CLR_RW();
	LCD1602_wBus(cmd);
	LCD1602_SET_E();
	delay_us(1);
	LCD1602_CLR_E();
}



void LCD1602Write(unsigned char data_out)
{
    LCD1602_CLR_E();
    
	//等待lcd1602空闲
	//while(LCD1602State() & 0x7F);
	delay_ms(1);
    
	LCD1602_SET_RS();
	LCD1602_CLR_RW();
	LCD1602_wBus(data_out);
	LCD1602_SET_E();
	delay_us(1);
	LCD1602_CLR_E();
}

void LCD1602_Init(void)
{
    LCD1602WriteCmd(LCD_MODE_STD);              /*LCD标准工作模式：8位数据传送，2行显示，字符点阵5*7*/
    LCD1602WriteCmd(DISP_OFF);                  /*显示关闭*/
    LCD1602WriteCmd(DISP_CLR);                  /*清屏*/ 
                                                /*清屏和光标归位需要较长的时间*/

    LCD1602WriteCmd(CUR_AUTO_R);                /*设置光标在文字插入后自动右移*/
    LCD1602WriteCmd(DISP_ON&CUR_OFF&BLINK_OFF); /*显示开，无光标, 光标不闪烁*/
}


void LCD1602_setxy(unsigned char x,unsigned char y)
{
	if(x==0)
	{
		LCD1602WriteCmd(0x80+y);
	}
	else
	{
		LCD1602WriteCmd(0xc0+y);
	}
}


void LCD1602_Clear(void)
{
	LCD1602WriteCmd(DISP_CLR);
    delay_ms(1);
}


void LCD1602_PrintString(const char *s)
{
	while(*s)
	{
		LCD1602Write(*s);
		s++;
	}
}

void LCD1602_PrintInteger(long data_out)
{
	char buf[12];
	unsigned char i=0;
	if(data_out==0)
	{
		LCD1602Write('0');
	}
	else
	{
		while(data_out > 0)
		{
			buf[i]=data_out%10+'0';
			i++;
			data_out=data_out/10;
		}
		while(i--)
		{
			LCD1602Write(buf[i]);
		}
	}
}	
//==================================
void LCD1602_PrintHEX_TWO(long data_out)
{
	long h,l;
				
	l=data_out%16;
	
	h=data_out/16;
	
	if(h<10)
		h+='0';
	else
		h=h-10+'A';
	LCD1602Write(h);
	
	if(l<10)
		l+='0';
	else
		l=l-10+'A';
	LCD1602Write(l);	
}
void LCD1602_PrintHEX(long data_out)
{
	char buf[12];
	unsigned char i=0;

	
		while(data_out > 0)
		{
			buf[i]=data_out%16;
			i++;
			data_out=data_out/16;
		}
		switch (i)
		{
			case 0:
			{
				buf[0]=0;
				buf[1]=0;
				buf[2]=0;
				buf[3]=0;
				i=4;
				break;
			}
			case 1:
			{
				buf[1]=0;
				buf[2]=0;
				buf[3]=0;
				i=4;
				break;
			}
			case 2:
			{
				buf[2]=0;
				buf[3]=0;
				i=4;
				break;
			}			
			case 3:
			{
				buf[3]=0;
				i=4;
				break;
			}
			default:
				break;

		}
		
		while(i--)
		{
			if(buf[i]<10)
				buf[i]+='0';
			else
				buf[i]=buf[i]-10+'A';
			LCD1602Write(buf[i]);
		}
	
}	

		
