I2C bus not working on Nucleo boards

Hey there! I have a strange problem with the I2C bus, no matter which Nucleo board I use (I have the F446RE and the L432KC).

I tried the following I2C Scanner:

#include "mbed.h"

#define I2C1_SDA PB_9
#define I2C1_SCL PB_8

I2C i2c1(I2C1_SDA, I2C1_SCL);

int ack = 1;

int main()
{
  debug("...................:[ I2C Scanner ]:...................\n\r");
  while (true)
  {
debug("Scanning I2C Interface ...\r\n");
  for(int address = 1; address < 127; address++)
  {
    ack = i2c1.write(address, "11", 1);
    if (ack == 0)
      debug("\tFound device at %3d -- %3x\r\n", address,address);
    ThisThread::sleep_for(10ms);
  }
debug("Scan finished.\r\n");
ThisThread::sleep_for(1s);
  }
}

Unfortunately, none of my I2C devices are discovered and I don’t know why. I checked the wiring again and again, I made sure I have proper resistors (using 2k8) and I used an oscilloscope to make sure, that at least there is something coming out of my microcontroller (yes, I can see how addresses are scanned). Everything seems fine on the hardware side of things, so is there something wrong with my code?

Greetings!

Edit: Above code is for the Nucleo F446RE; the L432KC uses different pins for its I2C1 interface of course.

Hello,

The Arm Mbed API uses 8 bit addresses, so make sure to left-shift 7 bit addresses by 1 bit before passing them:

...
for(int address = 1; address < 127; address++) {
    ack = i2c1.write(address << 1, "11", 1);
...
1 Like

Just FYI, my i2cdetect code is here:

Thank you @hudakz for helping me with such a stupid error. I don’t know why it did not read that note. :frowning:

Also thank you @MACRUM for your I2C scanner example.

Anyway… Looking at the API documentation I noticed something weird…:

int write (int address, const char *data, int length, bool repeated=false) will return 0 on success (ack) and nonzero on failure (nack). However, int write ( int data ) will return 1 on success (ack), 0 on failure (nack) and 2 on timeout.

Is there a reason for this? It seems unconsistent to me but I might not have the full picture.

You know, this has always bothered me…

1 Like

Ah, good to know. :grinning_face_with_smiling_eyes:

Also… could it be that int read ( int ack ) is not implemented yet? :roll_eyes:

Hello,

why do you mean?

BR, Jan