
unit TM1637
{
	link bit SDA_DIR;
	link bit SDA_IN;
	link bit SDA_OUT;
	
	link bit SCL_DIR;
	link bit SCL_OUT;
	
	//--------------------------------------------
	//[i] function_void OS_init;
	public void OS_init()
	{
		SDA_DIR = 1;
		SDA_OUT = 1;
		
		SCL_DIR = 1;
		SCL_OUT = 1;
	}
	//--------------------------------------------
	//写入一个命令
	void set_command( uint8 cmd )
	{
		start_iic();
		write_byte( cmd );
		end_iic();
	}
	//--------------------------------------------
	//写入一个字节
	void set_data( uint8 cmd, uint8 data )
	{
		start_iic();
		write_byte( cmd );
		write_byte( data );
		end_iic();
	}
	//--------------------------------------------
	//读取一个字节
	//暂时用不到, 不需要读取按键值
	uint8 get_data( uint8 cmd )
	{
		start_iic();
		write_byte( cmd );
		uint8 data = read_byte();
		NoAck();
		end_iic();
		return data;
	}
	//---------------------------------------------------
	//开始IIC通信
	void start_iic()
	{
		SDA_OUT = 1;
		SCL_OUT = 1;
		delay_1us();
		SDA_OUT = 0;
		delay_1us();
		SCL_OUT = 0;
		delay_1us();
	}
	//结束IIC通信
	void end_iic()
	{
		SDA_OUT = 0;
		SCL_OUT = 1;
		delay_1us();
		SDA_OUT = 1;
		delay_1us();
		SCL_OUT = 1;
		delay_1us();
	}
	//等待应答信号
	void wait()
	{
		uint8 t = 0;
		SDA_input_mode();
		SCL_OUT = 1;
		while( SDA_IN == 1 && t < 100 ) { t + 1; delay_1us(); }
		SCL_OUT = 0;
		delay_1us();
		SDA_output_mode();
	}
	//写一个字节
	void write_byte( uint8 data )
	{
		loop( 8 ) {
			SDA_OUT = data.0(bit);
			data >> 1;
			delay_1us();
			SCL_OUT = 1;
			delay_1us();
			SCL_OUT = 0;
			delay_1us();
		}
		wait();
	}
	//读一个字节
	uint8 read_byte()
	{
		uint8 data;
		SDA_input_mode();
		loop( 8 ) {
			data >> 1;
			data.7(bit) = SDA_IN;
			SCL_OUT = 1;
			delay_1us();
			SCL_OUT = 0;
			delay_1us();
		}
		SDA_output_mode();
		return data;
	}
	//发送非应答
	void NoAck()
	{
		//SDA_OUT = 0;		//应答
		SDA_OUT = 1;		//非应答
		delay_1us();
		SCL_OUT = 1;
		delay_1us();
		SCL_OUT = 0;
		delay_1us();
	}
	//SDA转换到输入模式
	void SDA_input_mode()
	{
		SDA_OUT = 1;
		SDA_DIR = 0;
	}
	//SDA转换到输出模式
	void SDA_output_mode()
	{
		SDA_DIR = 1;
	}
	//延时1微秒
	void delay_1us()
	{
		loop( 2 ) {}
	}
}







