嵌入式Linux操作I2C设备,我们一般会在内核态编写I2C驱动程序。另外还能在用户空间编写I2C程序,下面介绍相关代码的实现。
i2c-dev框架在内核中封装了I2C通信所需要的所有通信细节,I2C适配器会在/dev目录下创建字符设备,例如:/dev/i2c-0,通过系统调用操作/dev/i2c-0就可以实现与I2C设备通信。
一、I2C适配器操作函数
下面介绍如何在用户空间打开I2C适配器,并使用I2C适配器读写I2C设备。
1、打开I2C适配器
调用open系统调用打开/dev/i2c-n文件
/* 打开字符设备 */
s32 hal_i2c_open(u32 u32I2cIdx, s32 *ps32Fd)
{
s32 s32Fd = 0;
s8 s8Fname[128] = {0,};
sprintf((char *)s8Fname, "/dev/i2c-%u", u32I2cIdx);
s32Fd = open((char *)s8Fname, 0);
if (0 >= s32Fd){
LOG_WARN("i2c open %s s32Fd=%d,retry it\n",s8Fname,s32Fd);
s32Fd = open((char *)s8Fname, 0);
if (0 >= s32Fd){
LOG_ERR("Open %s error, s32Fd %d,u32I2cIdx:0x%X!\n",s8Fname, s32Fd,u32I2cIdx);
return -1;
}
}
*ps32Fd = s32Fd;
return 0;
}
/* 关闭字符设备 */
s32 hal_i2c_close(s32 s32Fd)
{
if(0 >= s32Fd){
LOG_ERR("failed !\n");
return -1;
}
close(s32Fd);
return 0;
}
2、I2C适配器读写
通过ioctl去读写I2C适配器从而与I2C设备通信
/*
*****************************************************************************************
* 函 数 名: hal_i2c_read
* 功能说明: I2C读
* 形 参: s32Fd : I2C节点
* u16DevAddr : 设备地址
* u16RegAddr : 寄存器地址
* u16RegLen : 寄存器长度
* pu8Buf : 读取数据buf
* u16DataLen : 需要读取数据长度
* 返 回 值: 返回0:OK
* 其他: ERROR
*****************************************************************************************
*/
s32 hal_i2c_read(s32 s32Fd, u16 u16DevAddr, u16 u16RegAddr,u16 u16RegLen, u8 *pu8Buf, u16 u16DataLen)
{
u8 u8Buf[2] = {0,};
struct i2c_rdwr_ioctl_data rdwr = {0};
struct i2c_msg msg[2] = {0};
if(I2C_DEVICE_REG_LEN_2BIT == u16RegLen){