

//液晶屏元件,处理器无关代码

//2015.4.15 唉.... 真是天才~~ 
//深更半夜解决一个重大问题: 2004液晶屏经常初始化不通过, 屏幕显示乱码,
//而一旦复位通过的话, 就会一直正常, 不再出错.
//反复查看数据手册也不知道哪里问题, ...... 怀疑是布线, 电容, 74595, ...
//加延时... 办法都用尽了, 最后偶然试着把复位序列调用多次, 看它行不行,
//结果一试非常稳定, 每次复位都能正确完成, 之后屏幕正常显示...
//按下复位, 拔电源, 试了好多次, 想出错都难啊...... 非常好

//2016.1.17 这里太重要了... 执行clear之后再复位, 则很稳定!
//周末, 终于把1602. 2004液晶屏弄好了, 现在8位并口,4位并口,串口转4位并口等都调试好了,
//关于复位问题, 最重要的就是初始化之后, 清屏, 然后再次调用初始化

	//=================================================================================
	//提供的接口
	//[i] interface_char char;
	unit char
	{
		link void clear() {}
		link void clear_line( int32 l ) {}
		link void write_char( int32 l, int32 c, [int8*?] string ) {}
		public const int8 PerWidth = 1;
	}
	char.clear = clear;
	char.clear_line = clear_line;
	char.write_char = print_line;
	
	[uint8*80] buffer;
	bool changed;
	
	//---------------------------------------------------
	//初始化
	//[i] function_void OS_init;
	public void OS_init()
	{
		CMD.port_init();
		
		InitReg();
		clear();
		OS_thread();
		
		//2016.1.17 这里太重要了... 执行clear之后再复位, 则很稳定!
		InitReg();
		
		clear();
	}
	//---------------------------------------------------
	//线程扫描
	//[i] function_void OS_thread;
	public void OS_thread()
	{
		if( changed ) {
			changed = false;
			
			SetColume( 0x80, 0 );
			SetColume( 0xC0, 20 );
			SetColume( 0x94, 40 );
			SetColume( 0xD4, 60 );
		}
	}
	void SetColume( uint8 p, uint8 j )
	{
		loop( 20 ) {
			uint8 c = buffer[j];
			if( c > 0x80 ) {
				c & 0x7F;
				buffer[j] = c;
				set_char( p, c );
			}
			p + 1;
			j + 1;
		}
	}
	//---------------------------------------------------
	//清空
	//[i] function_void clear;
	public void clear()
	{
		clear_line( 1 );
		clear_line( 2 );
		clear_line( 3 );
		clear_line( 4 );
	}
	//---------------------------------------------------
	//清空第 n 行
	//[i] function_void clear_line int32;
	public void clear_line( int32 line )
	{
		if( line < 1 || line > 4 ) {
			return;
		}
		uint8 p = ((uint)(int8)(int16)line - 1) * 20;
		uint8 x80 = 0x80;
		loop( 20 ) {
			buffer[p] = ' ' + x80;
			p + 1;
		}
		changed = true;
	}
	//---------------------------------------------------
	//第 n 行显示
	//[i] function_void print_line int32 int32 int32;
	public void print_line( int32 line, int32 column, int32 d )
	{
		if( line < 1 || line > 4 ) {
			return;
		}
		if( column < 1 || column > 20 ) {
			return;
		}
		uint8 p = ((uint)(int8)(int16)line - 1) * 20;
		uint8 start = (uint)(int8)(int16)column - 1;
		
		int8 data = (int8)(int16)d;
		if( data < 0x20 ) {
			data + '0';
		}
		uint8 x80 = 0x80;
		buffer[p + start] = (uint)data + x80;
		changed = true;
	}
	
	#include "$run$.txt"
	
	
	
	