Slave transmitter I2C

From Pinguino
Jump to: navigation, search

Example for functions: Wire.begin Wire.onReceive Wire.onRequest Wire.available Wire.read Wire.writeStr

void receiveEvent(u8);
void requestEvent(void);
void fillmessage(u8 *, u8 *);

u8 I2C_address = 0x2C; //slave address

void setup() {
  Wire.begin(I2C_address,0); // the second parameter (0) is not used in the present slave mode    
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent); // register event
  delay(100);
}

void loop() {
}
void receiveEvent(u8 count)
{
u8 rxbuffer[2];
u8 i;
  i=0;
  while(Wire.available())
    rxbuffer[i++] = Wire.read(); 
}
void requestEvent()
{
u8 txbuffer[32];
u8 message[] ="hi!?"; // this is a simple example
  fillmessage(message,txbuffer);
  Wire.writeStr(txbuffer);
}

void fillmessage(u8 *tosend, u8 *buff)
{
//This function might be more complicated to send text + numbers (rcv codified)
u8 i = 0;
  while (tosend[i] != '\0')
  {
    buff[i] = tosend[i];
    ++i;
  }
  buff[i] = tosend[i];
}