Send text string over i2c between two arduinos

Hi,

I've used the great help available all over the internet (mostly on this forum) to get this far, and have tweaked the code the best I can but there must still be something missing here.

I'm looking to send a string from one arduino to another arduino over i2c. The only way I've found of sending a text string is to send each character separately, and then compile this into a string in the "receiving" arduino.

Code I have so far is - for the sending arduino:

#include <Wire.h>

void setup()
{
  Wire.begin(4);                // join i2c bus with address #2

}

void loop()
{
  delay(100);
  sendMessage();
}



void sendMessage()
{
  Wire.beginTransmission(2);
  Wire.write("hello               "); 
                       
  delay(500);
}

And code so far for the "receiving" arduino is:

#include <Wire.h>

void setup()
{
  Wire.begin(2); 
  Serial.begin(9600);
  Wire.onReceive(receiveEvent); 
}

String data = "";

void loop()
{

}

void receiveEvent(int howMany)
{
  data = "";
  while( Wire.available()){
    data += (char)Wire.read();
    Serial.println(data);
  }
}

I'm not receiving the "hello" text in the serial monitor of the receiving Arduino.....any help appreciated. Thanks :slight_smile:

I'm not receiving the "hello" text in the serial monitor of the receiving Arduino

What are you getting? Our psychic was overworked and quit. Who can blame him?

I'm getting nothing in the serial monitor of the receiving unit. Blank screen.

So, print something in setup(), to confirm that the Arduino is working.

If nothing prints in the interrupt service routine, which is the wrong place to be using Serial.print(), it is likely that the ISR is not being called.

A schematic IS required.

The message in the transmitting sketch is not being sent. For the master, Wire.endTransmission() is the function which actually sends the message.

void sendMessage()
{
  Wire.beginTransmission(2);
  Wire.write("hello               "); 
  Wire.endTransmission(); //message buffer is sent with Wire.endTransmission()                   
  delay(500);
}

Everything will run better and smooth if the interrupt handlers are very short and fast. In the Slave in receiveEvent(), you use a String object and the Serial library. It is better to avoid both. Copy the data in a global (volatile) buffer and signal with a (volatile) flag that something is received. In the loop(), check for the flag.

volatile char buffer[40];
volatile boolean receiveFlag = false;

void receiveEvent(int howMany)
{
  Wire.readBytes(buffer, howMany);
  receiveFlag = true;
}