How do I read from I2C?


I am trying to read from arduino via I2C. for the writing I use wire .write, but for reading it seems to be hard - I cant just use,data) where 1 is the arduino address. It wants some kind of buffer thing to store the values. all I need is to read the last value the arduino sent and store it in a variable. does anyone know how to do this? thanks

For a buffer, you can just use a byte array.

    // Create 23 byte buffer
    final byte[] dataBuffer = new byte[23];
    // Do your write here
    // Read 23 bytes from I2C
    i2cDevice.readOnly(dataBuffer, 23);

Then you can use java.nio.ByteBuffer to convert the output to the actual types you need.

ok, I will give that a shot. I am looking for something simple - for the writing everyone said I need mad amounts of code - but its actually one line that really does the writing stuff. Thanks!

hmm now i am trying to just get the first byte from the array, and the robot quits when I try the following line
byte servoangle = i2cbuffer[1];
sorry for alll the stupid questions, I am quite a noob

The first byte of the array is element 0, not element 1.

YEEEAAAAHHHHH! I have spent all day today trying to send a 5 from the arduino to the rio, and it finally works! you wont belive how excited I am! thanks to all who helped!

1 Like

We have been trying to put together some basic files ,as we figure out new concepts, as starting points for future members.
If it helps here is what we have worked out for a starting point for I2C. Not sure if everything is best practice but it works.
Robot Code

package frc.robot;

import edu.wpi.first.wpilibj.I2C;
import edu.wpi.first.wpilibj.TimedRobot;

public class Robot extends TimedRobot {

  public static I2C arduino;
  public void robotInit() {
    arduino = new I2C(I2C.Port.kOnboard, 8); //Sets up the Arduino over I2C on port 8

  public void testInit() {

  public void testPeriodic() {
    byte[] sendData = "Gimme my data".getBytes(); //Data sent to the Arduino
    byte[] receiveData = new byte[12]; // Bytes requested from Arduino
    arduino.transaction(sendData, sendData.length, receiveData, receiveData.length); // Sends and Receives the Data to and from the Arduino
    System.out.println("Received: " + new String(receiveData, 0, receiveData.length)); //Prints the data received from the Arduino on the console

Arduino Code

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output


void loop() {

// function that executes whenever data is received from master
// this is an interrupt
void receiveEvent()
  Serial.print("Received: "); 
  while (Wire.available()) {
    char c =;

void requestEvent()
   Wire.write("From Arduino"); //Data to send to RoboRio - Character count needs to match byte[x] in Robot code