Pages: [1]   Go Down
Author Topic: I2C communication  (Read 481 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 7
Life is beautiful ....
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi, I run across a problem about I2C communication .
 
When I send sevrial (at least two byte) byte datas

from slave board to main board at the same time ,the

main board only can read the first byte ,can’t receive
 
the rest of it .Here is the code:
 
main_read:
 
Code:
#include <Wire.h>
 
byte x,y;
 
void setup()
 
{
 
    Wire.begin(1);
 
    Serial.print(9600);
 
}
 
void loop()
 
{
 
     Wire.requestFrom(1,2) ;
 
     while(Wire.available()>0)
 
     {
 
         x=Wire.read();
 
         y=Wire.read();
 
     }
 
 
 
     Serial.println(x);
 
     Serial.println(y);
 
}

Slave_write:
Code:

#include <Wire.h>
 
byte a=12,b=56;
 
void setup()
 
{
 
      Wire.begin(1);  

      Wire.onRequest(requestEvent);
 
      Serial.begin(9600);        

}
 
void loop()
 
{

  Serial.println("Hello world !");
 
  Serial.print(a);
 
  Serial.print(b);
 
  delay(100);
 
}
 
  void requestEvent()
 
  {
 
      Wire.write(a);
 
      Wire.write(b);
 
  }
 
What’s wrong with it ? I’m confunsed about it .
« Last Edit: December 11, 2012, 09:14:53 am by Fortware » Logged

Global Moderator
Offline Offline
Brattain Member
*****
Karma: 502
Posts: 19080
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Please edit your post, select the code, and put it between [code] ... [/code] tags.

You can do that by hitting the # button above the posting area.


Read this:  http://www.gammon.com.au/i2c


Code:
void requestEvent()
  {
      Wire.write(a);
      Wire.write(b);
  }

Your double-spacing is very distracting. You aren't writing an essay.

Inside a request event you can only (successfully) do one write. If you want to write two bytes, do it as a single write, eg.

Code:
void requestEvent()
   {
   byte buf [2] = { a, b };
   Wire.write(buf, sizeof buf);
   }
Logged


Global Moderator
Offline Offline
Brattain Member
*****
Karma: 502
Posts: 19080
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
main_read:
 
#include <Wire.h>
 
byte x,y;
void setup()
{
    Wire.begin(1);

The master and slave should not have the same address. Each device on the I2C bus needs a different address. You have used 1 for both of them.
Logged


Pages: [1]   Go Up
Jump to: