0

While reading the linux kernel documentation on I2C device drivers from user space, I noticed that ioctl() is used to "put the address on the bus".

So a typical workflow as described is:

  1. Open /dev/i2c-N and call ioctl() on it. By doing so you "specify with what device address you want to communicate"
  2. Followed by a read or write operation to i2c_smbus_write_byte_data() or i2c_smbus_read_byte_data().

Then it occurred to me that if I am building a system which has more than one device connected to that bus (i2c-N), and I have different threads that will use this device driver, there must be a mutex lock on the file descriptor that wraps the ioctl() + read()/write() operation, to ensure that the read/write is being done on the intended device.

Is this reasoning correct or have I misunderstood something?

0andriy
  • 4,183
  • 1
  • 24
  • 37
Sam Hammamy
  • 10,819
  • 10
  • 56
  • 94
  • No, unless you have more than one thread to access **the same** device. The idea is that each I²C slave device you want to access to needs the `open()`->`ioctl()`->`write()`/`read()`->`close()`. So you will have a _file descriptor_ uniquelly mapped to the needed I²C slave device. I.o.w. if you want to use the same _file descriptor_ you got from `open()` from different threads / tasks you need synchronization. Otherwise it's not necessary. – 0andriy Jun 01 '23 at 16:10
  • if I understood your point correct, you are saying that with each command, the sequence should be: open()->ioctl()->write()/read()->close(). isn't that wasteful? couldn't I keep the `fd` around for the lifetime of the application? – Sam Hammamy Jun 01 '23 at 16:34
  • I suppose I get your point, since you generally know how many devices are attached to your system. But in the case of robotics, it maybe that you want to add an additional sensor (like IMU sensor) without recompiling. – Sam Hammamy Jun 01 '23 at 16:36
  • You keep one file descriptor per one active I2C slave device. I showed you the general idea. You may open and close, or keep it open for a longer time — it’s all up to your design. – 0andriy Jun 02 '23 at 12:37

0 Answers0