#include //include wire library
void setup() //this will run only once {
Wire.begin(); // join i2c bus as master
}
short age = 0;
void loop() {
Wire.beginTransmission(2);
// transmit to device #2
Wire.write("age is = ");
Wire.write(age); // sends one byte
Wire.endTransmission(); // stop transmitting
delay(1000);
}
#include //include wire library
void setup() { //this will run only once
Wire.begin(2); // join i2c bus with address #2
Wire.onReceive(receiveEvent); // call receiveEvent when the master send any thing
Serial.begin(9600); // start serial for output to print what we receive
}
void loop() {
delay(250);
}
//-----this function will execute whenever data is received from master-----//
void receiveEvent(int howMany) {
while (Wire.available()>1) // loop through all but the last {
char c = Wire.read(); // receive byte as a character
Serial.print(c); // print the character
}
}
#include //include wire library void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop() {
Wire.requestFrom(2, 1); // request 1 bytes from slave device #2
while (Wire.available()) // slave may send less than requested {
char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
}
delay(500);
}
从发射器
使用以下函数:
Wire.onRequest(处理程序) – 当主设备从此从设备请求数据时调用该函数。
示例
#include
void setup() {
Wire.begin(2); // join i2c bus with address #2
Wire.onRequest(requestEvent); // register event
}
Byte x = 0;
void loop() {
delay(100);
}
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
Wire.write(x); // respond with message of 1 bytes as expected by master
x++;
}