Im trying to write to a register and then see if it actually wrote anything .When I try the snippet below I just get three 0's in the serial monitor. is the code below correct for write and read?It seems the write or read isnt working or both.
Wire.begin();
Wire.beginTransmission(0x10); // address
Wire.write(0x07); // register to write to
Wire.write(0b10000001); // bits to set
delay(500);
int result0=Wire.endTransmission();
Serial.println(result0);
Wire.beginTransmission(0x10); // address
Wire.write(0x07); // register to read
int result1=Wire.endTransmission(false);
Serial.println(result1);
Wire.requestFrom(0x10,1); // register to read from
byte a=Wire.read();
Serial.println(a);
Connect two Arduinos together using I2C Bus and GND line; after that, upload the following sketches to see that data byte 0x13 has arrived from Slave to the Serial Monitor of Master.
Master Codes:
#include<Wire.h>
void setup()
{
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(0x10); // address
Wire.write(0x07); // register to write to
//Wire.write(0b10000001); // bits to set
//delay(500);
byte result0=Wire.endTransmission();
if(result0 !=0)
{
Serial.println("Slave is not found...!);
while(1); //wait for ever
}
Wire.requestFrom(0x10,1); // register to read from
byte a=Wire.read();
Serial.println(a); //Serial Monitor shows: 13 that comes from Slave
}
void loop()
{
}
Slave Codes:
#include<Wire.h>
volatile bool flag = false
void setup()
{
Serial.begin(9600);
Wire.begin(0x10);
Wire.onReceive(receiveEvent);
Wire.onRequest(sendEvent);
}
void loop()
{
}
void receiveEvent(int howMany)
{
byte x = Wire.read();
if(x == 7)
{
flag = true;
}
}
void sendEvent()
{
if(flag == true)
{
Wire.write(0x13);
flag = false);
}
}
using your code I get a 19 (0x13) back from slave.