Arduino - Example Code for Setting Up I2C Writes and Reads

This is a quick example code for Arduino to write and read I2C from a register based device. This is single byte writing and single byte reading.

Full Code Snippet:

#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(400000L); //100kHz on SCL, 400kHz - 400000L
}

void loop() {

  int read_value;

  read_value = i2c_read(0x20, 0x00);
  read_value = i2c_read(0x20, 0x01);

  i2c_write(0x20, 0x06, 0x00); 
  i2c_write(0x20, 0x07, 0x00); 

}

void i2c_write(int i2c_address, int register_address, int data) {
  Wire.beginTransmission(i2c_address);
  Wire.write(register_address);
  Wire.write(data);
  Wire.endTransmission();
}

int i2c_read(int i2c_address, int register_address) {
  int val = 0x00;
  Wire.beginTransmission(i2c_address);
  Wire.write(register_address);
  Wire.endTransmission();
  Wire.requestFrom(i2c_address, 1);
  //check to see if there is a byte requested, if not then the device is not connected.

  if (Wire.available() == 0) {
    Serial.println("Error");
  } else {
    while (Wire.available()) {
      val = Wire.read();
      Serial.println("Good Read");
    }
  }
  return val;
}

#Includes:

The only #include is the <Wire.h> library for I2C

Setup ():

Initialize the serial prompt with Serial.begin(115200); (115200 baud rate)

Wire.begin() - initializes the I2C drivers

Wire.setClock(400000L) - sets I2C SCL frequency to 400 kHz

Loop ():

Example loop() function. Initialize a read value

read from target address 0×20, register 0×00

read from target address 0×21, register 0×01

write to target address 0×20, register 0×06, data 0×00

write to target address 0×20, register 0×07, data 0×00

i2c_write():

set up the i2c_write() function. Takes in parameters i2c target address, register address, and data to place in the register

begin with a start condition - Wire.beginTransmission()

send the register address

send the data to place inside the register

send stop condition through Wire.endTransmission()

i2c_read():

Setup the read function

define a value to return 0×00

send start bit - Wire.beginTransmission()

send register address

send stop bit - Wire.endTransmission();

request to read from the device 1 byte

run an if / else statement to check if the read was bad “error” or good “good read”

return the i2c data

Previous
Previous

What Does the “R” Mean in TCAL6416R?

Next
Next

How Voltage Level Translation Works - LSF0102 - PCA9306