Wildly incorrect Wire.requestFrom() results!

I’m getting radically inconsistent results using Wire.requestFrom()

EDIT: The master is a NodeMCU (ESP8266 based). I think that’s the problem. It seems to work fine with a Leonardo.

It seems to either pass the correct byte back to the master, or the master receives the value of the byte divided by 2 or 4. I haven’t found a consistent way to reproduce the bugs.

Everything else i2c works totally fine.

I made this test script to debug:

#include <Wire.h>

byte readbyte = 0;

void setup() {
  // put your setup code here, to run once:
  Wire.begin(D3, D4);
  Serial.begin(115200);
}

void loop() {
  Wire.requestFrom(12, 1);
  while (Wire.available()) {
    readbyte = byte(Wire.read());
    Serial.println(readbyte);
  }
  delay(100);
}
#include <Wire.h>

byte urmom = 255;

void setup() {
  // put your setup code here, to run once:
  Wire.begin(12);
  Wire.onRequest(requestEvent);
  Serial.begin(115200);
}

void loop() {

}

void requestEvent() {
  Wire.write(byte(40));
  Serial.println(urmom);
//  urmom++;
//  if (urmom == 255)
//    urmom = 0;
}

In the slave code, I tried using a byte variable, a constant byte, and a constant byte with the byte() function. I also tried incrementing a byte by one between each request.

It either sends the byte just fine, or the master receives the byte divided by 4 or 2, or the master receives the byte divided by either 4 but occasionally changes to dividing by two whille the program is running (or 2 to 4).

The results are not consistent.

What is going on here?!

So, it's sporadically losing a bit or two. I'd suggest that this might be something electrical - capacitance across the leads, or something like that.

Try using a different pin. Try using a different set of connecting leads. Try making i2c wire as short as possible. Fool with the value of the i2c pull-up resistor. Add a decouplng capacitor somewhere - I don't know that much about electronics, not sure where it would go. Make sure that both pieces of equipment have a common ground - bad soldering?

That kind of thing. Computers are deterministic, you aren't going to find the cause of an intermittent bug in the code. Well, not usually.