Arduino I2C Wire communication slave send int to master problem

Hi, I'm building a big game project and there is a function that checks if the user hit the main target
and if he hit the target the function sends 1, if not so 0.
This function also sends the number of hits that the user hit badly. (hard to explain but the function sends 0 or higher)
The reason that I want to send from slave to master is that the master is also sending data to the slave and it's working fine and I don't want to ruin it.
Problem: I want to send from slave to master 2 ints that inside of int array and it's not working.
Note: I didn't put the full codes because the codes are pretty long, I have the library Wire the things that need to be in void setup...

This is the code of the function that gets the variables: (Slave code - Arduino Mega)

void add_or_remove_points(int checkHit, int otherTargetHit)
{
  int i = 0;
  arr[0] = checkHit;
  arr[1] = otherTargetHit;
  for (i = 0; i < SEND_DATA_ARR_SIZE; i++) //SEND_DATA_ARR_SIZE = 2
  {
    Wire.write(arr[i]);
  }
}

Note 1: This code is working but the problem is that the master device is getting 0 and 255 and not the ints that I need to send.
Note 2: In void setup() I wrote "Wire.onRequest(add_or_remove_points);"

This is part of the function of the Master device: (Arduino Uno)

void in_game()
{
  int i = 0;

  Wire.requestFrom(SLAVE_ADDR, ANSWER_SIZE * sizeof(int)); //ANSWER_SIZE = 2
  while (Wire.available())
  {
    answer_Arr[i] = Wire.read();
    i++;
  }
  Serial.print("checkHit: ");
  Serial.println(answer_Arr[0]);
  Serial.print("otherTargetHit: ");
  Serial.println(answer_Arr[1]);
}

Project_Slave.ino (7.11 KB)

Project_LCD_Master.ino (9.85 KB)

checkHit is an int and I guess arr[] is a byte array (narrowing conversion).
Anyway, post the whole code.

6v6gt:
checkHit is an int and I guess arr[] is a byte array (narrowing conversion).
Anyway, post the whole code.

ok, I upload the codes.
Hope you could help me (:

The function of your onRequest handler is: void add_or_remove_points(int checkHit, int otherTargetHit)
Where do the parameters come from ? Who puts a value in the checkHit and otherTargetHit ?

Your first problem is that you are attempting to send int data types without specifying the length to wireWrite().
See Wire - Arduino Reference

You need something like:

Wire.write(arr[ i ], 2 ) ; // assuming uint16_t (2 byte integer)

For the slave sending something to the master, see this example: Gammon Forum : Electronics : Microprocessors : I2C - Two-Wire Peripheral Interface - for Arduino

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