7 years, 5 months ago.

I2Cslave with null Byte in data leads to incorrect data

I have programmed the LPC1768 as an I2C slave sensor simulator. If it is asked by the I2C master it should answer with four Bytes of data. In general it works fine as far as non of the four Bytes is 0x00.

e.g. msg[0]= 0x5F; msg[1]= 0x01; msg[2]= 0x32; msg[3]= 0x6D;

while(1) { int i = sensor1.receive(); switch (i) { case I2CSlave::ReadAddressed: sensor1.write(msg, strlen(msg) + 1); Includes null char break; ## master gets "5F 01 32 6D" , all fine

but if I change msg[1] = 0x00;

master get "5F 00 FF FF" (same on scope, so master is correct.

Can anybody explain that behaviour?

1 Answer

7 years, 5 months ago.

It might be because you expect strlen(msg) to always return 4 in your case.

After all, you DID define msg [4], right?

But, that's not how strlen() works!

It starts scanning at msg[0] and returns the number of NONZERO bytes.

For example, if msg[0] is 0x5f and msg[1] is 0, strlen(msg) will return 1.

Accepted Answer

You are absolutely correct! I replaced strlen(msg) by 4 an now it works fine. Thanks for your answer. Regards Michael

posted by Michael Balling 08 Jun 2017