Linux I2C通讯应用程序

I2C通讯通常用作寄存器设置,本文在linux平台上 实现传输255字节数据,主要是发送指令、传输文件(包括bin文件)等

一、打开I2C设备

#define I2C_FILE_NAME "/dev/i2c-1"

if ((i2c_file = open(I2C_FILE_NAME, O_RDWR)) < 0) {
	perror("Unable to open i2c control file");
	return 1;
}

二、I2C写数据

static int I2C_wirte(int file, unsigned char addr, unsigned char *value, int len) 
{
    struct i2c_rdwr_ioctl_data packets;
    struct i2c_msg messages[1];
 
    messages[0].addr  = addr;
    messages[0].flags = 0;
    messages[0].len   = len;
    messages[0].buf   = value;
 
    /* Transfer the i2c packets to the kernel and verify it worked */
    packets.msgs  = messages;
    packets.nmsgs = 1;
    if(ioctl(file, I2C_RDWR, &packets) < 0) {
    	perror("Unable to send data");
    	return 1;
    }
 
    return 0;
}

三、I2C读数据

int I2C_read(int file, unsigned char addr, unsigned char *value, int len_write, int len_read) 
{
	unsigned char *inbuf, *buf_write;
	struct i2c_rdwr_ioctl_data packets;
	struct i2c_msg messages[2];

	/* messages[0] : write step */
	messages[0].addr  = addr;
	messages[0].flags = 0;
	messages[0].len   = len_write;
	messages[0].buf   = value;

	/* messages[1] : read step */
	messages[1].addr  = addr;
	messages[1].flags = I2C_M_RD/* | I2C_M_NOSTART*/;
	messages[1].len   = len_read;
	messages[1].buf   = value;   //读到数据存放value中

	/* Send the request to the kernel and get the result back */
	packets.msgs      = messages;
	packets.nmsgs     = 2;
	if(ioctl(file, I2C_RDWR, &packets) < 0) {
		perror("Unable to send data");
		return 1;
	}

	return 0;
}

代码链接:https://download.csdn.net/download/m0_50136807/87732706?spm=1001.2014.3001.5503 

MCU的I2C配置成从地址,可以通过linux平台向MCU发送指令或者文件,其中MCU配置成I2C slave的链接如下:

https://blog.csdn.net/m0_50136807/article/details/130392415?spm=1001.2014.3001.5501

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sorry0619

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值