1

I'm using I2C and the Arduino Library (Wire) to communicate between two Arduinos, and my code isn't working. It's supposed to read in an int from the slave, write a value to the slave, then read back that value. I'm expecting "0 4", but i keep getting "0 0". Does this mean that the slave isn't registering the write?

Master code:

#include <Wire.h>

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

void ffsis()
{ 
  //request i
  Wire.requestFrom(2, 1);   
  int i = Wire.read(); 
  Serial.print(i); 

  //send n seed
  Wire.beginTransmission(2); 
  Wire.write(12);               
  Wire.endTransmission();   

  Serial.print(" ");

  //request n
  Wire.requestFrom(2, 1); 
  int n = Wire.read();
  Serial.print(n);
}

void loop()
{
  delay(100);
}

Slave code:

#include <Wire.h>

void setup()
{
  Wire.begin(2);                
  Wire.onRequest(requestEvents);
  Wire.onReceive(receiveEvents);
}

void loop(){}

int n = 0;

void requestEvents()
{
  Wire.write(n);
}

void receiveEvents(int howMany)
{  
  int n = wire.read();
}
1

int n = wire.read();

"Wire" should be capitalized.

Amplifying on Ken's reply, you have two variables called "n", and the global one should be declared volatile. Also, I2C deals in bytes, not ints, so preferably do this:

#include <Wire.h>

void setup()
{
  Wire.begin(2);                
  Wire.onRequest(requestEvents);
  Wire.onReceive(receiveEvents);
}

void loop(){}

volatile byte n = 0;

void requestEvents()
{
  Wire.write(n);
}

void receiveEvents(int howMany)
{  
  n = Wire.read();
}

In addition, the address 2 is a reserved address.

Address 0 is reserved as a "broadcast" address, addresses 1 to 7 are reserved for other purposes, and addresses 120 to 127 are reserved for future use.

You should choose an address in the range 8 to 119.

Reference

| improve this answer | |
0

Since you have int n in the receiveEvents function, you're making a new local variable, not using the global n variable.

| improve this answer | |
  • Your answer is correct but it could be made better if you provided further explanations on variable scopes in C/C++, and maybe post the updated code. – jfpoilpret Mar 28 '15 at 7:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy