Wire Library rxBuffer overflow

Status
Not open for further replies.

trash80

Member
Hello! I think I may have found a bug in Wire.cpp, though it could be a mistake on my end- after debugging and a slight modification to Wire.cpp it seems to fix the issue.

I am using a large amount of RAM on the Teensy 3.1 and when trying to use the Wire library with Adafruit_MCP23017 the Teensy hangs. Interestingly I'm using the up to date Platformio for compilation, and when testing in the Arduino IDE, it works fine. Even ended up copying over the Teensy Library files to make sure everything matched between Platformio and Arduino.

The issue seems to be from the TwoWire::requestFrom method:
Code:
	while (length > 1) {
		i2c_wait();
		length--;
		if (length == 1) I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TXAK;
		rxBuffer[count++] = I2C0_D;
	}
	i2c_wait();
	I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
	rxBuffer[count++] = I2C0_D;
	if (sendStop) I2C0_C1 = I2C_C1_IICEN;
	rxBufferLength = count;
	return count;

When I add in a condition to the count variable via "if(count >= BUFFER_LENGTH) count = 0;" before writing to rxBuffer everything works as expected. Though looking at it there is no reason for count to get so high that it overflows. Since it doesn't happen in the Arduino IDE, I suspect something strange is happening when the code is compiled in Platformio. (Different version of GCC? No idea.)

Here is the test code I was working with:
Code:
#include <Wire.h>
#include "Adafruit_MCP23017.h"

Adafruit_MCP23017 mcp;

uint8_t some_big_data[50000];


void setup() {
  pinMode(13,OUTPUT);
  digitalWrite(13, HIGH);
  delay(300);
  digitalWrite(13, LOW);
  delay(300);

  Serial1.begin(9600);

  Serial1.println(some_big_data[0]);

  mcp.begin();
  mcp.pinMode(0, INPUT);
  mcp.pullUp(0, HIGH);
  mcp.pinMode(1, INPUT);
  mcp.pullUp(1, HIGH);

}

void loop() {
  digitalWrite(13, LOW);
  delay(300);
  digitalWrite(13, HIGH);
  delay(300);
}
 
Yeah it looks like some sort of compiler issue. If I just declare the rxBuffer in TwoWire as volatile, that also fixes the issue without needing the if statement- it effectively does nothing anyway.
 
Thanks. Yeah, seems to work fine there. Suspect it's the build process (though it's almost identical) or the version of GCC ARM. :( Unfortunately the Arduino IDE is pretty tedious for large projects. Gah!
 
You can turn on "Use External Editor" in File > Preferences.

For the upcoming 1.6.6 release, the Arduino devs are moving the build system to its own native, not-Java application. Maybe that will help some people, maybe not?
 
Status
Not open for further replies.
Back
Top