How to transfer data using Wire.h header and i2c protocol? Below the code it's only transferring address and not transferring data. Help me

I'm taking Clock data(SCL) from A5 and SDA from A4 port in Arduino UNO board. The code below is used to transfer 8 bit signal and illustrating signal on oscilloscope. The problem is that the 8 bit data vis not transferring and only transferring address bits. Please help me.

#include <Wire.h>

void setup()
{
  
Wire.begin();

 // join i2c bus (address optional for master)

}
//byte x = 0;

void loop(){
  
Wire.beginTransmission(170);
  Wire.write(1);
Wire.write(0x07); // sends five bytes
Wire.endTransmission(); // stop transmitting

/*x++;        // increment value
  if (x == 127) { // if reached 64th position (max)
    x = 0;    // start over from lowest value
  }*/
delay(10);
}

The transmission is aborted because no slave responded.
For testing purpose a broadcast (address 0) may work?

1 Like

1. Connect UNO and NANO/UNO as per following diagram using I2C Bus. Don't forget to install the pull-up resistors.
i2cUnoUno

2. Upload the following sketch (your one) in UNO-Master.

#include <Wire.h>

void setup()
{
    Wire.begin();
}

void loop()
{
  Wire.beginTransmission(170);
  Wire.write(1);
  Wire.write(0x07); // 
  Wire.endTransmission(); // stop transmitting
  delay(1000);  //test interval
}

3. Upload the following sketch in NANO/UNO-Slave.

#include <Wire.h>
volatile bool flag = false;
byte myData[2];

void setup()
{
  Serial.begin(9600);
  Wire.begin(170);
  Wire.onReceive(receiveEvent);
}

void loop()
{
  if(flag == true)
  {
    Serial.println(myData[0]); //shows: 1 (01)
    Serial.println(myData[1]); //shows: 7 (07)
    flag = false;
  }
}

void receiveEvent(int howMany)
{
  for(int i = 0; i<howMany; i++)
  {
    myData[i] = Wire.read();
  }
  flag = true;
}

4. Check that Serial Monitor of Slave shows: 1 and 7.

1 Like

thank you :slightly_smiling_face:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.