-
-
Save rwaldron/616e95b7c2637ebd21c5 to your computer and use it in GitHub Desktop.
#include <Wire.h> | |
byte i2cdata[4]; | |
void setup() { | |
Wire.begin(); | |
Serial.begin(9600); | |
} | |
void loop() { | |
Wire.requestFrom(4, 4); | |
int a = Wire.available(); | |
Serial.print("Available: "); | |
Serial.println(a); | |
// Both of these produce the same result | |
// for (int i = 0; i < a; i++) { | |
// Serial.print(Wire.read()); | |
// Serial.print(" "); | |
// } | |
while (Wire.available()) { | |
Serial.print(Wire.read()); | |
Serial.print(" "); | |
} | |
Serial.println(); | |
memset(&i2cdata, 0, 4); | |
delay(500); | |
} |
#include <Wire.h> | |
int address = 4; | |
void setup() { | |
Wire.begin(address); | |
Wire.onRequest(onRequest); | |
} | |
void loop() {} | |
void onRequest() { | |
byte buffer[4] = {1, 2, 3, 4}; | |
Wire.write(buffer, 4); | |
} | |
/* | |
When this sketch is running on the slave, the output of the master is: | |
Available: 4 | |
1 2 3 4 | |
... | |
*/ |
#include <Wire.h> | |
int address = 4; | |
void setup() { | |
Wire.begin(address); | |
Wire.onRequest(onRequest); | |
} | |
void loop() {} | |
void onRequest() { | |
for (int i = 1; i < 5; i++) { | |
Wire.write(i); | |
} | |
} | |
/* | |
When this sketch is running on the slave, the output of the master is: | |
Available: 4 | |
4 255 255 255 | |
... | |
*/ |
TinyWireS most likely works with multiple calls to send because it's a different library with a different implementation than Arduino's Wire library.
Looking into this further, it may be a bug (or perhaps an oversight) in the Arduino Wire code. When you send a single byte with Wire.write, twi_transmit is called with the byte sent and a length of 1. This data is then copied into the twi_txBuffer array, but since the length is 1 each time Wire.write is called, the buffer is overwritten on each call rather than the next byte being added to the next index in twi_txBuffer. May or may not be intentional by design.
Thanks for the details :)
Sounds like TinyWireS probably needs an update to bring things in line with this behaviour. I noticed there were a lot of branches doing different things so there's been a lot of fragmentation.
@ajfisher have you tried this I2C library that Adafruit made for the Trinket? https://github.com/adafruit/TinyWireM
actually it looks like TinyWireM only implements I2C master
If you use Wire.write in the slave to send only a single value, then in the master you can only request a single byte:
Wire.requestFrom(4, 1)
. Basically you can only call Wire.write once in the slave per request from the master. If you have to send multiple bytes you need to send an array.