Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using I2C and the Arduino Library (Wire) to communicate between two Ardunios, and my code isn't working. It's supposed read in an int from the slave, write a value to the slave, then read back that value. Im 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();
}
share|improve this question

migrated from stackoverflow.com Mar 26 '15 at 15:55

This question came from our site for professional and enthusiast programmers.

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

share|improve this answer

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

share|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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.