
//修改记录

//2014.5.6
//修改了字符发送底层函数, 去掉了方向选择端口, 这个放在具体的模块封装文件中去提供接口
//去掉了发送延时, 现在是检测硬件寄存器判断字符是否可以发送以及是否发送完毕
//增加了波特率设置函数作为接口

//2015.12.27
//去掉了协议解析部分, 只保留串口缓冲区

	public const int16 max_length = 32;
	public [int8*max_length] buffer;
	public int16 length;
	public int16 start;

	int16 cindex;

	public const int32 XTAL = $freq$;

	//加载芯片底层代码
	#include "$chip$.txt"
	
	unit reader0
	{
		public link bool IsReady() {}
		public link int32 GetData() {}
		public link void SetData( int32 d ) {}
		public link void SetStart() {}
		public link int32 ReadBuffer( int32 i ) {}
	}
	reader0.IsReady = is_ready;
	reader0.GetData = get_data;
	reader0.SetData = print_char;
	reader0.SetStart = SetStart;
	reader0.ReadBuffer = ReadBuffer;
	
	//----------------------------------------------------
	//串口初始化,波特率:9600,8个数据位,1个停止位,没有奇偶校验
	public void uart_OS_init()
	{
		//io.RDE_DIR = 1;
		//io.RDE_OUT = 0;
		
		//io.RXD_DIR = 0;
		//io.RXD_OUT = 1;
		
		//io.TXD_DIR = 1;
		//io.TXD_OUT = 1;
		
		PORT.D2_DIR = 0;
		PORT.D2_OUT = 1;
		
		PORT.D3_DIR = 1;
		PORT.D3_OUT = 1;
		
		//设置默认波特率
		set_baud( baud );
		
		length = 0;
		start = 0;
		cindex = 0;
	}
	//---------------------------------------------------
	//扫描数据
	public void OS_thread()
	{
		OS_EventFlag.1(bit) = 1;
		if( is_ready() ) {
			OS_EventFlag.2(bit) = 1;
		}
	}
	//---------------------------------------------------
	//获取当前数据
	public int32 get_data()
	{
		int16 n = start;
		start + 1;
		start % max_length;
		return buffer[n];
	}
	//---------------------------------------------------
	//判断当前数据是否有效
	public bool is_ready()
	{
		//注意 length 是临界变量,不能直接访问
		#asm "cli"
		int16 t_length = length;
		#asm "sei"
		
		return start != t_length;
	}
	void SetStart()
	{
		cindex = start;
	}
	int32 ReadBuffer( int32 n )
	{
		int16 i = cindex + (int16)n;
		i % max_length;
		uint32 data = (uint)buffer[i];
		return (int)data;
	}
	//=================================================================================
	
	//发送一个字符
	public void print_char( int32 data )
	{
		uint32 d = (uint)data;
		print_byte( (int)d.0(uint8) );
	}

//=================================================================================
	//发送一个字节
	public void print_byte( int8 data )
	{
		WAIT_SEND_OK();
		UDR = (uint)data;
	}
	//发送延时
	void delay()
	{
		loop( 15 ) loop( 100 ) {}
	}
	//数据接收中断
	INTERRUPT_UART
	void RXC()
	{
		//必须在中断程序中读取 UDR,否则在退出后会重新进入中断
		buffer[length] = (int)UDR;
		length + 1;
		length % max_length;
	}
	
	
	#include "uart_extend.txt"
	
	//----------------------------------------------------
	//发送一个字符
//	public void print_char( int8 data )
//	{
//		io.RDE_OUT = 1;
//		delay();
//		CHIP.UDR = (uint)data;
//		repeat until CHIP.UCSRA.5(bit) == 1; {}
//		CHIP.UCSRA.5(bit) = 1;
//		delay();//这个延时很重要! 去掉之后可以接收但是发送有错
//		io.RDE_OUT = 0;
//	}















