The TWI devices are working with the UNO, but they are not working with Mega. Arduino Mega is being suspected to contain a malfunctioning TWI Interface. The execution of the following codes may reveal if the TWI Interface is really bad! We assume that the Arduino Mega contains built-in pull-up for the TWI Bus and all TWI devices are disconnected from the TWI Bus. (These codes work for the UNO.)
void setup()
{
pinMode(13, OUTPUT);
Serial.begin(9600);
TWBR = 0x02;
TWSR = 0x02; //200 KHz speed
TWCR = 0b10100100;
while (bitRead(TWCR, 7) !=HIGH)
;
Serial.print((TWSR & 0b11111000), HEX); //shows status code: 0x08
}
void loop()
{
digitalWrite(13, !digitalRead(13));
delay(2000);
}
Having received the status code (0x08), we may proceed to receive the next status code (0x18) by connecting only the mcp4531 in the bus and issuing the following commands (untested):
START command //correct status code: 0x08
(codes are similar to above)
//deviceaddress inquiry in Write Mode correct status code: 0x18
//codes to be executed are:
TWDR = 0bXXXXXXX0; //XXXXXXX are 7-bit Pot address
TWCR = 0b10000100; //needed to generate clock pulses
while(bitRead(TWCR, 7) !=HIGH);
;
Serial.print((TWSR & 0b11111000), HEX); //Serial Monitor should show: 0x18
STOP command
TWCR = 0b10010100;