Python based I2C functions for Raspberry Pi

Let’s see basic Python based I2C functions which are frequently used for I2C communication on Raspberry Pi.

While developing program for Raspberry Pi I2C communication in python, we can use SMBus library package which has great support to access I2C devices. So, we should add SMBus support for Python by using apt packet manager,

sudo apt-get install python-smbus

Python based I2C Functions:

Import SMBus

  • To access I2C bus on Raspberry Pi using SMBus Python module, import SMBus module as follows.

import smbus

  • create object of SMBus class to access I2C based Python function.

<Object name> = smbus.SMBus(I2C port no.)

I2C port no : I2C port no. i.e. 0 or 1

  • Example – Bus = smbus.SMBus(1)

Now, we can access SMBus class with Bus object.

Bus.write_byte_data(Device Address, Register Address, Value)

  • This function is used to write data to the required register.

Device Address : 7-bit or 10-bit device address

Register Address : Register address to which we need to write

Value : pass value which needs to write into the register

  • Example – Bus.write_byte_data(0x68, 0x01, 0x07)

Bus.write_i2c_block_data(Device Address, Register Address, [value1, value2,….])

  • This function is used to write a block of 32 bytes.

Device Address : 7-bit or 10-bit device address

Register Address : Register address to which we need to write data

Value1 Value2…. : write a block of bytes to the required address

  • Example – Bus.write_i2c_block_data(0x68, 0x00, [0, 1, 2, 3, 4, 5]) # write 6 bytes of data from 0 address.

Bus.read_byte_data(Device Address, Register Address)

  • This function is used to read data byte from required register.

Device Address : 7-bit or 10-bit device address

Register Address : Register address from which we need to read data

  • Example – Bus.read_byte_data (0x68, 0x01)

Bus.read_i2c_block_data(Device Address, Register Address, block of bytes)

  • This function is used to read a block of 32 bytes.

Device Address – 7-bit or 10-bit device address

Register Address – Register address from which we need to read data

Block of Bytes      – readno of bytes from the required address

  • Example – Bus.read_i2c_block_data(0x68, 0x00, 8) # returnvalue is a list of 6 bytes
Short URL: http://tinyurl.com/yc4ufrg3
   Send article as PDF   

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Do NOT follow this link or you will be banned from the site!