简体   繁体   中英

Sending 0x00 using I2C

I am using the Wire class to have two Arduino Unos communicate using I2C. It seems that the Wire class ends transmission on a value of 0. So if I send bytes 0x01, 0x02, 0x00, and 0x04, the master receives: 0x01, 0x02, 0xFF, 0xFF.

It seems odd that a communication network designed for processor communication cannot send a 0x00. All the examples for I2C that I have seen use ASCII only. Inter-processor communication restricted to ASCII does not seem to make any sense. Am I missing something with I2C or is this just an implementation limitation of the Arduino Wire class?

Master

void loop() {
  Wire.requestFrom(2, 4); 

  while(Wire.available()) { 
    byte b = (byte) Wire.read(); 
    Serial.println(b); 
  }

  delay(1000);
}

Slave

void requestEvent() {
  char bytes[4] = {0x01,0x02,0x00,0x04};
  Wire.write(bytes);
}

The results are: 1 2 255 255.

When that 0x00 was 0x03 I got the expected: 1 2 3 4.

You are passing an array of char s to Wire.write() ... This makes Wire treat the argument as a null-terminated string, and therefore the NULL byte terminates the transmission. If you want to send byte s, call the write() function once for each byte, passing it byte types.

Alternatively, you can call the write(const uint8_t *, size_t); version: you pass it a pointer to / array of bytes, but you also have to give it a size of your data array.

在调用Wire.write()之前,是否发生了Wire.begin()和Wire.beginTransmission()(具有正确的地址)的发生?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM