#include "zlg7290_169.h"
void IIC_Init(void)
{
P3SEL |= BIT1 + BIT3; //P3.1、P3.3配置为IIC引脚
U0CTL |= I2C + SYNC; //IIC模式
U0CTL &= ~I2CEN; //禁止IIC模块
I2CTCTL = I2CSSEL_2; //IIC时钟SMCLK
I2CPSC = 7; //IIC时钟8分频
I2CSCLH = 0x03; //SCL高电平 5*IIC时钟
I2CSCLL = 0x03; //SCL低电平 5*IIC时钟
U0CTL |= I2CEN; //打开IIC时钟
}
void IIC_Write_Init(unsigned char SlaveAddress, unsigned char nBytes)
{
U0CTL |= MST; //主模式
I2CNDAT = nBytes; //数据字节数
I2CSA = SlaveAddress >> 1; //器件地址
I2CTCTL |= I2CTRX; //发送方式
while (I2CBUSY & I2CDCTL); //等待空闲
I2CTCTL |= I2CSTT + I2CSTP; //开始传送
}
void IIC_Read_Init(unsigned char SlaveAddress, unsigned char nBytes)
{
U0CTL |= MST; //主模式
I2CNDAT = nBytes; //数据字节数
I2CSA = SlaveAddress >> 1; //器件地址
I2CTCTL &= ~I2CTRX; //接收方式
while (I2CBUSY & I2CDCTL); //等待空闲
I2CTCTL |= I2CSTT + I2CSTP; //开始传送
}
void IIC_WriteByte(unsigned char Data)
{
while (!(I2CIFG & TXRDYIFG)); //
I2CDRB = Data;
while ((I2CIFG & NACKIFG)) I2CTCTL |= I2CSTP;//无应答结束总线
}
unsigned char IIC_ReadByte(void)
{
while (!(I2CIFG & RXRDYIFG));
return I2CDRB;
}
void IIC_Write(unsigned char SubAddress, unsigned char *IIcData, unsigned char Bytes)
{
IIC_Write_Init(DeviceAddress, Bytes+1);
IIC_WriteByte(SubAddress);
while (Bytes--)
{
IIC_WriteByte(*IIcData);
IIcData++;
}
while (I2CTCTL & I2CSTP);
}
void IIC_Read(unsigned char SubAddress, unsigned char *IIcData, unsigned char Bytes)
{
unsigned char i;
IIC_Write_Init(DeviceAddress, 1);
IIC_WriteByte(SubAddress);
while (I2CTCTL & I2CSTP);
IIC_Read_Init(DeviceAddress, Bytes);
for (i=0; i<Bytes; i++)
{
*IIcData = IIC_ReadByte( );
IIcData++;
}
while (I2CTCTL & I2CSTP);
}