I have this simple setup to test I2C communication. Both resistors are 4.7K
The master send a byte every 100ms. I do get 0 for the result of the Wire.endTransmission()
The slave just says 'rec from wire' when the receive event fires. It works - but just one time. If I reset the slave it works one time. Anyone see what I a doing wrong?
Master Code:
#include <Wire.h>
unsigned long currentMillis;//time at the start of each loop
unsigned long lastWireTime = 0UL;
void setup()
{
Wire.begin(); //no address for master
}
void loop()
{
currentMillis = millis();
if(currentMillis - lastWireTime > 100UL){
lastWireTime = currentMillis;
Wire.beginTransmission(2);
Wire.write(1);
byte res = Wire.endTransmission();//sends the buffer - return of 0 = success
}
}
Try these sketches (tested between UNO and MEGA): Master Codes:
#include <Wire.h>
unsigned long currentMillis;//time at the start of each loop
unsigned long lastWireTime = 0UL;
void setup()
{
Serial.begin(9600);
Wire.begin(); //no address for master
// Serial.print("OK");
}
void loop()
{
//currentMillis = millis();
if (millis() - lastWireTime >= 1000UL)
{
lastWireTime = millis();
Wire.beginTransmission(2);
Wire.write(1);
byte res = Wire.endTransmission();//sends the buffer - return of 0 = success
if (res != 0)
{
Serial.print("I2C Bus Communication Problem...!");
while (1); //wait for ever
}
else
{
Serial.println("Slave Found on I2C Bus.");
}
}
}
Thank you. Why comment out the println's though - I mean how do you know it's working otherwise? I got it working by changing the while(1 < Wire.available()) to while(Wire.available() > 0)
However, I'm don't really understand why it works now. I realize it's doing the Wire.read() now though, but I didn't know it had to. That's why I had the first println outside of the while loop. Does whatever is sent NEED to be read, otherwise the slave is not freed up?