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();
}
per1234
4,2782 gold badges23 silver badges43 bronze badges
asked Mar 24, 2015 at 18:45

2 Answers 2

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

answered Jul 26, 2015 at 7:21
0

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

answered Mar 27, 2015 at 23:20
1
  • 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. Commented Mar 28, 2015 at 7:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.