Chinaunix首页 | 论坛 | 博客
  • 博客访问: 418186
  • 博文数量: 99
  • 博客积分: 65
  • 博客等级: 民兵
  • 技术积分: 1012
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-20 16:30
个人简介

linux kernel 工程师

文章分类

全部博文(99)

文章存档

2018年(5)

2017年(12)

2016年(27)

2015年(10)

2014年(43)

2012年(2)

我的朋友

分类: LINUX

2014-03-19 13:42:42

本测试程序通过 ioctl(fd, I2C_SMBUS, &ioctl_data)访问smbus。

#include
#include
#include
#include
#include
#include
#include

#define I2C_DEV    "/dev/i2c-0"
#define I2C_24CXX_ADDR  0x50 /* 0x58 for 0x24c64 or 0x50 for 24c128*/
#define REG_OFFSET    0x20
#define WRITE_VALUE         0x5a

#if 0
#define I2C_SMBUS_READ 1
#define I2C_SMBUS_WRITE 0

union i2c_smbus_data {
 __u8 byte;
 __u16 word;
 __u8 block[I2C_SMBUS_BLOCK_MAX + 2]; /* block[0] is used for length */
          /* and one more for user-space compatibility */
};

struct i2c_smbus_ioctl_data {
 __u8 read_write;
 __u8 command;
 __u32 size;
 union i2c_smbus_data __user *data;
};
#endif

int
main()
{
 union i2c_smbus_data data;
 struct i2c_smbus_ioctl_data ioctl_data = {0};
 unsigned long addr = I2C_24CXX_ADDR;
 int fd;
 int rc;
 
 fd = open(I2C_DEV, O_RDWR);
 if (fd < 0) {
  printf("failed to open %s\n", I2C_DEV);
  return (-1);
 }

 if (ioctl(fd, I2C_SLAVE, addr) < 0) {
         printf("ioctl, I2C_SLAVE failed: %d.\n", errno);
         return (-1);
     }
 
 /* test reading and writing registers in 24CXX */

 /* read from Configuration Register (0x03) */
 data.byte = 0;
 ioctl_data.read_write = I2C_SMBUS_READ;
 ioctl_data.command = REG_OFFSET;
 ioctl_data.size = I2C_SMBUS_BYTE_DATA;
 ioctl_data.data= &data;
 
 rc = ioctl(fd, I2C_SMBUS, &ioctl_data);
 if (rc < 0) {
  printf("read, I2C_SMBUS failed: %d.\n", errno);
  close(fd);
  return (-1);
 }

 printf("value is: 0x%02x\n", data.byte);

 /* write 0x5a into Configuration Register (0x03) */
 printf("write 0x%02x at 0x%02x\n", WRITE_VALUE, REG_OFFSET);
 
 data.byte = WRITE_VALUE;
 ioctl_data.read_write = I2C_SMBUS_WRITE;
 ioctl_data.command = REG_OFFSET;
 ioctl_data.size = I2C_SMBUS_BYTE_DATA;
 ioctl_data.data= &data;
 rc = ioctl(fd, I2C_SMBUS, &ioctl_data);
 if (rc < 0) {
  printf("write, I2C_RDWR failed: %d.\n", errno);
  close(fd);
  return (-1);
 }

 

 sleep(1);
 /* read out again to check */
 printf("read out at 0x%02x\n",REG_OFFSET);
 
 data.byte = 0;
 ioctl_data.read_write = I2C_SMBUS_READ;
 ioctl_data.command = REG_OFFSET;
 ioctl_data.size = I2C_SMBUS_BYTE_DATA;
 ioctl_data.data = &data;
 rc = ioctl(fd, I2C_SMBUS, &ioctl_data);
 if (rc < 0) {
  printf("read, I2C_RDWR failed: %d.\n", errno);
  close(fd);
  return (-1);
 }

 if (data.byte != WRITE_VALUE)
  printf("write failed. ");
 else
  printf("write success. ");

 printf("Config_reg: 0x%02x\n", data.byte);

 sleep(1);

 close(fd);

 return (0);
}

阅读(6698) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~