#include "main.h"
volatile uint32_t I2CDATA1;
void InitSYS()
{
UNLOCKREG();
DrvSYS_SetOscCtrl(E_SYS_XTL12M, 1); //选择外部晶振;
DrvSYS_Delay(5000);
LOCKREG();
}
void InitGPIO()
{
DrvGPIO_InitFunction( E_FUNC_I2C1); //使能I2C功能;
}
void InitI2C()
{
DrvI2C_Open(I2C_PORT1, 400000); //打开I2C硬件并配置时钟总线400KHZ;
DrvI2C_SetClockFreq (I2C_PORT1, 400000);//给I2C配置时钟频率;
DrvI2C_GetStatus (I2C_PORT1); //获取I2C状态码;
DrvI2C_WriteData(I2C_PORT1, 0); //写字节;
DrvI2C_ReadData(I2C_PORT1); //读字节;
DrvI2C_Ctrl(I2C_PORT1, 0, 0, 0, 0); //设定I2C控制位,包括控制寄存器中的STA, STO, AA, SI。
}
void Write_data(uint32_t address ,uint32_t data )
{
uint32_t I2CDelay;
DrvI2C_Open(I2C_PORT1, 400000); //打开I2C硬件,并配置时钟总线400KHZ
DrvI2C_Ctrl(I2C_PORT1, 1, 0, 0, 0); //发送一个起始信号
while(I2C1->CON.SI==0);
DrvI2C_WriteData(I2C_PORT1, 0xA0); //发送写命令;
DrvI2C_Ctrl(I2C_PORT1, 0, 0, 1, 0);
while(I2C1->CON.SI==0);
DrvI2C_WriteData(I2C_PORT1, address); //写地址;
DrvI2C_Ctrl(I2C_PORT1, 0, 0, 1, 1);
while(I2C1->CON.SI==0);
DrvI2C_WriteData(I2C_PORT1, data); //写数据;
DrvI2C_Ctrl(I2C_PORT1, 0, 0, 1, 1); //给响应并清除中断标志;
while( I2C1->CON.SI == 0 );
DrvI2C_Ctrl(I2C_PORT1, 0, 1, 1, 0); //清标志位 SI 并STOP
for(I2CDelay=0;I2CDelay<50;I2CDelay++);
DrvI2C_Close(I2C_PORT1);
for(I2CDelay=0I2CDelay<6000;I2CDelay++);
for(I2CDelay=0;I2CDelay<6000I2CDelay++);
}
uint32_t Read_data(uint32_t address,uint32_t wordaddress)
{
uint32_t I2CDATA=0;
DrvI2C_Open(I2C_PORT1, 50000);
DrvI2C_Ctrl(I2C_PORT1, 1, 0, 1, 0); //发送一个起始信号;
while(I2C1->CON.SI==0);
DrvI2C_WriteData(I2C_PORT1, 0xA0); //写从机地址+写
DrvI2C_Ctrl(I2C_PORT1, 0, 0, 1, 0);
while(I2C1->CON.SI==0);
DrvI2C_WriteData(I2C_PORT1, wordaddress); //写字地址;
DrvI2C_Ctrl(I2C_PORT1, 0, 0, 1, 1); //清除中断标志位并ACK;
while(I2C1->CON.SI==0);
DrvI2C_Ctrl(I2C_PORT1, 1, 0, 1, 0); //设定I2C控制比特 START并清中断标志
while( I2C1->CON.SI == 0 );
DrvI2C_WriteData(I2C_PORT1, address++); //写地址+读;
DrvI2C_Ctrl(I2C_PORT1, 0, 0, 1, 1); //清标志位 SI 并使能应答
while( I2C1->CON.SI == 0 );
DrvI2C_Ctrl(I2C_PORT1, 0, 0, 1, 0); //清标志位 SI
while( I2C1->CON.SI == 0 );
I2CDATA=DrvI2C_ReadData(I2C_PORT1);
DrvI2C_Ctrl(I2C_PORT1, 0, 1, 1, 0);
DrvI2C_Close(I2C_PORT1);
return I2CDATA;
}
int main ()
{
InitSYS();
InitGPIO();
InitI2C();
while(1)
{
Write_data(0x02,0x54);
I2CDATA1=Read_data(0xA1,0x02);
printf("%d\n\r",I2CDATA1);
}
}