In AndersSkibsted code the recieveEvents function might not be called because it has the wrong prototype. The Wire.onRecieve takes a function with no return (ie. void) that takes a single int parameter. see https://www.arduino.cc/en/Reference/WireOnReceive I would have though the compiler would give an error.

You might receive data in one big chunk or a byte at a time…or even no data at all. That is why the receiveEvent has a count argument. You should handle the possibilities that count could be 0,1 or any positive number.

The databuf is a area of memory set aside for pulling data from the i2c. The memset sets the databuf to contain only 0’s. The size of the data buffer is 256 bytes. You should make sure your code cannot write more than that into the buffer.

The example above has a few problems. In receiveEvent, it should call “received += count” instead of “received = count” since the receiveEvent could be called more that once before the loop() gets a chance to execute. Also it should check that count is less that MEM_LEN to make sure it doesn’t write off the end of the buffer.

1 Like