这篇中将围绕韦东山LINUX第二部分教程源码,对IIC协议进行程序实现上的分析。
/* I2C registers */
#define IICCON (*(volatile unsigned *)0x54000000) // IIC control#define IICSTAT (*(volatile unsigned *)0x54000004) // IIC status#define IICADD (*(volatile unsigned *)0x54000008) // IIC address#define IICDS (*(volatile unsigned *)0x5400000c) // IIC data shift#define IICLC (*(volatile unsigned *)0x54000010) //IIC multi-master line controlunsigned char at24cxx_read(unsigned char address)
{ unsigned char val; printf("at24cxx_read address = %d\r\n", address); i2c_write(0xA0, &address, 1); printf("at24cxx_read send address ok\r\n"); i2c_read(0xA0, (unsigned char *)&val, 1); printf("at24cxx_read get data ok\r\n"); return val;}void at24cxx_write(unsigned char address, unsigned char data){ unsigned char val[2]; val[0] = address; val[1] = data; i2c_write(0xA0, val, 2);}首先分析功能实现函数:读与写函数,其中读函数中,先实现发送地址再进行读数据。
/*
* 主机发送 * slvAddr : 从机地址,buf : 数据存放的缓冲区,len : 数据长度 */void i2c_write(unsigned int slvAddr, unsigned char *buf, int len){ g_tS3C24xx_I2C.Mode = WRDATA; // 写操作 g_tS3C24xx_I2C.Pt = 0; // 索引值初始为0 g_tS3C24xx_I2C.pData = buf; // 保存缓冲区地址 g_tS3C24xx_I2C.DataCount = len; // 传输长度 IICDS = slvAddr; IICSTAT = 0xf0; // 主机发送,启动 /* 等待直至数据传输完毕 */ while (g_tS3C24xx_I2C.DataCount != -1);}/*
* 主机接收 * slvAddr : 从机地址,buf : 数据存放的缓冲区,len : 数据长度 */void i2c_read(unsigned int slvAddr, unsigned char *buf, int len){ g_tS3C24xx_I2C.Mode = RDDATA; // 读操作 g_tS3C24xx_I2C.Pt = -1; // 索引值初始化为-1,表示第1个中断时不接收数据(地址中断) g_tS3C24xx_I2C.pData = buf; // 保存缓冲区地址 g_tS3C24xx_I2C.DataCount = len; // 传输长度 IICDS = slvAddr; IICSTAT = 0xb0; // 主机接收,启动 /* 等待直至数据传输完毕 */ while (g_tS3C24xx_I2C.DataCount != 0);}