图一 : IIC引脚配置为IIC模式
图二: IIC控制寄存器
图三 cortex-A8 内部IIC相关寄存器框图
图四: IIC状态寄存器
图5 LM75 外围电路
读取LM75温度的几个步骤:
1 . 发送从机地址
2. 配置模式,LM74有四种模式,我们这里只选第一种只读模式
3.再次发送从机地址,选择LM75芯片后即可等待LM75回送数据,这时芯片会回送主机两次数据第一次是主要值,第二次是小数部分,最小精度到0.5
注意:每一次收发数据都要进行应答,以保证数据的有效性
typedef struct {
unsigned int I2CCON0;
unsigned int I2CSTAT0;
unsigned int I2CADDR0;
unsigned int I2CDS0;
unsigned int I2CLC0;
} I2c0_type; //I2C相关寄存器
typedef struct {
unsigned int GPDCON
unsigned int GPDDAT;
unsigned int GPDPULL;
unsigned int GPDDRV;
unsigned int GPDPDNCON;
unsigned int GPDPDNPULL;
}gpd_tydef; //连接从机设备GPIO端口
#define I2C0 (* (volatile I2c0_type *)0xEC100000)
#define GPD (* (volatile gpd_tydef *)0xE0300080)
#define mode 0x00 //设置读模式
#define config 0x01 //设置配置模式
#define HYST 0x02 //设置(HYST读写)模式
#define T 0x03 //设置OS读写模式
void cfg_gpio(void)
{
GPD.GPDCON = (GPD.GPDCON&~((0x0f<<12)|(0x0f<<16)) + (2<<12) | (2<<16)); //配置GPIO为I2C
}
void delay(void) //延时函数
{
unsigned int delay;
for(delay = 0;delay < 0x1fffff;delay ++);
}
int read_data_one() //读模式,第一阶段,发送器件地址及要读取的地址
{
I2C0.I2CDS0 = 0x90; //Lm75 slave device address
I2C0.I2CSTAT0 = 0xf0; //Master trans mode ,START ,ENABLE RX/TX
while(!(I2C0.I2CCON0&(1<<4))); //wait until the interrupt pending bit is cleared
I2C0.I2CDS0 = mode; //the datas of slave device address which we need to read
I2C0.I2CCON0 = 0xef; //clear the interrupt pending bit ,enable ack bit ,Prescale :512 ,RX/TX,interrupt enable
while(!(I2C0.I2CCON0&(1<<4))); //wait until the interrupt pending bit is set
delay();
return 0;
}
int read_data_two() //读模式,第二阶段,发送器件地址,接收从机的数据
{
int temp,low,high;
I2C0.I2CDS0 = 0x90; //Lm75 slave device address
I2C0.I2CSTAT0 = 0xb0; //Master receive mode ,
I2C0.I2CCON0 = 0xef;
while(!(I2C0.I2CCON0&(1<<4)));
I2C0.I2CCON0 = 0xef;
delay();
high = I2C0.I2CDS0; //receive the high 8bit datas of the LM75
I2C0.I2CCON0 = 0x2f; //regardless of ACK ,clear the interrupt pending bit
delay();
low =I2C0.I2CDS0;
I2C0.I2CSTAT0 = 0x90; //receive the low 8bit datas of the LM75
I2C0.I2CCON0 = 0xef; //clear the interrupt pending bit ,enable ack bit ,Prescale :512 ,RX/TX,interrupt enable
return ((high << 8) | low); //return the 16bit datas of temp
}
int main()
{
int temp,low,high;
cfg_gpio();
while(1)
{
read_data_one();
temp = read_data_two();
hign = temp>>8;
low = temp &0xff;
printf("temp = %d.%d\n",high,((low>>7) == 0 ? 0:5));
}
return 0;
}