Hello!
I have been experiencing a strange problem, and I'm wondering if anyone knows what's going on.
I am sending a value from an ATTiny84 to an Arduino Mega master over I2C. This value is one byte, and I only ever use 4 bits of that byte (it's a value from 0-15).
This is the function the Mega uses to ask for the data:
#include <Wire.h>
void setup() {
Wire.begin();
}
void loop() {
int currentTime = millis();
if (currentTime - prevTime >= 1000) {
ask();
prevTime = currentTime;
}
// put your main code here, to run repeatedly:
}
void ask() {
byte data;
Wire.requestFrom(0x6F, 1);
while (Wire.available()) {
data = Wire.read();
}
}
This is the function the Tiny uses to send the data it's asked for:
#define I2C_DEVICE_ADDRESS 0x6F // 111
#include <TinyWireS.h>
void setup() {
TinyWireS.begin(I2C_DEVICE_ADDRESS); //
TinyWireS.onRequest(requestEvent);
}
void requestEvent() {
byte data = [some binary number from 0-15];
TinyWireS.send(data);
}
void loop() {
TinyWireS_stop_check();
}
So far, so normal.
The weird part: If I send a single byte (such as 1001), it doesn't always arrive as intended. Sometimes it's truncated to 7 bits, sometimes it's mangled, sometimes it's both.
I did some testing (a lot of testing, but here's a small sample):
Test 1
Tiny sent: 10000000
Mega rec: 10000000
Test 2
Tiny sent: 11000000
Mega rec: 11000000
Test 3
Tiny sent: 10010001
Mega rec: 10010001
Test 4
Tiny sent: 00001111
Mega rec: 1001001
Test 5
Tiny sent: 11110000
Mega rec: 1110000
As you can see, transmissions 1-3 are fine. 4 arrived as 7 bits and a totally different value. 5 arrived as 7 bits and seems to be shifted left by 1. In testing these irregularities seem to be consistent.
I did eventually find a fix:Only use hex values. If I use hex values, there is no issue at all and everything works as expected; what the Tiny sends is what the Mega gets. I've also found that declaring device addresses as hex also means that the Tiny behaviour is much more reliable; declaring them as 7-bit binary numbers makes them inconsistent.
Does anyone have any insight as to why binary would be unreliable, but hex isn't? I'm curious, and I also wanted to leave this here in case anyone else is bewildered by this and goes looking for answers.
Thanks so much for any insight you can lend!