Skip to content

I2C interfacing

Tushar Semwal edited this page Oct 18, 2017 · 4 revisions

The arguments passed to a predicate can take three forms - Input, Output or Both, and are denoted by symbols +, - and ? respect

  1. Connect the I2C device to the Raspberry Pi.
  2. Check if the device is connected properly using the command:
    $ sudo i2cdetect -y 1
    It should show something like:
    alt text
  3. The address of the I2C device that we interact with is the one that appears on the table in the above image.
  4. The commands that can be used to interact with the I2C device are:
    • wiringPiI2CSetup(+Addr,-Fd): To setup a connection with the device.
      - Addr: The address of the device obtained in step 2. Example: 0x68 (refer image in step 2).
      - Fd: The value returned by the setup command for furthur referencing to the device.

    • wiringPiI2CWriteReg8(+Fd,+Reg,+Val): To write a value in a particular register on the device.
      - Fd: The value of Fd obtained from the setup command.
      - Reg: Address of the register to which the value is to be written.
      - Val: The value to be written to the particular register (reg).

    • wiringPiI2CReadReg8(+Fd,+Reg,-Val): To read the output from a particular register on the device.
      - Fd: The value of Fd obtained from the setup command.
      - Reg: Address of the register from which the value is to be read.
      - Val: The value stored in the register returned by the command.

Note: wiringPiI2CReadReg16(+Fd,+Reg,-Val) and wiringPiI2CWriteReg16(+Fd,+Reg,+Val) are also available.


Example for IMU: 1. Follow the first three steps of I2C to connect the IMU to Raspberry pi. 2. Now once we get the address we type the following commands:
?- wiringPiI2CSetup(0x68, Fd). --returns the value of Fd (4 in this case) to be used in later commands.
?- wiringPiI2CWriteReg8(4,0x6b,0x00). --sets a value to particular registers (refer to IMU datasheet) to awaken the device.
?- wiringPiI2CWriteReg8(4,0x6c,0x00). --sets a value to particular registers to awaken the device.
?- wiringPiI2CWriteReg8(4,0x74,0x00). --sets a value to particular registers to awaken the device.
?- wiringPiI2CReadReg8(4,0x43,T). --returns the value of stored in 0x43 register.