S3C2440在linux系统下读写IIC设备24c08

这个程序示例展示了如何在Linux环境下通过I2C总线与地址为0x50的设备进行通信,进行EEPROM的数据读写操作。首先打开I2C设备文件,然后设置I2C从设备地址,接着写入数据到指定寄存器,并最后读取数据。如果在读写过程中发生错误,程序会进行错误处理并退出。
摘要由CSDN通过智能技术生成

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>

//#include </linux/i2c-dev.h>

#define I2C_SLAVE 0x0703 /* Use this slave address */

int main(int argc ,char **argv)
{

  #define IIC_Path  "/dev/i2c/0"

  int fd;
  int addr = 0x50; /* The I2C address */
  int res;
  char i;
  char length;
  char register_addr = 0x00;   
  char write_buf[10];
  char read_buf[10];

  
  //snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
  fd = open(IIC_Path, O_RDWR);
  if (fd < 0) 
  	{
	 /* ERROR HANDLING; you can check errno to see what went wrong */
	  printf("failed open %s  \n",IIC_Path);	
	  exit(1);
    }	  

  if (ioctl(fd, I2C_SLAVE, addr) < 0) 
  	{
	 /* ERROR HANDLING; you can check errno to see what went wrong */
     printf("failed ioctl set addr\n");	  
	 exit(1);
    }

/* Using I2C Write, equivalent of 
   i2c_smbus_write_word_data(file, register, 0x6543) */
write_buf[0] = register_addr;
write_buf[1] = 0x43;
write_buf[2] = 0x65;
write_buf[3] = 0x11;
write_buf[4] = 0x22;
length=5;


if (write(fd, &write_buf[0], length) !=length) 
	{
  		/* ERROR HANDLING: i2c transaction failed */
	  printf("failed to write data to EEPROM \n");	  	
	}


//char buf[10];
	//char sendbuffer1[2];

	write_buf[0]=register_addr;

	//write_buf[1]=register_addr;

	write(fd,&write_buf[0],1);

	//res=read(fd,buff,count);
	
/* Using I2C Read, equivalent of i2c_smbus_read_byte(file) */
  if (read(fd, &read_buf[0], length) != length) 
  	{
	 /* ERROR HANDLING: i2c transaction failed */
     printf("failed to read data from EEPROM \n");
    }
	else 
	{
		  /* buf[0] contains the read byte */
     for(i=0;i<length;i++)
         printf("read read_buf[%d]=%x\n",i,read_buf[i]); 
	}

close(fd);
return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值