I2C Slave

Hi!

I’m developing an I2C Master with my fpga and i want to use my arduino like it was an slave.

// This example code is in the public domain.


#include <Wire.h>

void setup()
{
  Wire.begin(4);                // join i2c bus with address #1
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop()
{
  delay(1000);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
  while(1 < Wire.available()) // loop through all but the last
  {
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  Serial.print(" ");
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x,BIN);         // print the integer
}

I’m using this code, but i’m very noob with wire.h. I want to print in serial screen 03 03 c3 three byte as you can see in trama.png but i only get 11 or 3 in HEX

any advices?

trama.png

salida1.png

Don't print to the serial interface in interrupt context. receiveEvent is called in interrupt context, so you have to store the data and print it in the main loop.
Why do you think anything should be printed in HEX if you don't tell the system so in the sketch? 3 is 11 in binary.

small remarks

Wire.begin(4); // join i2c bus with address #1
comments is out of sync ...
less comment is often better
Wire.begin(4); // join i2c

Serial.begin(9600);
why not
Serial.begin(115200); // 12x faster

Use a buffer and a flag and use the data in the loop().
There is no need to test the available bytes, the ‘howMany’ has already that number.
Why do you read an extra byte, that is confusing and a coding error is easily made.

// This example code is in the public domain. It is not even tested !

#include <Wire.h>

volatile byte buffer[16];
volatile boolean gotMail = false;


void setup()
{
  Serial.begin(9600);           // start serial for output

  Wire.begin(4);                // join i2c bus
  Wire.onReceive(receiveEvent); // register event
}

void loop()
{
  if (gotMail)
  {
    for (int i=0; i<16; i++)
    {
      Serial.print(buffer[i], HEX);
      Serial.print(", ");
    }
    Serial.println();
    gotMail = false;
  }

  // no delay needed
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
  // Would Wire.readBytes(buffer, howMany); also work ? I don't know.

  for (int i=0; i<howMany && i<16; i++)
  {
    buffer[i] = Wire.read(); // receive byte as a character
  }
  gotMail = true;
}

The number of received bytes should also be passed on to the loop().
During the printing of the buffer, new data could arrive. So two buffers are needed and the interrupts should be disabled while copying the data.

Thanks guys!
I tried it with flags and buffers and i got response.