I2C

I2C communication, reading and writing registers.

Scan Addresses


import i2c_bus

# i2c0 = i2c_bus.easyI2C(i2c_bus.PORTA, addr, freq=400000)

i2c0 = i2c_bus.easyI2C((sda, scl), 0x68, freq=400000)

# True or False
if i2c0.available():
    print(i2c0.available())
    # return a list
    print(i2c0.scan())

Read/Write Registers v1


# Write 1 byte to reg
i2c0.write_u8(reg, data)

# Write 2 bytes continuously to reg
i2c0.write_u16(reg, data, byteorder='big')

# Write 4 bytes continuously to reg
i2c0.write_u32(reg, data, byteorder='big')

# Read 1 byte from reg
i2c0.read_u8(reg)

# Read 2 bytes continuously from reg
i2c0.read_u16(reg, byteorder='big')

# Read 4 bytes continuously from reg
i2c0.read_u32(reg, byteorder='big')

# Read N bytes continuously
i2c0.read(num)

# Read N bytes from reg continuously
i2c0.read_reg(reg, num)

# Endianness
# byteorder = "little" or "big" (default)

Read/Write Registers v2


# format_type
# UINT8LE
# UINT16LE
# UINT32LE
# INT8LE
# INT16LE
# INT32LE
# UINT8BE
# UINT16BE
# UINT32BE
# INT8BE
# INT16BE
# INT32BE

# Write 1 data of specified type to reg
i2c0.write_mem_data(reg, data, format_type)

# Write 1 data of specified type
i2c0.write_data(data, format_type)

# Write data from List continuously to reg
i2c0.write_list(data)

# Write N data of specified type continuously to reg
i2c0.write_mem_list(reg, data, num)

# Read 1 data of specified type continuously
i2c0.read_data(num, format_type)

# Read N data of specified type from reg continuously
i2c0.read_mem_data(reg, num, format_type)

Example Program

  • Read temperature and humidity values from DHT12 sensor
import i2c_bus
import time

i2c0 = i2c_bus.easyI2C(i2c_bus.PORTA, 0x5C, freq=400000)
while True:
  hum = i2c0.read_mem_data(0x00, 2, i2c_bus.INT8LE)
  print(hum[0]+hum[1]*0.1)
  wait_ms(100)
  tem = i2c0.read_mem_data(0x02, 2, i2c_bus.INT8LE)
  print(tem[0]+tem[1]*0.1)
  wait_ms(100)
On This Page