Monday, 1 December 2014

i2c device access from userspace


If the system supports hardware / software i2c and if the i2c-dev modules properly installed, the i2c devices appear in /dev .

for a system with four i2c buses :

crw-rw---T 1 root i2c 89, 0 Jan  1  1970 /dev/i2c-0
crw-rw---T 1 root i2c 89, 1 Jan  1  1970 /dev/i2c-1
crw-rw---T 1 root i2c 89, 2 Jan  1  1970 /dev/i2c-2
crw-rw---T 1 root i2c 89, 3 Jan  1  1970 /dev/i2c-3

note: the following configs are required in the kernel config

CONFIG_I2C=y
CONFIG_I2C_BOARDINFO=y
CONFIG_I2C_COMPAT=y
CONFIG_I2C_CHARDEV=y
CONFIG_I2C_HELPER_AUTO=y
CONFIG_I2C_SUNXI=y  (for allwinner devices)

There are some very useful diagnostic tools in i2c-tools package, so make sure that  they are installed:

 sudo apt-get -y install i2c-tools python-smbus  

with the device plugged into the i2c bus, first discover (and make sure it responds ) using i2c-detect.
This is a very good test to see if the device responds and the address.
The following is a  response from a device at address 0x34  in /dev/i2c-0 :


 root@BP-A20:~# i2cdetect -y 0
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- UU -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- -- -- 

reading in python : (reading 8 bytes )

 import smbus  
 import time  
    i2c = smbus.SMBus(0)  
    address = 0x34  
    status = i2c.read_i2c_block_data(address, 0x00, 8)  
    print status  

reading and wrting in c :

 #include <stdio.h>  
 #include <linux/types.h>  
 #include <linux/i2c-dev.h>  
 #include <fcntl.h>  
 int main (int argc, char *argv[])   
 {  
      int i, fd;  
      __u8 address = 0x34;  
      __u8 write_array[16] = {0};  
      fd = open("/dev/i2c-2", O_RDWR);  
      ioctl(fd, I2C_SLAVE, address);   
      if (read(fd, values,32) !=32)  
           printf("failed to read 32 bytes \n");  
      write_array[0] = 0x81;  
      write_array[1] = 0x00;  
      write(fd,write_array,2);  
      close (fd);  
 }  

No comments:

Post a Comment