Go Down

Topic: I2C doesn't seem to work correctly (Read 910 times) previous topic - next topic

jameselder232

Hi, I have two Arduino nano board connected via an I2C connection on analog pins 4 and 5 with 4.8k pull up resistors connected to the 5V rail. Now i am using some simple code to send a character string between the two Arduinos:

Slave:
Code: [Select]
#include <SPI.h>
#include <SoftwareSerial.h>
#include <Wire.h>

void setup() {
       Serial.begin(4800);
       Wire.begin(2); //Establish the device on the I2C network as slave (Address 2)
}
 
void loop()
{
 Serial.println("Writing Data");
 Wire.write("Hello"); //Write data to the buffer for transmission
}


Master:
Code: [Select]
#include <SPI.h>
#include <SoftwareSerial.h>
#include <Wire.h>                      
                       
void setup()
{
         
Serial.begin(4800);
       Wire.begin(); //Establish the device on the I2C network as master (Slave Address 2)
}
char data[5];
char c;
int j;
void loop()
{
                       Serial.println("Requesting Data");
                       Wire.requestFrom(2, 5); //Request 5 bytes from address 2
                       j = 0;
                       Serial.println("Reading Data");
                       while(Wire.available())
                       {
                         c = Wire.read();
                         Serial.println(c);
                       }
}


The output is as follows:

Requesting Data
Reading Data

ÿ
ÿ
ÿ
ÿ

Nick Gammon

You can't just have Wire.write on its own. You need a Wire.beginTransmission and Wire.endTransmission.

Take a look a this:

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

There are examples there of communicating between two devices.

jameselder232

Apparently you only need wire.begin and wire.end if you are sending master->slave messages which I'm not. That's why the wire.begin function takes an address. The master node does not have an address so i can't use the wire.begin function... Can someone confirm this?

CrossRoads

You need Wire.beginTransmission();

an address is not needed for the master but the command is.
Designing & building electrical circuits for over 25 years. Check out the ATMega1284P based Bobuino and other '328P & '1284P creations & offerings at  www.crossroadsfencing.com/BobuinoRev17.
Arduino for Teens available at Amazon.com.

Grumpy_Mike

Quote
Can someone confirm this?

I can confirm that it is rubbish if that helps.

Go Up