Simple I2C setup only works when serial monitor is open

I was troubleshooting a more complex setup that I simplified it to this. I have a teensy 4.1 connected to an ESP32 devkitC with 2k2 pull-up resisters to 3.3v on the two I2C lines. It's working fine IF the serial monitor in the Arduino IDE for the teensy is open. Opening the serial monitor on the ESP32 has no impact. I don't even have to print anything. I'm watching the two lines with a scope. As soon as I open the serial monitor, I2C starts working. I must be missing something basic. Any ideas?

//I2C Master - teensy 4.1
#include <Wire.h>

void setup() {
  Wire.begin();  // join i2c bus as master
  Serial.begin(115200);
  while (!Serial);
}

void loop() {
    Wire.beginTransmission(9);  // transmit to device 
    Wire.write("123"); 
    Wire.endTransmission();     // stop transmitting
    delay(100);
    //Serial.println("loop");
}

// ESP32 Slave
#include <Wire.h>
char receivedChars[4]; // Array to hold received characters. One extra for null-terminator.
volatile bool i2c_marker = false;

void setup() {
  Serial.begin(115200);
  while (!Serial);

  Wire.begin(9); //slave address 9
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int bytes) {
  int i = 0;
  while (Wire.available() && i < 3) {
    receivedChars[i] = Wire.read();  // Read I2C into character array
    i++;
  }
  receivedChars[i] = '\0'; // Null-terminate the string
  i2c_marker = true;
}

void loop() {
  if (i2c_marker) {
    //Serial.println(receivedChars); // Print the received string
    memset(receivedChars, 0, sizeof(receivedChars)); // Clear the array
    i2c_marker = false;
  }
}

That's the explanation.

Perhaps this is where your code hangs?

Does the Teensy really require that hack?

Yes! Thank you!

It was blocking. I thought it was used to wait until Serial was ready. I was wrong! Working great now!

It does wait for the Serial that You didn't provide/connect.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.