#include <Wire.h>

  //----- INITIALISE I2C -----
  Wire.begin();



  //----- WRITE TO I2C DEVICE -----
  unsigned char value = 1;
  Wire.beginTransmission(0x5a);
  Wire.write(value);
  uint8_t Result = Wire.endTransmission(true); //true=send stop
  //Result: 0=success, 1=tx buff overrun, 2=NACK on address tx, 3=NACK on data tx, 4=other error 
  
  
  //----- READ FROM I2C DEVICE -----
  Wire.requestFrom(0x5a, 2);     //Address, no of bytes
  uint8_t BytesReceived = Wire.available();    //The slave can send less than was requested
  //No need to send stop as done automatically
  if (BytesReceived >= 2)
  {
    byte LSB = Wire.read();
    byte MSB = Wire.read();
  }


  //----- WRITE THEN READ I2C DEVICE -----
  unsigned char value;
  Wire.beginTransmission(0x5a);
  Wire.write(value);
  if (Wire.endTransmission(false) == 0) //false=send restart (IMPORTANT-THIS ENDTRANSMISSION DOES NOT SEND STOP!).  0=success, 1=tx buff overrun, 2=NACK on address tx, 3=NACK on data tx, 4=other error 
  {
    Wire.requestFrom(0x5a, 2);     //Address, no of bytes
    uint8_t BytesReceived = Wire.available();    //The slave can send less than was requested
    //No need to send stop as done automatically
    if (BytesReceived >= 2)
    {
      byte LSB = Wire.read();
      byte MSB = Wire.read();
    }
  }
  else
  {
    Wire.endTransmission(true); //true=send stop
  }
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

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