WIRE.H Libary Wire.Write

If I send the text "12345678" with the command Wire.Write it's received as "123456756"
The last character is always converted to it's decimal equilant.
I can't figure out why it's doing this.
It doesn't matter how long the string is.
Why does it do that and how can I make it show the character?

Sender code:
Wire.beginTransmission(4);
Wire.Write("12345678");
Wire.endTransmission();

Receiver code:
Wire.begin(4);
Wire.onReceive(receiveEvent);
Serial.begin(9600);

Please post 2 complete sketches that show the problem, using code tags when you do

In my case, "12345678" is well received. Compare your codes with my sketches and find the flaws in your codes:
Master Sketch:

#include<Wire.h>

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

void loop() 
{
  Wire.beginTransmission(4);
  Wire.write("12345678");
  Wire.endTransmission();
  delay(1000);
}

Slave Sketch:

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

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

void loop()
{
  if(flag == true)
  {
    Serial.println(myData);
    flag = false;
  }
}

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

Slave Monitor:

23:44:02.810 -> 12345678
23:44:03.793 -> 12345678
23:44:04.825 -> 12345678
23:44:05.825 -> 12345678

Just found the problem, I copied a sample code from arduino.cc which read the last character as integer. My fault!! Didn´t check the code :frowning:

Please, post the codes that are under void receiveEvent(){} function to see how the last character has been read as an int.

void receiveEvent(int howMany)
{
  while(1 < Wire.available()) // loop through all but the last
  {
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

Just copied sample code from arduino.cc, didn't read the code...

1 Like

Nothing wrong with the codes. The author has read the first seven bytes and presented their ASCII forms on the Serial Monitor. So, it appeared as 1234567. The last byte (which has arrived as 0x38) has been displayed in decimal-base, and it has appeared as 56 on the Serial Monitor.

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