So I'm trying to read an 8-byte character string from an I2C device and print it to the serial console. This raw 8-char array is not terminated when it comes from the device, so I'm pretty sure I need to manually terminate it. Unfortunately, when I go to print the resultant string, the serial monitor just fills up with line breaks. Could someone take a look at this code and tell me where I went wrong?
uint8_t* HT_Controller::readMultiple(uint8_t reg, uint8_t num)
{
Wire.beginTransmission(i2cAddr);
Wire.write(reg);
Wire.endTransmission();
Wire.requestFrom(i2cAddr, num);
uint8_t* data = new uint8_t[num];
for(int i = 0; i < num; i++)
{
data[i] = Wire.read();
}
return data;
}
char* HT_Controller::getManufacturer()
{
uint8_t* data = readMultiple(REGISTER_MFR, NUM_MFR_BYTES); //Read the bytes from the controller
char* dataTerminated = new char[NUM_MFR_BYTES + 1]; //Our new array that will have a null char at the end
memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array
delete(data); //We're done with the original array, remove it from the heap
dataTerminated[NUM_MFR_BYTES] = 0; //Add that null char. NB: we don't need to '+1' the index because arrays start at 0, not 1
return dataTerminated;
}
And here's how it's used in the main sketch:
void loop()
{
char* data = mc1->getManufacturer();
Serial.println(data);
delete(data);
delay(500);
}