嵌入式linux应用读写i2c示例

这里分享一个嵌入式linux读写24c02的i2c程序
ioctl函数的使用:
原型:struct ioctl(struct file *file,unsigned int cmd,unsigned long arg);
cmd有I2C_SLAVE,I2C_SLAVE_FORCE,I2C_TENBIT,I2C_SET_SPEED几个选项;
I2C_SLAVE:对应的arg取值为I2C从机地址,用来设定I2C从机地址;
I2C_SLAVE_FORCE:对应的arg取值为I2C从机地址,用来修改I2C从机地址;
I2C_TENBIT:对应的arg取值为0:从机地址为7 bit;对应的arg取值为1:从机地址为10bit。用来指定I2C从机地址的位数;
I2C_SET_SPEED:对应的arg取值为I2C总线控制器分频值。用来设置I2C总线控制器时钟频率;

常用设置设置I2c从机地址为0xA0,如果选用at24c08设备,那么从机是7 bit地址,所以要右移1位,指定从机地址为7 bit,

i2c.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>

static int fd = 0;

//初始化i2c
//i2c_dev设备文件 i2c_addr 设备地址 
//返回 0
int i2c_init(char *i2c_dev, unsigned char i2c_addr)
{
	int res = 0;
	
	fd = open(i2c_dev, O_RDWR);
	if(fd < 0)
	{
		printf("[%s]:[%d] open i2c file error\r\n", __FUNCTION__, __LINE__);
		return -1;
	}
	res = ioctl(fd,I2C_TENBIT,0);				   //7位模式 
	res = ioctl(fd,I2C_SLAVE, (i2c_addr >> 1));    //设置I2C从设备地址
	
	return res;
}

//读i2c
//buf数据 len长度 
//返回 实际读取的长度 
int i2c_readNbyte(unsigned char *buf, int len)
{
	int res = 0;
	
	res = read(fd, buf,len);
	return res;
}

//写i2c
//buf数据 len长度 
//返回 实际写的长度 
int i2c_writeNbyte(unsigned char *buf, int len)
{
	int res = 0;
	
	res = write(fd, buf,len);
	return res;
}

int i2c_readReg(unsigned int reg_addr, unsigned char *buf, int len)
{
	int res = 0;
	unsigned char buff[2];
	
	buff[0] = reg_addr >> 8;
	buff[1] = reg_addr & 0xff;
	write(fd, buff, 2);
	res = read(fd, buf,len);
	
	return res;
}

int i2c_writeReg(unsigned int reg_addr, unsigned char *buf, int len)
{
	int res = 0,i;
	unsigned char *buff = 0;
	
	buff = (unsigned char *)malloc((len+2));
	buff[0] = reg_addr >> 8;
	buff[1] = reg_addr & 0xff;
	for(i = 0; i < len; i++)
		buff[(i+2)] = buf[i];
	res = write(fd, buff, (len+2));
	free(buff);
	
	return res;
}

int i2c_close()
{
	close(fd);
	return 0;
}

main.c

#include <stdio.h>
#include "i2c.h"

int main()
{
	unsigned char buff[2] = {0x12,0x34};
	
	i2c_init("/dev/i2c-1",  0xa0);
	i2c_writeNbyte(buff, 2);
	i2c_readNbyte(buff, 2);
	printf("%x\n",buff[1]);
	i2c_close();
	
	return 0;
}
  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值