I2C Raspberry Pi to Arduino with PHP

Hello

I am working on a project, where a I2C bus between a Raspberry Pi and a Arduino Micro is set up. The Raspberry Pi is the master, the Arduino is the slave. Communication on Raspberry Pi is done with PHP using this library. The code on Arduino looks like this:

#include <Wire.h>

void setup() {
  // Join I2C bus as slave with uniqe address
  Wire.begin(0x0b);
  // Call receiveEvent when data received                
  Wire.onReceive(receive_i2c_event);
}

void loop() {
}

void receive_i2c_event(int bytes){
  while(Wire.available() > 0){
    int c = Wire.read();
    Serial.println(c);
  }
}

The problem I am facing is the fact, that the PHP library first sends one Byte to the register, and then the rest of the Bytes. The Arduino receives everything in one stream and messes up the whole content. If I for example send this on the Raspberry Pi:

<?php
$fd = i2c_open("/dev/i2c-1");
i2c_select($fd, 0x0b);

$array = str_split("hello world");
foreach($array as $key => $char){
  $array[$key] = ord($char);
}

i2c_write($fd, 0, $array);
i2c_close($fd);
?>

... the Arduino obviously gets first the 0 and then the rest of the bytes (see php-i2c-extension/i2c.php at master · tasoftch/php-i2c-extension · GitHub). This is the output in the serial console:

09:17:09.096 -> 0
09:17:09.096 -> 104
09:17:09.096 -> 101
09:17:09.096 -> 108
09:17:09.096 -> 108
09:17:09.096 -> 111
09:17:09.096 -> 32
09:17:09.096 -> 119
09:17:09.096 -> 111
09:17:09.096 -> 114
09:17:09.096 -> 108
09:17:09.096 -> 100

My question is, how can I use the Wire library to tell the Arduino to use the first byte for the register and not being part of the string? Do I have to use a different lib?

Thanks, Stefan

You can't.
But what you can do is to write code in your receiver function that takes the first byte received and treat it differently.

I doubt you will find a library that will do that.

Hi @Grumpy_Mike , thanks!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.