#include <Wire.h>
void setup() {
Wire.begin(0x50);
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
}
void receiveEvent(int howMany)
{
int n = Wire.available();
Serial.print("receiveEvent: ");
Serial.print(n);
Serial.print(" bytes: ");
while (Wire.available() > 0) { // loop through all but the last
int x = Wire.read(); // receive byte as a character
Serial.print(x); // print the character
Serial.print(",");
}
Serial.println();
}
void requestEvent()
{
Serial.print("requestEvent: ");
int n = Wire.write("hello "); // respond with message of 6 bytes
Serial.print(" wrote ");
Serial.print(n);
Serial.println(" bytes");
}
void loop() {
// put your main code here, to run repeatedly:
}
#include <Wire.h>
void setup() {
Wire.begin();
}
int loopcount = 0;
unsigned char b[4] = {0, 0, 0, 0};
void loop() {
Wire.beginTransmission(0x50);
Wire.write(0x00);
Wire.endTransmission(false);
Wire.requestFrom(0x50, 4);
int count = Wire.available();
for (int i = 0; i < count; i++) {
b[i] = Wire.read();
Serial.print(b[i], HEX);
if (i >= 3) break;
Serial.print(',');
}
Serial.println();
delay(2000);
if (++loopcount > 5) {
Serial.println("Write increment");
uint32_t n = (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
n = n + 1;
b[0] = n >> 24;
b[1] = n >> 16;
b[2] = n >> 8;
b[3] = n;
Wire.beginTransmission(0x50);
Wire.write(0x00);
for (int i = 0; i < 4; i++) {
Wire.write(b[i]);
}
Wire.endTransmission();
delay(2000);
loopcount = 0;
}
}
Yes, the API for slave mode is rather lacking; you have to take a punt on how many bytes to give to onRequest and there's no way to know how many get consumed. But that's a design problem with the Wire library.Just want to confirm I'm looking into this problem. I am able to reproduce it.
Also looks like the onRequest handler doesn't have any way to detect when the master size replies NAK to end the transfer.
if (status & LPI2C_SSR_SDF) { // Stopif (status & (LPI2C_SSR_SDF|LPI2C_SSR_RSF)) { // Stop or Repeat Start#include <Wire.h>
#include <EEPROM.h>
int address = 0;
void setup() {
Wire.begin(0x50);
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
}
void receiveEvent(int howMany)
{
int n = Wire.available();
Serial.print("receiveEvent: ");
Serial.print(n);
Serial.print(" bytes: ");
for (int i=0; i < n; i++) {
int x = Wire.read();
Serial.print(x);
Serial.print(",");
if (i == 0) {
address = x;
} else {
EEPROM.write(address, x);
address = address + 1;
}
}
Serial.println();
}
void requestEvent()
{
Serial.println("requestEvent: ");
// no way to know how much data is wants
for (int i=0; i < 16; i++) {
int x = EEPROM.read(address + i);
Wire.write(x);
}
// we don't get info about how many bytes
// actually sent, so no way to increment
// address by number actually read, as a
// real EEPROM chip does
}
void loop() {
}